Git Product home page Git Product logo

jhipster5-demo's Introduction

Get Started with JHipster 5

This article shows you how to build a simple blog application with JHipster 5.0.1. You can also watch a video of this tutorial on YouTube.

💡
It appears you’re reading this document on GitHub. If you want a prettier view, install Asciidoctor.js Live Preview for Chrome, then view the raw document. Another option is to use the DocGist view.
Source Code

If you’d like to get right to it, the source code for this application is on GitHub. To run the app, use yarn && yarn webpack:build && ./mvnw. To test it, run ./mvnw test. To run its end-to-end tests, run ./mvnw in one terminal and yarn e2e in another.

What is JHipster?

JHipster is one of those open-source projects you stumble upon and immediately think, “Of course!” It combines three very successful frameworks in web development: Bootstrap, Angular, and Spring Boot. Bootstrap was one of the first dominant web-component frameworks. Its most substantial appeal was that it only required a bit of HTML and it worked! All the efforts we made in the Java community to develop web components were shown a better path by Bootstrap. It leveled the playing field in HTML/CSS development, much like Apple’s Human Interface Guidelines did for iOS apps.

Julien Dubois started JHipster in October 2013 (Julien’s first commit was on October 21, 2013). The first public release (version 0.3.1) launched on December 7, 2013. Since then, the project has had over 170 releases! It is an open-source, Apache 2.0-licensed project on GitHub. It has a core team of 17 developers and over 420 contributors. You can find its homepage at www.jhipster.tech. If you look at the project on GitHub, you can see it’s mostly written in JavaScript (33%) and Java (27%).

At its core, JHipster is a Yeoman generator. Yeoman is a code generator that you run with a yo command to generate complete applications or useful pieces of an application. Yeoman generators promote what the Yeoman team calls the “Yeoman workflow”. This workflow is an opinionated client-side stack of tools that can help developers quickly build beautiful web applications. It takes care of providing everything needed to get working without the normal pains associated with a manual setup.

JHipster 5 is the same JHipster many developers know and love, with a couple of bright and shiny new features: namely React, Angular 6, and Spring Boot 2 support.

Install JHipster 5

The Installing JHipster instructions show you all the tools you’ll need to use a released version of JHipster.

  1. Install Java 8 from Oracle.

  2. Install Git from https://git-scm.com.

  3. Install Node.js from http://nodejs.org. JHipster recommends using a LTS release.

  4. Install Yarn using the Yarn installation instructions.

  5. Run the following command to install JHipster.

    yarn global add [email protected]
📎
If you’re using npm, run npm i -g --save-exact [email protected].

Create a Project

To create a project, open a terminal window and create a directory. For example, mkdir blog. Navigate into the directory and run jhipster. You’ll be prompted to answer a number of questions about the type of application you want to create and what features you’d like to include. The screenshot below shows the choices I made to create a simple blog application with Angular.

Generating the application
Figure 1. Generating the application

If you’d like to create the same application I did, you can place the following .yo-rc.json file in an empty directory and run jhipster in it. You won’t be prompted to answer any questions because the answers are already in .yo-rc.json.

{
  "generator-jhipster": {
    "promptValues": {
      "packageName": "org.jhipster.blog",
      "nativeLanguage": "en"
    },
    "jhipsterVersion": "5.0.1",
    "applicationType": "monolith",
    "baseName": "blog",
    "packageName": "org.jhipster.blog",
    "packageFolder": "org/jhipster/blog",
    "serverPort": "8080",
    "authenticationType": "jwt",
    "cacheProvider": "ehcache",
    "enableHibernateCache": true,
    "websocket": false,
    "databaseType": "sql",
    "devDatabaseType": "h2Disk",
    "prodDatabaseType": "postgresql",
    "searchEngine": false,
    "messageBroker": false,
    "serviceDiscoveryType": false,
    "buildTool": "maven",
    "enableSwaggerCodegen": false,
    "jwtSecretKey": "455e1315207269bf7ba9685bdba93b4ff0224ba0",
    "clientFramework": "angularX",
    "useSass": false,
    "clientPackageManager": "yarn",
    "testFrameworks": [
      "protractor"
    ],
    "jhiPrefix": "jhi",
    "enableTranslation": true,
    "nativeLanguage": "en",
    "languages": [
      "en",
      "es"
    ]
  }
}
💡
What about React? If you’d like to see how to use JHipster 5 to build a React + OAuth 2.0 / OIDC app, see Build a Photo Gallery PWA with React, Spring Boot, and JHipster.

The project creation process will take a couple of minutes to run, depending on your internet connection speed. When it’s finished, you should see output like the following.

Generation success
Figure 2. Generation success

Run ./mvnw to start the application and navigate to http://localhost:8080 in your favorite browser. The first thing you’ll notice is a dapper-looking fellow explaining how you can sign in or register.

Default homepage
Figure 3. Default homepage

Sign in with username admin and password admin, and you’ll have access to navigate through the Administration section. This section offers nice looking UIs on top of some Spring Boot’s many monitoring and configuration features. It also allows you to administer users:

User management
Figure 4. User management

It gives you insights into Application and JVM metrics:

Application and JVM Metrics
Figure 5. Application metrics

And it allows you to see the Swagger docs associated with its API.

Swagger UI
Figure 6. Swagger docs

You can run the following command (in a separate terminal window) to run the Protractor tests and confirm everything is working correctly.

yarn e2e

Generate Entities

For each entity you want to create, you will need:

  • a database table;

  • a Liquibase change set;

  • a JPA entity class;

  • a Spring Data JpaRepository interface;

  • a Spring MVC RestController class;

  • an Angular model, state, component, dialog components, service; and

  • several HTML pages for each component.

Also, you should have integration tests to verify that everything works and performance tests to confirm that it runs fast. In an ideal world, you’d also have unit tests and integration tests for your Angular code.

The good news is JHipster can generate all of this code for you, including integration tests and performance tests. Also, if you have entities with relationships, it will create the necessary schema to support them (with foreign keys), and the TypeScript and HTML code to manage them. You can also set up validation to require certain fields as well as control their length.

JHipster supports several methods of code generation. The first uses its entity sub-generator. The entity sub-generator is a command-line tool that prompts you with questions which you answer.

JDL-Studio is a browser-based tool for defining your domain model with JHipster Domain Language (JDL). Finally, JHipster-UML is an option for those that like UML. Supported UML editors include Modelio, UML Designer, GenMyModel and Visual Paradigm. I like the visual nature of JDL-Studio, so I’ll use it for this project.

Below is the entity diagram and JDL code needed to generate a simple blog with blogs, entries, and tags.

Blog entity diagram
Figure 7. Blog entity diagram
💡
You can find a few other JDL samples on GitHub.

If you’d like to follow along, copy/paste the contents of the file below into JDL-Studio.

blog.jh
entity Blog {
    name String required minlength(3),
    handle String required minlength(2)
}

entity Entry {
    title String required,
    content TextBlob required,
    date Instant required
}

entity Tag {
    name String required minlength(2)
}

relationship ManyToOne {
    Blog{user(login)} to User,
    Entry{blog(name)} to Blog
}

relationship ManyToMany {
    Entry{tag(name)} to Tag{entry}
}

paginate Entry, Tag with infinite-scroll

Click the download button in the top right corner to save it to your hard drive. Run the following command (in the blog directory) to import this file and generate entities, tests, and a UI.

jhipster import-jdl ~/Downloads/jhipster-jdl.jh

You’ll be prompted to overwrite src/main/resources/config/liquibase/master.xml. Type a to overwrite this file, as well as others.

Restart the application with /.mvnw and run yarn start to view the UI for the generated entities. Create a couple of blogs for the existing admin and user users, as well as a few blog entries.

💡
You don’t have to run yarn start, but doing so allows you to change your UI files and see the results immediately.
Blogs
Figure 8. Blogs
Entries
Figure 9. Entries

From these screenshots, you can see that users can see each other’s data, and modify it.

Add Business Logic

💡
To configure an IDE with your JHipster project, see Configuring your IDE. Instructions exist for Eclipse, IntelliJ IDEA, Visual Studio Code, and NetBeans.

To add more security around blogs and entries, open BlogResource.java and find the getAllBlogs() method. Change the following line:

src/main/java/org/jhipster/blog/web/rest/BlogResource.java
return blogRepository.findAll();

To:

src/main/java/org/jhipster/blog/web/rest/BlogResource.java
return blogRepository.findByUserIsCurrentUser();

The findByUserIsCurrentUser() method is generated by JHipster in the BlogRepository class and allows limiting results by the current user.

src/main/java/org/jhipster/blog/repository/BlogRepository.java
public interface BlogRepository extends JpaRepository<Blog, Long> {

    @Query("select blog from Blog blog where blog.user.login = ?#{principal.username}")
    List<Blog> findByUserIsCurrentUser();

}

After making this change, re-compiling BlogResource should trigger a restart of the application thanks to Spring Boot’s Developer tools. If you navigate to http://localhost:9000/blogs, you should only see the blog for the current user.

Admin’s blog
Figure 10. Admin’s blog

To add this same logic for entries, open EntryResource.java and find the getAllEntries() method. Change the following line:

src/main/java/org/jhipster/blog/web/rest/EntryResource.java
Page<Entry> page = entryRepository.findAll(pageable);

To:

src/main/java/org/jhipster/blog/web/rest/EntryResource.java
Page<Entry> page = entryRepository.findByBlogUserLoginOrderByDateDesc(SecurityUtils.getCurrentUserLogin().orElse(null), pageable);

Using your IDE, create this method in the EntryRepository class. It should look as follows:

src/main/java/org/jhipster/blog/repository/EntryRepository.java
Page<Entry> findByBlogUserLoginOrderByDateDesc(String currentUserLogin, Pageable pageable);

Recompile both changed classes and verify that the user user only sees the entries you created for them.

User’s entries
Figure 11. User’s entries

You might notice that this application doesn’t look like a blog and it doesn’t allow HTML in the content field.

Make UI Enhancements

When doing UI development on a JHipster-generated application, it’s nice to see your changes as soon as you save a file. JHipster uses Browsersync and webpack to power this feature. You enable this previously by running the following command in the blog directory.

yarn start

In this section, you’ll change the following:

  1. Change the rendered content field to display HTML

  2. Change the list of entries to look like a blog

Allow HTML

If you enter HTML in the content field of a blog entry, you’ll notice it’s escaped on the list screen.

Escaped HTML
Figure 12. Escaped HTML

To change this behavior, open entry.component.html and change the following line:

src/main/webapp/app/entities/entry/entry.component.html
<td>{{entry.content}}</td>

To:

src/main/webapp/app/entities/entry/entry.component.html
<td [innerHTML]="entry.content"></td>

After making this change, you’ll see that the HTML is no longer escaped.

Escaped HTML
Figure 13. HTML in entries

Improve the layout

To make the list of entries look like a blog, replace <div class="table-responsive"> with HTML, so it uses a stacked layout in a single column.

src/main/webapp/app/entities/entry/entry.component.html
<div class="table-responsive" *ngIf="entries">
    <div infinite-scroll (scrolled)="loadPage(page + 1)" [infiniteScrollDisabled]="page >= links['last']" [infiniteScrollDistance]="0">
        <div *ngFor="let entry of entries; trackBy: trackId">
            <h2>{{entry.title}}</h2>
            <small>Posted on {{entry.date | date: 'short'}} by {{entry.blog.user.login}}</small>
            <div [innerHTML]="entry.content"></div>
            <div class="btn-group mb-2 mt-1">
                <button type="submit"
                        [routerLink]="['/entry', entry.id, 'edit']"
                        class="btn btn-primary btn-sm">
                    <fa-icon [icon]="'pencil-alt'"></fa-icon>
                    <span class="d-none d-md-inline" jhiTranslate="entity.action.edit">Edit</span>
                </button>
                <button type="submit"
                        [routerLink]="['/', { outlets: { popup: 'entry/'+ entry.id + '/delete'} }]"
                        replaceUrl="true"
                        queryParamsHandling="merge"
                        class="btn btn-danger btn-sm">
                    <fa-icon [icon]="'times'"></fa-icon>
                    <span class="d-none d-md-inline" jhiTranslate="entity.action.delete">Delete</span>
                </button>
            </div>
        </div>
    </div>
</div>

Now it looks more like a regular blog!

Blog entries
Figure 14. Blog entries

Lock It Down!

You can further enhanced the security of your API by only allowing users that own a blog (or entry) to edit it. Here’s some sudo-code to show the logic:

Optional<Blog> blog = blogRepository.findById(id);
if (blog.isPresent() && <user doesn't match current user>) {
    return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
}
return ResponseUtil.wrapOrNotFound(blog);

Below is the refactored BlogResource.java with additional logic in each method to prevent data tampering.

src/main/java/org/jhipster/blog/web/rest/BlogResource.java
@PostMapping("/blogs")
@Timed
public ResponseEntity<?> createBlog(@Valid @RequestBody Blog blog) throws URISyntaxException {
    log.debug("REST request to save Blog : {}", blog);
    if (blog.getId() != null) {
        throw new BadRequestAlertException("A new blog cannot already have an ID", ENTITY_NAME, "idexists");
    }
    if (!blog.getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
        return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
    }
    Blog result = blogRepository.save(blog);
    return ResponseEntity.created(new URI("/api/blogs/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
        .body(result);
}

@PutMapping("/blogs")
@Timed
public ResponseEntity<?> updateBlog(@Valid @RequestBody Blog blog) throws URISyntaxException {
    log.debug("REST request to update Blog : {}", blog);
    if (blog.getId() == null) {
        throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
    }
    if (blog.getUser() != null &&
        !blog.getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
        return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
    }
    Blog result = blogRepository.save(blog);
    return ResponseEntity.ok()
        .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, blog.getId().toString()))
        .body(result);
}

@GetMapping("/blogs/{id}")
@Timed
public ResponseEntity<?> getBlog(@PathVariable Long id) {
    log.debug("REST request to get Blog : {}", id);
    Optional<Blog> blog = blogRepository.findById(id);
    if (blog.isPresent() && blog.get().getUser() != null &&
        !blog.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
        return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
    }
    return ResponseUtil.wrapOrNotFound(blog);
}

@DeleteMapping("/blogs/{id}")
@Timed
public ResponseEntity<?> deleteBlog(@PathVariable Long id) {
    log.debug("REST request to delete Blog : {}", id);
    Optional<Blog> blog = blogRepository.findById(id);
    if (blog.isPresent() && blog.get().getUser() != null &&
        !blog.get().getUser().getLogin().equals(SecurityUtils.getCurrentUserLogin().orElse(""))) {
        return new ResponseEntity<>("error.http.403", HttpStatus.FORBIDDEN);
    }
    blogRepository.deleteById(id);
    return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}

You’ll need to make similar changes in EntryResource.java. See this commit for all the changes that you’ll need in these two classes, as well as their integration tests.

Deploy to the Cloud

A JHipster application can be deployed anywhere a Spring Boot application can be deployed.

JHipster ships with support for deploying to Cloud Foundry, Heroku, Kubernetes, AWS, and AWS with Boxfuse. I’m using Heroku in this example because it doesn’t cost me anything to host it.

When you prepare a JHipster application for production, it’s recommended to use the pre-configured “production” profile. With Maven, you can package your application by specifying the prod profile when building.

./mvnw -Pprod package

The production profile is used to build an optimized JavaScript client. You can invoke this using webpack by running yarn run webpack:prod. The production profile also configures gzip compression with a servlet filter, cache headers, and monitoring via Metrics. If you have a Graphite server configured in your application-prod.yml file, your application will automatically send metrics data to it.

When you run this command, you’ll likely get a test failure.

[INFO] Results:
[INFO]
[ERROR] Failures:
[ERROR]   BlogResourceIntTest.getAllBlogs:179 Status expected:<200> but was:(500)
[INFO]
[ERROR] Tests run: 154, Failures: 1, Errors: 0, Skipped: 0

The reason this happens is in a stack trace in your terminal.

org.springframework.dao.InvalidDataAccessApiUsageException: Authentication object cannot be null

To fix this, you can use Spring Security Test’s @WithMockUser. Open BlogResourceIntTest.java and inject UserRepository as a dependency.

src/test/java/org/jhipster/blog/web/rest/BlogResourceIntTest.java
@Autowired
private UserRepository userRepository;

Change the createEntity() method so it’s not static and uses the userRepository to set a user on the blog entity.

public Blog createEntity(EntityManager em) {
    Blog blog = new Blog()
            .name(DEFAULT_NAME)
            .handle(DEFAULT_HANDLE)
            .user(userRepository.findOneByLogin("user").get());
    return blog;
}

Add @WithMockUser to the getAllBlogs() method.

@Test
@Transactional
@WithMockUser
public void getAllBlogs() throws Exception {

After fixing this test, you should be able to run ./mvnw -Pprod package without any failures.

To deploy this application to Heroku, I logged in to my account using heroku login from the command line. I already had the Heroku CLI installed.

$ heroku login
Enter your Heroku credentials:
Email: [email protected]
Password: *******************
Logged in as [email protected]

I ran jhipster heroku as recommended in the Deploying to Heroku documentation. I used the name “jhipster5-demo” for my application when prompted. I selected “Git (compile on Heroku)” as the type of deployment.

$ jhipster heroku
Using JHipster version installed locally in current project's node_modules
Executing jhipster:heroku
Options:
Heroku configuration is starting
? Name to deploy as: jhipster5-demo
? On which region do you want to deploy ? us
? Which type of deployment do you want ? Git (compile on Heroku)

Using existing Git repository

Heroku CLI deployment plugin already installed

Creating Heroku application and setting up node environment
https://jhipster-5-demo.herokuapp.com/ | https://git.heroku.com/jhipster-5-demo.git

Provisioning addons
Created Database addon

Creating Heroku deployment files
   create src/main/resources/config/bootstrap-heroku.yml
   create src/main/resources/config/application-heroku.yml
   create Procfile
 conflict pom.xml
? Overwrite pom.xml? overwrite this and all others
    force pom.xml

Skipping build

Updating Git repository
git add .
git commit -m "Deploy to Heroku" --allow-empty

Configuring Heroku

Deploying application
remote: Compressing source files... done.
remote: Building source:

... building ...

remote:        https://jhipster-5-demo.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/jhipster-5-demo.git
 * [new branch]      HEAD -> master

Your app should now be live. To view it run
    heroku open
And you can view the logs with this command
    heroku logs --tail
After application modification, redeploy it with
    jhipster heroku
Congratulations, JHipster execution is complete!
Execution time: 6 min. 7 s.

I ran heroku open, logged as admin and was pleased to see it worked!

JHipster 5 Demo on Heroku
Figure 15. JHipster 5 Demo on Heroku

JHipster: Accelerating Spring Boot + Angular Development

I hope you’ve enjoyed learning how JHipster can help you develop modern web applications! It’s a nifty project, with an easy-to-use entity generator, a pretty UI, and many Spring Boot best-practice patterns. The project team follows five simple policies, paraphrased here:

  1. The development team votes on policies.

  2. JHipster uses technologies with their default configurations as much as possible.

  3. Only add options when there is sufficient added value in the generated code.

  4. For the Java code, follow the default IntelliJ IDEA formatting and coding guidelines.

  5. Use strict versions for third-party libraries.

These policies help the project maintain its sharp edge and streamline its development process. If you have features you’d like to add or if you’d like to refine existing features, you can watch the project on GitHub and help with its development and support. We’re always looking for help!

Now that you’ve learned how to use Angular, Bootstrap 4, and Spring Boot with JHipster, go forth and develop great applications!

Learn More about JHipster

To learn more about JHipster and all it has to offer, look no further than Full Stack Development with JHipster by Deepu K Sasidharan and Sendil Kumar. Both Deepu and Sendil have contributed an incredible amount of time and code to JHipster. We’ve very luck to have them. They’re both amazing developers! ❤️

JHipster’s awesome community has starred in some excellent online training videos too:

Follow @java_hipster on Twitter for release announcements, articles, new features, and upcoming talks.

Source Code

The source code for this project is available on GitHub at mraible/jhipster5-demo.

Travis CI is continually testing this project with configuration from its .travis.yml file. This file was generated using jhipster ci-cd and everything passed on the first try!

About the Author

Matt Raible is a web developer, Java Champion, and Developer Advocate at Okta. He loves to architect and build slick-looking UIs with CSS and TypeScript. When he’s not slinging code with open source frameworks, he likes to ski with his family, drive old VWs, and enjoy craft beer.

Matt writes on the Okta developer blog, his personal blog, and you can find him on Twitter @mraible.

jhipster5-demo's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.