full_name stringlengths 7 104 | description stringlengths 4 725 ⌀ | topics stringlengths 3 468 ⌀ | readme stringlengths 13 565k ⌀ | label int64 0 1 |
|---|---|---|---|---|
CasterIO/RxExamples | Samples from the Rx Episodes on Caster.IO | null | null | 0 |
aillamsun/genesis | Spring cloud Example | distributed-transaction eureka genesis-microservices hystrix-dashboard lcn mapper mybatis pagehelper spring-boot spring-cloud spring-cloud-lcn spring-config swagger-ui zipkin-sleuth zuul-feign | ## Genesis. Is a Spring Cloud Project
------
## 技术架构
genesis 是一个基于Spring cloud(Camden.SR1) Spring Boot(1.4.1.RELEASE) Mybatis(3.3.0) 通用Mapper 通用分页Pagehelper完成的一个基础组件架构,
使用Spring Cloud Eureka、Feign、Zuul、Spring config、Zipkin、Sleuth、Hystrix Turbine、Hystrix Dashboard...
## MAVEN模块说明
#### 1. 基础组件说明
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| genesis-common | 无 | 公共模块(工具类,资源......) | 无 |
| genesis-core | 无 | 核心代码 | 无 |
| genesis-model | 无 | 公共实体对象
| spar_generator | 无 | 生成mybatis mapper model实体
| spar_mapper | 无 | 抽离的mapper mapper.xml
------
#### 2. Spring Cloud(genesis-microservices)组件说明
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| genesis-microservices-discovery | 8761 8762 8763 | 服务注册中心(用作和8762 8763实现高可用注册中心) | 无 |
| genesis-microservices-config | 8040 | 服务配置中心服务 | 无 |
| genesis-microservices-config-client | 8041 | 服务配置客户端测试启动访问(ip:port/message打印) | 无 |
| genesis-microservices-gateway | 8050 | 服务网关 | 无 |
| genesis-microservices-hystrix-dashboard | 8051 | 服务监控(Hystrix Dashboard) | 无 |
| genesis-microservices-hystrix-turbine | 8052 | 服务监控(Hystrix Turbine) | 无 |
| genesis-microservices-monitor | 8060 | 服务监控(spring boot admin) | 无 |
| genesis-microservices-security | 无 | security | 无 |
| genesis-microservices-sleuth | 8092 | 提供测试Zipkin 服务 提供本地、远程调用API | 无 |
| genesis-microservices-zipkin | 8091 |Zipkin Server 对Spring Cloud应用进行服务追踪分析(主要和Sleuth) | 无 |
| genesis-microservices-bus-kafka | 无 |bus-kafka | 无 |
| genesis-microservices-bus-amqp | 无 |bus-amqp | 无 |
------
#### 3. Spring(genessis-spring)扩展组件说明
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| genesis-spring-extends | 无 | Spring 扩展(更新中...) | 无 |
| genesis-spring-plugins | 无 | Spring 插件(更新中...) | 无 |
| genesis-spring-plugins-mybatis | 无 | Spring boot mybatis stater自定义(在genesis-provider-goods使用测试) | 无 |
------
#### 4. Examples(genesis-examples) 提供真是服务使用
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| genesis-common-config | 无 | 通用配置 | 无 |
| genesis-provider-by-feign | 8080 | API接口(使用Feign 负载均衡) | 无 |
| genesis-provider-by-ribbon | 8084 | API接口(使用 Ribbon 负载均衡) | 无 |
| genesis-provider-by-zuul | 8085 | API接口网关(使用Zuul) | 无 |
| genesis-provider-goods | 8081 | Goods服务提供者(此服务使用了genesis-spring-plugins-mybatis stater) | 无 |
| genesis-provider-goods2 | 8082 | Goods服务提供者(用于启动测试 API goods模块Feign Client负载均衡) | 无
| genesis-provider-order | 8083 | Order服务提供者 | 无 |
| genesis-sleuth-zipkin-demo | 8093 | sleuth-zipkin-demo 接口 | 无 |
------
#### 5. 分布式事务Example(更新中....)(genesis-transaction-examples) 提供LCN分布式事务功能实现 |
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| tx-manager | 8010 | 事务管理 | 无 |
| tx-user-ms | 8011 | 用户服务 | 无 |
| tx-userMoney-ms | 1012 | 用户金钱管理服务 | 无 |
## 架构图(目前待完善)
后续会更新架构图出去,暂时先这样看着... 焦灼中..........

## 服务中心HA说明
| 项目名称 | 端口 | 描述 | URL |
| ---------------------------------------- | ---- | ---------------------- | --------------- |
| genesis-microservices-discovery | 8761 8762 8763| 服务注册中心) | 无 |
> * 1,(C:\Windows\System32\drivers\etc\hosts文件)
```java
127.0.0.1 discovery1
127.0.0.1 discovery2
127.0.0.1 discovery3
```
> * 2,每个配置里面都有一个application.properties,本机为了方便在idea工具启动 所以使用了两个项目
> * 3,以后线上可以使用一个工程即可 如下:
#### application-chengdu-1.properties
```java
spring.application.name=eureka-server-clustered
server.port=8761
eureka.instance.hostname=discovery1
eureka.client.serviceUrl.defaultZone=http://${security.user.name}:${security.user.password}@discovery2:8762/eureka/,http://${security.user.name}:${security.user.password}@discovery3:8763/eureka/
```
#### application-chengdu-2.properties
```java
spring.application.name=eureka-server-clustered
server.port=8762
eureka.instance.hostname=discovery2
eureka.client.serviceUrl.defaultZone=http://${security.user.name}:${security.user.password}@discovery1:8761/eureka/,http://${security.user.name}:${security.user.password}@discovery3:8763/eureka/
```
#### application-chengdu-3.properties
```java
spring.application.name=eureka-server-clustered
server.port=8763
eureka.instance.hostname=discovery3
eureka.client.serviceUrl.defaultZone=http://${security.user.name}:${security.user.password}@discovery1:8761/eureka/,http://${security.user.name}:${security.user.password}@discovery2:8762/eureka/
```
### 命令启动格式1:
```java
java -jar discovery-1.0.0.jar --spring.profiles.active=chengdu-1
java -jar discovery-1.0.0.jar --spring.profiles.active=chengdu-2
java -jar discovery-1.0.0.jar --spring.profiles.active=chengdu-3
```
命令修改为:
```java
java -jar discovery-1.0.0.jar
```
### 效果图:
### [访问discovery1](http://discovery1:8761)

## 监控视图测试
### 使用说明:
#### Spring boot Admin 监控
> * 数据库脚本 genesis-common-config resources/db/下面spring-cloud-test.sql
> * 首先启动:genesis-microservices-monitor 端口 8060
> * 启动 genesis-provider-goods 端口 8081
访问 http://localhost:8060 admin UI
访问 http://localhost:8081/goods
#### 效果图
-----
#### Hystrix-dashboard 监控
> * 数据库脚本 genesis-common-config resources/db/下面spring-cloud-test.sql
> * 首先启动:genesis-microservices-discovery
> * 启动genesis-microservices-hystrix-dashboard 端口 8051
> * 启动genesis-provider-by-feign 端口8080
访问 http://localhost:8051
在地址栏输入:http://localhost:8080/hystrix.stream
#### 效果图

-----
#### Hystrix Turbine 监控
> * 数据库脚本 genesis-common-config resources/db/下面spring-cloud-test.sql
> * 首先启动:genesis-microservices-discovery
> * genesis-provider-goods,genesis-provider-order
> * genesis-provider-by-feign,genesis-provider-by-ribbon
> * genesis-microservices-hystrix-dashboard 端口 8051
> * 启动genesis-microservices-hystrix-turbine 端口 8052
> * 分别启动 genesis-provider-goods 端口8081 、genesis-provider-order 端口 8083
访问http://localhost:8051
输入框输入:http://localhost:8052/turbine.stream
分别访问 feign ribbon
#### 效果图1

确认:
#### 效果图2

## 服务跟踪监控Zipkin、Sleuth 测试
### 使用说明:
#### 项目启动
> * 启动 Zipkin Server 服务 genesis-microservices-zipkin 端口 8091
> * 启动 Zipkin Server 服务demo genesis-microservices-sleuth 端口 8092
> * 启动测试 Zipkin、Sleuth 服务提供者 genesis-sleuth-zipkin-demo 端口 8093
> * 直接调用 8092 Controller接口即可
#### 跟踪列表效果图

#### 跟踪详细信息效果图

## Zuul 和 Feign 测试
### 使用说明:
#### 1,项目启动:
> * 数据库脚本 genesis-common-config resources/db/下面spring-cloud-test.sql
> * 首先启动:genesis-microservices-discovery
> * 测试Fegin可以启动genesis-provider-by-feign。前提启动genesis-provider-good、genesis-provider-order
> * 测试Zuul可以启动genesis-provider-by-zuul 。前提启动genesis-provider-good、genesis-provider-order
> * genesis-provider-by-feign提供swgger UI 通过API文档Try 就可以了
## API 文档访问测试
### 使用说明:
#### 1,项目启动:
> * 启动API genesis-provider-by-feign访问http://localhost:8080/swagger-ui.html

## 分布式事务基于Spring Cloud + LCN
### LCN
首先感谢LCN提供
[LCN](https://github.com/1991wangliang/tx-lcn)
### 使用说明:
#### 1,项目启动:
> * 首先启动 tx-manager
[tx-manager](http://localhost:8100/index)
效果图

> * 启动 tx-user-ms 和 tx-user-money-ms
#### 测试
> * 访问 http://localhost:8011/user/save
Controller
```java
@RequestMapping(value = "/save",method = RequestMethod.POST)
public int save() {
return userService.save();
}
```
Service
```java
@TxTransaction
@Transactional
public int save() {
User user = new User();
user.setUserName("Test Tx");
user.setPassword("11111");
int rs1 = userMapper.insert(user);
/**
* 保存 余额 分布式服务
*/
int rs2 = userMoneyClient.save();
/**
* 抛出异常
*/
int v = 100 / 0;
return rs1 + rs2;
}
```
UserMoneyClient
```java
@FeignClient(name = "genesis-tx-user-money-ms", configuration = TransactionRestTemplateConfiguration.class)
public interface UserMoneyClient {
@RequestMapping(value = "/user-money/save",method = RequestMethod.POST)
int save();
}
```
| 1 |
caprica/vlcj-player | Feature-rich example vlcj media player | null | *You are currently looking at the development branch of vlcj-player for vlcj-4.0.0, if you want a stable version of
vlcj-player that works with vlcj-3 you should switch to the
[vlcj-3.x branch](https://github.com/caprica/vlcj-player/tree/vlcj-3.x).*
vlcj-player
===========
The vlcj-player is a media player application built using vlcj with a Swing
rich-client user interface.
The main goal of the project is to provide an extensive demo application
showing how to build media players with vlcj, and to include as many features
of vlcj as possible.
Generally the vlcj-player tries to match the Qt interface of VLC with as many
of the same features implemented as possible.
However, it is not possible to get a 100% like-for-like implementation since
LibVLC, used by vlcj, exposes only a sub-set of the total functionality of VLC.
Screenshot
----------

Features
--------
- audio player
- video player
- full-screen
- audio equalizer
- video adjustments
- title selection
- chapter navigation
- audio track selection
- video track selection
- subtitle track selection
- load external subtitle file
- change audio device
- change audio stereo mode
- change playback speed
- capture and display native logs
- capture and display video surface debug messages (e.g. to test mouse and keyboard events still work)
- volume controls
- mute
- zoom/scale
- aspect ratio
- crop
- logo/marquee
- always on top
- video snapshots
- drag and drop local files to the main window
- drag and drop URLs from web browsers to the main window (e.g. to play a YouTube video)
- redirect native output streams (on Linux)
...and a whole bunch of other nifty stuff.
Status
------
This project is currently a work-in-progress.
If you execute "mvn install" or "mvn package", you will get a distribution
package that you can unpack. This will give you the vlcj-player application jar
and all of the dependencies - you can simply execute `java -jar vlcj-player-1.0.0-SNAPSHOT.jar`
and the application should start.
On the other hand, just run it from an Eclipse project.
License
-------
The vlcj-player project is provided under the GPL, version 3 or later.
| 1 |
lczmdr/drools-developers-cookbook-examples | Drools Developer's Cookbook examples | null | null | 0 |
thomasdarimont/keycloak-project-example | An example project for Keycloak Customizations | null | null | 1 |
mkurz/deadbolt-2-java-examples | Example usages of Deadbolt 2 Java | null | deadbolt-2-java-examples
=========================
Example usages of Deadbolt 2's Java API. Deadbolt 2 is an authorisation module for Play 2.
Deadbolt 2 comprises of several modules - a common core, and language-specific implementations for Java and Scala. Example applications and a user guide are also available.
All modules related to Deadbolt 2, including the user guide, are grouped together in the [Deadbolt 2](https://github.com/schaloner/deadbolt-2) Github super-module. Installation information, including Deadbolt/Play compatibility, can also be found here. | 1 |
mpatric/mp3agic-examples | Example apps using mp3agic library | null | null | 1 |
EsotericSoftware/spine-superspineboy | Example platformer game for spine-libgdx. | null | 
Super Spineboy is a platformer game for Windows, Mac and Linux written using [Spine](http://esotericsoftware.com/) and [spine-libgdx](https://github.com/EsotericSoftware/spine-runtimes/tree/master/spine-libgdx). Spine is a 2D animation tool specifically for games and Super Spineboy shows some of the ways to make use of Spine skeletons and animations in an actual game.
[](https://www.youtube.com/watch?v=zAZ_PxxEgDI)
## Download
Super Spineboy can be [downloaded](http://esotericsoftware.com/files/runtimes/superSpineboy.jar) in binary form and run on Windows, Mac or Linux. Java 1.6+ is required. To run Super Spineboy, double click the `superSpineboy.jar` file or run it from the command line:
```
java -jar superSpineboy.jar
```
## Controls
* Left click shoots toward the mouse position. Hold to keep shooting.
* `A` is left, `D` is right, `W` is jump.
* Alternatively, `left arrow` is left, `right arrow` is right, `space` is jump.
* Press `alt + enter` or click `Fullscreen` in the menu to run the game fullscreen.
* Press the number keys `1` through `6` to control the game speed, allowing you to see how smooth the animations are and the transitions between animations.
* Press `tilda` or `P` to pause.
* Press `Z` to zoom in/out so you can see the animations more easily.
## Gameplay tips
You may find Super Spineboy difficult at first. The game is relatively short, so the difficulty ramps up quickly. These tips may help you overcome the hordes!
* Don't move through further into the level until you've killed all the enemies you find.
* Spineboy's weapon shoots very fast, but suffers from reduced accuracy when shot continuously. Cease firing momentarily to regain accuracy.
* You cannot shoot backward when running away, but you can jump while running away and shoot backward in the air.
* Standing your ground and mowing down enemies is great, but there are quickly so many enemies that you get overrun. When this happens, goomba head stomp the enemies. This is key to winning!
* Getting sandwiched between two groups of enemies is a sure way to die. Head stomp your way to one side so you aren't surrounded.
* If the game runs poorly, try unchecking `Background` in the menu.
## Source
Super Spineboy is written in Java and uses OpenGL, [libgdx](http://libgdx.badlogicgames.com/), [Spine](http://esotericsoftware.com/) and [spine-libgdx](https://github.com/EsotericSoftware/spine-runtimes/tree/master/spine-libgdx). A loose [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) design pattern is used for code organization. This makes for a clean separation between the game logic and what is drawn.
The Super Spineboy source can be downloaded from GitHub using a Git client or as a [zip file](https://github.com/EsotericSoftware/spine-superspineboy/archive/master.zip). To run from source using Eclipse, click `File` -> `Import` -> `Existing projects`.
## License
Super Spineboy is licensed under the [Spine Runtime License](https://github.com/EsotericSoftware/spine-superspineboy/blob/master/LICENSE). Please see the license for full details, but this basically means that if you license [Spine](http://esotericsoftware.com/), you can create derivative works or otherwise use Super Spineboy however you like.
## Screenshots



| 1 |
callstack/repack-examples | Repository with examples for Re.Pack | null | # repack-examples
A repository with examples for [Re.Pack](https://github.com/callstack/repack).
## Usage
Install dependencies:
```bash
yarn install
```
Run scripts inside desired example:
```bash
yarn workspace <name> run start
yarn workspace <name> run ios
yarn workspace <name> run android
```
for example:
```bash
yarn workspace local-chunks run start
```
| 0 |
camelinaction/camelinaction2 | :camel: This project hosts the source code for the examples of the Camel in Action 2nd ed book :closed_book: written by Claus Ibsen and Jonathan Anstey. | apache-camel book camel eip integration java microservice | Camel in Action 2nd Edition
===========================
This project hosts the source code for the examples of the [Camel in Action](https://www.manning.com/books/camel-in-action-second-edition) 2nd edition book written by [Claus Ibsen](https://twitter.com/davsclaus) and [Jonathan Anstey](https://twitter.com/jon_anstey).

Table of Contents
-----------------
Part 1 - First Steps
- 1 [Meeting Camel](chapter1)
- 2 [Routing with Camel](chapter2)
Part 2 - Core Camel
- 3 [Transforming data with Camel](chapter3)
- 4 [Using beans with Camel](chapter4)
- 5 [Enterprise integration patterns](chapter5)
- 6 [Using components](chapter6)
Part 3 - Developing and testing
- 7 [Microservices](chapter7)
- 8 [Developing Camel projects](chapter8)
- 9 [Testing](chapter9)
- 10 [RESTful web services](chapter10)
Part 4 - Going further with Camel
- 11 [Error handling](chapter11)
- 12 [Transactions and idempotency](chapter12)
- 13 [Parallel processing](chapter13)
- 14 [Securing Camel](chapter14)
Part 5 - Running and managing Camel
- 15 [Running and deploying Camel](chapter15)
- 16 [Management and monitoring](chapter16)
Part 6 - Out in the Wild
- 17 [Clustering](chapter17)
- 18 [Microservices with Docker and Kubernetes](chapter18)
- 19 [Camel tooling](chapter19)
Bonus Chapters
- 20 [Reactive Camel](chapter20)
- 21 Camel and the IoT by Henryk Konsek (has no source code)
Appendixes
- A Simple, the expression language
- B The Camel community
Downloading the source code
---------------------------
You can either download a .zip with all the source code from the [releases page](https://github.com/camelinaction/camelinaction2/releases), or use the github way of cloning the repository on your computer.
System requirements
---------------------------
You need JDK 8 installed on your system in order to compile the source code.
Maven version >= 3.5.
Apache Camel 2.20.1 or newer 2.x version.
Camel 3.x support is *not* on the main branch, but provided as _best effort_ on [dedicated branches](https://github.com/camelinaction/camelinaction2/branches)
Up to date source code
----------------------
We the authors, intended to keep this source code up to date with future releases of Apache Camel. Giving our readers the best experience with the book and using the latest Camel releases.
Errata
------
Any mistakes in the book can be reported to us via github issues tracker.
The errata can be [viewed here](errata.txt)
Getting in touch
----------------
To get in touch with the us the authors you can:
* write on the [Manning Author Online forum](https://forums.manning.com/forums/camel-in-action-second-edition)
* reach out to us on twitter: [@davsclaus](https://twitter.com/davsclaus), [@jon_anstey](https://twitter.com/jon_anstey)
* or use the [github issue tracker](https://github.com/camelinaction/camelinaction2/issues)
Happy reading and riding the Camel.
Claus Ibsen, and Jonathan Anstey
| 0 |
janbodnar/Java-Advanced | Examples for Advanced Java course | advanced-programming course java programming-language | # Java-Advanced
Examples for Advanced Java course
https://zetcode.com/
Available under 2-Clause BSD License https://opensource.org/licenses/BSD-2-Clause
## VS Code
Extensions:
- Java Platforma Support
- Trailing
- vscode-icons
- Rewrap
The project `settings.json`
```json
{
"jdk.runConfig.vmOptions": "--enable-preview --source 22",
"jdk.jdkhome": "c:\\Users\\Jano\\.jdks\\jdk22.0.0_36",
}
```
The `settings.json`
```json
{
"editor.rulers": [
80
],
"workbench.iconTheme": "vscode-icons",
"terminal.integrated.defaultProfile.windows": "Command Prompt",
"jdk.jdkhome": "c:\\Users\\Jano\\.jdks\\jdk22.0.0_36",
"editor.stickyScroll.enabled": false,
"editor.minimap.enabled": false,
}
| 0 |
lynxbroker/API-examples | Code samples that show some of the LYNX API possible implementations | automated-trading ibapi lynx-api trading-algorithms | # LYNX API examples
Code samples that show some of the LYNX API possible implementations.
### Table of contents
- [**Excel**](https://github.com/lynxbroker/API-examples/tree/master/Excel) - request real-time market data from TWS via API using Microsoft Excel
- [**Java**](https://github.com/lynxbroker/API-examples/tree/master/Java) - code samples of the API integration with Java & [*quickstart*](https://github.com/lynxbroker/API-examples/tree/master/Java/quickstart) application
- [**Python**](https://github.com/lynxbroker/API-examples/tree/master/Python) - code samples of the API integration with Python
---
##### For more information in regard to the API Documentation, visit our [website](https://api.lynx.academy).
---
<p align="center">
<img src="Java/place_order/images/logo_cover.svg">
</p>
| 0 |
RameshMF/jsp-servlet-jdbc-mysql-crud-tutorial | JSP Servlet JDBC MySQL CRUD Example Tutorial | null | # jsp-servlet-jdbc-mysql-crud-tutorial
JSP Servlet JDBC MySQL CRUD Example Tutorial
https://www.javaguides.net/2019/03/jsp-servlet-jdbc-mysql-crud-example-tutorial.html
| 1 |
Petikoch/Java_MVVM_with_Swing_and_RxJava_Examples | Explorative Java Swing GUI example code from 2016 with an implementation of MVVM (Model View ViewModel) using RxJava and RxSwing. DON'T use it in production, there are some open issues here! | java mvvm rxjava swing-gui | null | 1 |
eljefe6a/beamexample | An example Apache Beam project. | null | # Apache Beam Example Code
An example Apache Beam project.
### Description
This example can be used with conference talks and self-study. The base of the examples are taken from Beam's `example` directory. They are modified to use Beam as a dependency in the `pom.xml` instead of being compiled together. The example code is changed to output to local directories.
## How to clone and run
1. Open a terminal window.
1. Run `git clone git@github.com:eljefe6a/beamexample.git`
1. Run `cd beamexample/BeamTutorial`
1. Run `mvn compile`
1. Create local output directory: `mkdir output`
1. Run `mvn compile exec:java -Dexec.mainClass="org.apache.beam.examples.tutorial.game.solution.Exercise1" -Pdirect-runner`
1. Run `cat output/user_score` to verify the program ran correctly and the output file was created.
### Using a Java IDE
1. Follow the [IDE Setup](http://beam.incubator.apache.org/contribute/contribution-guide/#optional-ide-setup) instructions on the Apache Beam Contribution Guide.
## Other Runners
### Apache Flink
1. Follow the first steps from [Flink's Quickstart](https://ci.apache.org/projects/flink/flink-docs-release-1.1/quickstart/setup_quickstart.html) to [download Flink](https://ci.apache.org/projects/flink/flink-docs-release-1.1/quickstart/setup_quickstart.html#download).
1. Create the `output` directory.
1. To run on a JVM-local cluster: `mvn compile exec:java -Dexec.mainClass=org.apache.beam.examples.tutorial.game.solution.Exercise1 -Dexec.args='--runner=FlinkRunner --flinkMaster=[local]' -Pflink-runner`
1. To run on an out-of-process local cluster (note that the steps below should also work on a real cluster if you have one running):
1. [Start a local Flink cluster](https://ci.apache.org/projects/flink/flink-docs-release-1.1/quickstart/setup_quickstart.html#start-a-local-flink-cluster).
1. Navigate to the WebUI (typically [http://localhost:8081](http://localhost:8081)), click [JobManager](http://localhost:8081/#/jobmanager/config), and note the value of `jobmanager.rpc.port`. The default is probably 6123.
1. Run `mvn package -Pflink-runner` to generate a JAR file. Note the location of the generated JAR (probably `./target/BeamTutorial-bundled-flink.jar`)
1. Run `mvn -X -e compile exec:java -Dexec.mainClass=org.apache.beam.examples.tutorial.game.solution.Exercise1 -Dexec.args='--runner=FlinkRunner --flinkMaster=localhost:6123 --filesToStage=./target/BeamTutorial-bundled-flink.jar' -Pflink-runner`, replacing the defaults for port and JAR file if they differ.
1. Check in the [WebUI](http://localhost:8081) to see the job listed.
1. Run `cat output/user_score` to verify the pipeline ran correctly and the output file was created.
### Apache Spark
1. Create the `output` directory.
1. Allow all users (Spark may run as a different user) to write to the `output` directory. `chmod 1777 output`.
1. Change the output file to a fully-qualified path. For example, `this("output/user_score");` to `this("/home/vmuser/output/user_score");`
1. Run `mvn package -Pspark-runner`
1. Run `spark-submit --jars ./target/BeamTutorial-bundled-spark.jar --class org.apache.beam.examples.tutorial.game.solution.Exercise2 --master yarn-client ./target/BeamTutorial-bundled-spark.jar --runner=SparkRunner`
### Google Cloud Dataflow
1. Follow the steps in either of the [Java quickstarts for Cloud Dataflow](https://cloud.google.com/dataflow/docs/quickstarts) to initialize your Google Cloud setup.
1. [Create a bucket](https://cloud.google.com/storage/docs/creating-buckets) on Google Cloud Storage for staging and output.
1. Run `mvn -X compile exec:java -Dexec.mainClass="org.apache.beam.examples.tutorial.game.solution.Exercise1" -Dexec.args='--runner=DataflowRunner --project=<YOUR-GOOGLE-CLOUD-PROJECT> --gcpTempLocation=gs://<YOUR-BUCKET-NAME> --outputPrefix=gs://<YOUR-BUCKET-NAME>/output/' -Pdataflow-runner`, after replacing `<YOUR-GCP-PROJECT>` and `<YOUR-BUCKET-NAME>` with the appropriate values.
1. Check the [Cloud Dataflow Console](https://console.cloud.google.com/dataflow) to see the job running.
1. Check the output bucket to see the generated output: `https://console.cloud.google.com/storage/browser/<YOUR-BUCKET-NAME>/`
## Further Reading
* The World Beyond Batch Streaming [Part 1](https://www.oreilly.com/ideas/the-world-beyond-batch-streaming-101) and [Part 2](https://www.oreilly.com/ideas/the-world-beyond-batch-streaming-102)
* [Future-Proof Your Big Data Processing with Apache Beam](http://thenewstack.io/apache-beam-will-make-big-difference-organization/)
* [Future-proof and scale-proof your code](https://www.oreilly.com/ideas/future-proof-and-scale-proof-your-code)
* [Question and Answers with the Apache Beam Team](http://www.jesse-anderson.com/2016/07/question-and-answers-with-the-apache-beam-team/)
| 1 |
USCDataScience/dl4j-kerasimport-examples | This repository contains deeplearning4j examples for importing and making use of models trained in keras | null | # DL4J Keras Import Examples
This repository contains deeplearning4j examples for importing and making use of models trained in keras
# Index
+ `deep-learning-models` contains popular deep learning models implemented in keras
+ `dl4j-import-example` contains examples for importing keras models to deeplearning4j,
first example: an image classifier based on InceptionV3 net.
| 0 |
ypriverol/spark-java8 | Java 8 and Spark learning through examples | dataset java lambda learning-spark spark | # Java 8 and Spark Learning tutorials
This is a collection of [Java 8](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html) and [Apache Spark](http://spark.apache.org/) examples and concepts,
from basic to advanced. It explain basic concepts introduced by Java 8 and how you can merge them with Apache Spark.
The current tutorial or set of examples provide a way of understand Spark 2.0 in details but also to get familiar with
Java 8 and it new features like lambda, Stream and reaction programming.
## Why Java 8
Java 8 is the latest version of Java which includes two major changes: Lambda expressions and Streams. Java 8 is a revolutionary release of the world’s #1 development platform.
It includes a huge upgrade to the Java programming model and a coordinated evolution of the JVM, Java language, and libraries. Java 8 includes features for productivity,
ease of use, improved polyglot programming, security and improved performance. Welcome to the latest iteration of the largest, open, standards-based, community-driven platform.
1- Lambda Expressions, a new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data.
Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.
2- Classes in the new java.util.stream package provide a Stream API to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API,
which enables bulk operations on collections, such as sequential or parallel map-reduce transformations including performance improvement for HashMaps with Key Collisions.
## Why Spark
[Apache Spark™](http://spark.apache.org/) is a fast and general engine for large-scale data processing. Apache Spark is a fast and general-purpose cluster computing system. It provides high-level APIs in Java,
Scala, Python and R, and an optimized engine that supports general execution graphs. It also supports a rich set of higher-level tools including Spark SQL for SQL and structured data processing, MLlib for machine
learning, GraphX for graph processing, and Spark Streaming.
## Instructions
A good way of using these examples is by first cloning the repo, and then
starting your own [Spark Java 8](http://github.con/ypriverol/spark-java8).
### Installing Java 8 and Spark
Java 8 can be download [here](http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html). After the installation
you need to be sure that the version you are using is java 8, you can check that by running:
```bach
java -version
```
In order to setup Spark locally in you machine you should download the spark version from [here](http://spark.apache.org/downloads.html). Then you should follow the next steps:
```bach
> tar zxvf spark-xxx.tgz
> cd spark-xxx
> build/mvn -DskipTests clean package
```
After the compilation and before running your first example you should add to your profile the [SPARK MASTER Variable](http://spark.apache.org/docs/latest/spark-standalone.html):
```bach
> export SPARK_LOCAL_IP=127.0.0.1
```
To be sure that you spark is installed properly in your machine you can run the first example from spark:
```bach
> ./bin/run-example SparkPi
```
## Datasets
Some of the datasets we will use in this learning tutorial are:
- Tweets Archive from [@ypriverol](https://twitter.com/ypriverol) is used in the word count
- We will be using datasets from the [KDD Cup 1999](http://kdd.ics.uci.edu/databases/kddcup99/kddcup99.html). The results
of this competition can be found [here](http://cseweb.ucsd.edu/~elkan/clresults.html).
## References
The reference book for these and other Spark related topics is:
- *Learning Spark* by Holden Karau, Andy Konwinski, Patrick Wendell, and Matei Zaharia.
## Examples
The following examples can be examined individually, although there is a more or less linear 'story' when followed in sequence. By using different datasets they try to solve a related set of tasks with it.
### [RDD Basic Examples](https://github.com/ypriverol/spark-java8/wiki/2-RDD-Basic-Examples)
Here a list of the most basic examples in Spark-Java8 and definition of the most basic concepts in Spark.
1- [SparkWordCount](https://github.com/ypriverol/spark-java8/wiki/2.1--Spark-Word-Count): About How to create a simple JavaRDD in Spark.
2- [MaptoDouble](https://github.com/ypriverol/spark-java8/wiki/2.2-Map-To-Double): How to generate general statistics about an RDD in Spark
3- [SparkAverage](https://github.com/ypriverol/spark-java8/wiki/2.3-Spark-Average): How to compute the average of a set of numbers in Spark.
### [RDD Sampling Examples](https://github.com/ypriverol/spark-java8/wiki/3-Spark-Sampling-Examples)
1- [SparkSampling](https://github.com/ypriverol/spark-java8/wiki/3.1-SparkSampling): Basic Spark Sampling using functions sample and takesample.
| 0 |
gephi/gephi-plugins-bootcamp | Out of the box plug-ins development suite. Contains examples for all types of plug-ins. | null | # Gephi Plugins Bootcamp
Get started with the [Gephi](http://gephi.org) Platform and start to create [Gephi Plugins](https://gephi.org/plugins/#/) by looking at these examples.
The Gephi Plugins Bootcamp is the best sources of examples and good practices to create all types of plug-ins (layout, filter, io, visualization, ...). Consult the [**Javadoc**](https://gephi.org/javadoc/0.9.3/) to discover the different APIs. Documentation is also available on the [Gephi Plugins](https://github.com/gephi/gephi-plugins) repository.

## What's inside?
Complete list of the plug-ins examples included in the bootcamp:
### Layout
* **Grid Layout**
* Place all nodes in a simple grid. Users can configure the size of the area and the speed.
* **Sorted Grid Layout**
* Same example as Grid Layout but users can sort nodes with an attribute column.
### Filter
* **Transform to Undirected**
* Edge filter to remove mutual edges in a directed graph.
* **Top nodes**
* Keep the top K nodes using an attribute column.
* **Remove Edge Crossing**
* Example of a complex filter implementation which removes edges until no crossing occurs.
### Tool
* **Find**
* Tool with an autocomplete text field to find any node based on labels and zoom by it.
* **Add Nodes**
* Listen to mouse clicks and adds nodes. Also adds edges if selecting other nodes.
### Export
* **JPG Export**
* Vectorial export to the JPG image format. Contains a settings panel to set the width and height.
* **SQLite Database Export**
* Current graph export to a SQLite Database file. A new sub-menu is added in the Export menu and an example of a custom exporter is shown.
### Preview
* **Highlight Mutual Edges**
* Colors differently mutual edges. Overwrites and extends the default edge renderer.
* **Glow Renderer**
* Adds a new renderer for node items which draws a glow effect around nodes.
* **Node Z-ordering**
* Extends the default node builder by reordering the node items by size or any number columns. Also shows how to create complex Preview UI.
* **Square shaped nodes**
* Demonstrates how to extend and replace a default renderer. Extends node default renderer to support square shaped nodes.
### Import
* **Matrix Market Importer**
* File importer for the Matrix Market format.
### Statistic
* **Count Self-Loop**
* Example of a statistics result at the global level. Simply counts the number of self-loop edges in the graph.
* **Average Euclidean Distance**
* Example of a per-node calculation. For a given node it calculates the average distance to others.
### Generator
* **Simple generator**
* Hello world generator which creates a two nodes network.
* **Streaming generator**
* Shows how to create a continuous generator using threads.
### Data laboratory
* **Interactive sparkline**
* Table cell action that shows an interactive sparkline of a number list or dynamic number.
* **Convert column to dynamic**
* Column action that replaces a column with its dynamic equivalent with a defined interval.
* **Invert row selection**
* General action (plugin) that inverts the current table row selection.
* **Equal values merge strategy**
* Column merge strategy that creates a new boolean column with values indicating if the two given columns have the same value.
* **Set node(s) color**
* Nodes action that edits the color of one or more nodes
### Plugins sub-menu
* **Test action**
* Simple action which display a message and a dialog.
* **Remove self loops**
* Action which accesses the graph and remove self-loops, if any.
* **Using Progress and Cancel**
* Action which creates a long task and execute it with progress and cancel support.
### Execute at startup
* **When UI is ready**
* Do something when the UI finished loading.
* **Workspace select events**
* Do something when a workspace is selected.
### Processor
* **Initial Position**
* Set up the nodes' initial position always the same. It calculates a hash with all nodes so the X/Y position is randomized always in the same way.
### New Panel
* **New panel**
* Example of a new panel plugin set up at the ranking position.
| 0 |
bezkoder/spring-boot-login-example | Spring Boot Login and Registration example with MySQL, JWT, Rest Api - Spring Boot Spring Security Login example | authentication authorization jwt jwt-auth jwt-authentication jwt-authorization jwt-token login mysql rest-api spring-boot spring-data-jpa spring-security token-based-authentication | # Spring Boot Login example with Spring Security, MySQL and JWT
Build a Spring Boot Login and Registration example (Rest API) that supports JWT with HttpOnly Cookie. You’ll know:
- Appropriate Flow for User Login and Registration with JWT and HttpOnly Cookies
- Spring Boot Rest Api Architecture with Spring Security
- How to configure Spring Security to work with JWT
- How to define Data Models and association for Authentication and Authorization
- Way to use Spring Data JPA to interact with MySQL Database
## User Registration, Login and Authorization process.

## Spring Boot Server Architecture with Spring Security
You can have an overview of our Spring Boot Server with the diagram below:

For more detail, please visit:
> [Spring Boot Login example with MySQL and JWT](https://www.bezkoder.com/spring-boot-login-example-mysql/)
> [For H2 Embedded database](https://www.bezkoder.com/spring-boot-security-login-jwt/)
> [For MongoDB](https://www.bezkoder.com/spring-boot-jwt-auth-mongodb/)
Working with Front-end:
> [Angular 12](https://www.bezkoder.com/angular-12-jwt-auth-httponly-cookie/) / [Angular 13](https://www.bezkoder.com/angular-13-jwt-auth-httponly-cookie/) / [Angular 14](https://www.bezkoder.com/angular-14-jwt-auth/) / [Angular 15](https://www.bezkoder.com/angular-15-jwt-auth/) / [Angular 16](https://www.bezkoder.com/angular-16-jwt-auth/) / [Angular 17](https://www.bezkoder.com/angular-17-jwt-auth/)
> [React](https://www.bezkoder.com/react-login-example-jwt-hooks/) / [React Redux](https://www.bezkoder.com/redux-toolkit-auth/)
## Dependency
– If you want to use PostgreSQL:
```xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
```
– or MySQL:
```xml
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
```
## Configure Spring Datasource, JPA, App properties
Open `src/main/resources/application.properties`
- For PostgreSQL:
```
spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
# App Properties
bezkoder.app.jwtCookieName= bezkoder
bezkoder.app.jwtSecret= ======================BezKoder=Spring===========================
bezkoder.app.jwtExpirationMs= 86400000
```
- For MySQL
```
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto= update
# App Properties
bezkoder.app.jwtCookieName= bezkoder
bezkoder.app.jwtSecret= ======================BezKoder=Spring===========================
bezkoder.app.jwtExpirationMs= 86400000
```
## Run Spring Boot application
```
mvn spring-boot:run
```
## Run following SQL insert statements
```
INSERT INTO roles(name) VALUES('ROLE_USER');
INSERT INTO roles(name) VALUES('ROLE_MODERATOR');
INSERT INTO roles(name) VALUES('ROLE_ADMIN');
```
## Refresh Token
[Spring Boot Refresh Token with JWT example](https://www.bezkoder.com/spring-boot-refresh-token-jwt/)
## More Practice:
> [Spring Boot File upload example with Multipart File](https://bezkoder.com/spring-boot-file-upload/)
> [Exception handling: @RestControllerAdvice example in Spring Boot](https://bezkoder.com/spring-boot-restcontrolleradvice/)
> [Spring Boot Repository Unit Test with @DataJpaTest](https://bezkoder.com/spring-boot-unit-test-jpa-repo-datajpatest/)
> [Spring Boot Rest Controller Unit Test with @WebMvcTest](https://www.bezkoder.com/spring-boot-webmvctest/)
> [Spring Boot Pagination & Sorting example](https://www.bezkoder.com/spring-boot-pagination-sorting-example/)
> Validation: [Spring Boot Validate Request Body](https://www.bezkoder.com/spring-boot-validate-request-body/)
> Documentation: [Spring Boot and Swagger 3 example](https://www.bezkoder.com/spring-boot-swagger-3/)
> Caching: [Spring Boot Redis Cache example](https://www.bezkoder.com/spring-boot-redis-cache-example/)
Associations:
> [JPA/Hibernate One To Many example in Spring Boot](https://www.bezkoder.com/jpa-one-to-many/)
> [JPA/Hibernate Many To Many example in Spring Boot](https://www.bezkoder.com/jpa-many-to-many/)
> [JPA/Hibernate One To One example in Spring Boot](https://www.bezkoder.com/jpa-one-to-one/)
Deployment:
> [Deploy Spring Boot App on AWS – Elastic Beanstalk](https://www.bezkoder.com/deploy-spring-boot-aws-eb/)
> [Docker Compose Spring Boot and MySQL example](https://www.bezkoder.com/docker-compose-spring-boot-mysql/)
## Fullstack CRUD App
> [Vue.js + Spring Boot + H2 Embedded database example](https://www.bezkoder.com/spring-boot-vue-js-crud-example/)
> [Vue.js + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-vue-js-mysql/)
> [Vue.js + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-vue-js-postgresql/)
> [Angular 8 + Spring Boot + Embedded database example](https://www.bezkoder.com/angular-spring-boot-crud/)
> [Angular 8 + Spring Boot + MySQL example](https://www.bezkoder.com/angular-spring-boot-crud/)
> [Angular 8 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/angular-spring-boot-postgresql/)
> [Angular 10 + Spring Boot + MySQL example](https://www.bezkoder.com/angular-10-spring-boot-crud/)
> [Angular 10 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/angular-10-spring-boot-postgresql/)
> [Angular 11 + Spring Boot + MySQL example](https://www.bezkoder.com/angular-11-spring-boot-crud/)
> [Angular 11 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/angular-11-spring-boot-postgresql/)
> [Angular 12 + Spring Boot + Embedded database example](https://www.bezkoder.com/angular-12-spring-boot-crud/)
> [Angular 12 + Spring Boot + MySQL example](https://www.bezkoder.com/angular-12-spring-boot-mysql/)
> [Angular 12 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/angular-12-spring-boot-postgresql/)
> [Angular 13 + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-13-crud/)
> [Angular 13 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-13-mysql/)
> [Angular 13 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-13-postgresql/)
> [Angular 14 + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-14-crud/)
> [Angular 14 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-14-mysql/)
> [Angular 14 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-14-postgresql/)
> [Angular 15 + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-15-crud/)
> [Angular 15 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-15-mysql/)
> [Angular 15 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-15-postgresql/)
> [Angular 16 + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-16-crud/)
> [Angular 16 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-16-mysql/)
> [Angular 16 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-16-postgresql/)
> [Angular 17 + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-17-crud/)
> [Angular 17 + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-17-mysql/)
> [Angular 17 + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-17-postgresql/)
> [React + Spring Boot + MySQL example](https://www.bezkoder.com/react-spring-boot-crud/)
> [React + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-react-postgresql/)
> [React + Spring Boot + MongoDB example](https://www.bezkoder.com/react-spring-boot-mongodb/)
Run both Back-end & Front-end in one place:
> [Integrate Angular with Spring Boot Rest API](https://www.bezkoder.com/integrate-angular-spring-boot/)
> [Integrate React.js with Spring Boot Rest API](https://www.bezkoder.com/integrate-reactjs-spring-boot/)
> [Integrate Vue.js with Spring Boot Rest API](https://www.bezkoder.com/integrate-vue-spring-boot/)
| 1 |
politrons/reactive | Reactive: Examples of the most famous reactive libraries that you can find in the market. | akka flow flux java reactivestreams reactivex reactor rsocket rxjava spring stream | Author Pablo Picouto Garcia
Is this repo useful? Please ⭑Star this repository and share the love.
Here we cover with examples the most famous [reactive](https://www.reactivemanifesto.org/) libraries that you can find
in the market.
## ReactiveX

Marble diagrams are not clear enough?.
Here we cover with some practical examples, the most common use of
the [ReactiveX](https://github.com/ReactiveX/RxJava/wiki) platform for Java.
RxScala examples [here](https://github.com/politrons/reactiveScala)
* **Contactable**

* [HotObservable](src/test/java/rx/observables/connectable/HotObservable.java)
* **Combining**

* [Chain](src/test/java/rx/observables/combining/ObservableChain.java)
* [Concat](src/test/java/rx/observables/combining/ObservableConcat.java)
* [Merge](src/test/java/rx/observables/combining/ObservableMerge.java)
* [Zip](src/test/java/rx/observables/combining/ObservableZip.java)
* [Switch](src/test/java/rx/observables/combining/ObservableSwitch.java)
* **Creating**

* [Create](src/test/java/rx/observables/creating/ObservableCreate.java)
* [Defer](src/test/java/rx/observables/creating/ObservableDefer.java)
* [Interval](src/test/java/rx/observables/creating/ObservableInterval.java)
* [Subscription](src/test/java/rx/observables/creating/ObservableSubscription.java)
* **Filtering**

* [Debounce](src/test/java/rx/observables/filtering/ObservableDebounce.java)
* [Distinct](src/test/java/rx/observables/filtering/ObservableDistinct.java)
* [Skip](src/test/java/rx/observables/filtering/ObservableSkip.java)
* [Take](src/test/java/rx/observables/filtering/ObservableTake.java)
* [First](src/test/java/rx/observables/filtering/ObservableFirst.java)
*[Run java classes](src/test/java/java11/HelloWorld11.java)
* **Transforming**

* [Map](src/test/java/rx/observables/transforming/ObservableMap.java)
* [FlatMap](src/test/java/rx/observables/transforming/ObservableFlatMap.java)
* [GroupBy](src/test/java/rx/observables/transforming/ObservableGroupBy.java)
* [Scan](src/test/java/rx/observables/transforming/ObservableScan.java)
* [Collect](src/test/java/rx/observables/transforming/ObservableCollect.java)
* [Buffer](src/test/java/rx/observables/transforming/ObservableBuffer.java)
* [Window](src/test/java/rx/observables/transforming/ObservableWindow.java)
* [Compose](src/test/java/rx/observables/transforming/ObservableCompose.java)
* **Scheduler**

* [Asynchronous](src/test/java/rx/observables/scheduler/ObservableAsynchronous.java)
* **Errors**

* [Exceptions](src/test/java/rx/observables/errors/ObservableExceptions.java)
* **Utils**
* [Delay](src/test/java/rx/observables/utils/ObservableDelay.java)
* [AmbConditional](src/test/java/rx/observables/utils/ObservableAmbConditional.java)
* [Cache](src/test/java/rx/observables/utils/ObservableCache.java)
* [ToBlocking](src/test/java/rx/observables/utils/ObservableToBlocking.java)
* **Single**
An Observable that just emit 1 item through the pipeline.
* [SingleFeatures](src/test/java/rx/single/SingleFeatures.java)
* **Relay**
A subject which subscribe observers and keep the pipeline open all the time.
* [Relay](src/test/java/rx/relay/Relay.java)
## Spring Reactor

The reactive stream API implementation of Spring.

* [Creating](src/test/java/reactor/ReactorCreating.java)

* [Combining](src/test/java/reactor/ReactorCombining.java)

* [Transforming](src/test/java/reactor/ReactorTransforming.java)

* [Filtering](src/test/java/reactor/ReactorFiltering.java)

* [Async](src/test/java/reactor/ReactorAsync.java)
## Akka

Implementation of Akka patterns using Akka typed, using Java DSL.
* [patterns](src/test/java/akka/AkkaFeatures.java)
## Akka Stream
The reactive stream API implementation of Akka.
* [Source, Flow, Sink](https://github.com/politrons/Akka/blob/master/src/main/scala/stream/AkkaStream.scala)
* [Subscriber](https://github.com/politrons/Akka/blob/master/src/main/scala/stream/Subscriber.scala)
* [Back-pressure](https://github.com/politrons/Akka/blob/master/src/main/scala/stream/BackPressure.scala)
* [GraphDSL](https://github.com/politrons/Akka/blob/master/src/main/scala/stream/Graphs.scala)
## RSocket

Binary protocol for use on byte stream transports.
* [Fire and Forget](src/test/java/rsocket/RSocketFireAndForget.java)
* [Request Response](src/test/java/rsocket/RSocketRequestResponse.java)
* [Request Stream](src/test/java/rsocket/RSocketRequestStream.java)
* [Request Channel](src/test/java/rsocket/RSocketRequestChannel.java)
## Quarkus

Example of most important features of the red hat framework.
* [features](quarkus/)
## Micronaut

A modern, JVM-based, full-stack framework for building modular, easily testable microservice and serverless
applications.
* [features](https://github.com/politrons/micronaut)
## Oracle Helidon

Helidon is a collection of Java libraries for writing microservices that run on a fast web core powered by Netty.
* [WebClient / WebServer](src/test/java/helidon/HelidonWebServer.java)
* [Reactive Messaging](src/test/java/helidon/HelidonReactiveMessaging.java)
* [Kafka connector](src/test/java/helidon/HelidonKafka.java)
* [Scheduler](src/test/java/helidon/HelidonScheduler.java)
##

Example of most important features of this functional programing library for Java.
* [effects](src/test/java/vavr/VavrEffects.java)
* [Functions](src/test/java/vavr/VavrFunctions.java)
* [Collections](src/test/java/vavr/VavrCollections.java)
* [Pattern matching](src/test/java/vavr/VavrPatternMatching.java)
* [Future](src/test/java/vavr/VavrFuture.java)
## Category Theory

Example of Monad implementation for Java.
* [monad](src/test/java/effects/PolEffectSystem.java)
## 
Apache Curator is a Java/JVM client library for Apache ZooKeeper, a distributed coordination service.
* [distributed lock and counter](src/test/java/curator/ApacheCuratorFeature.java)
## Reactive Stream Monads combination
A Combination of Monads that implement Reactive Stream.
* [ReactiveStream](src/test/java/ReactiveMonadsCombinations.java)
## Observer V Iterator Pattern
An explanation, comparative and benchmark between these two patterns.
* [ObserverVsIterator](src/test/java/rx/utils/ObserverVsIterator.java)
## RxJava V Spring Reactor
A Comparative and benchmark between these two frameworks.
* [ReactorVsRx](src/test/java/rx/utils/ReactorVsRx.java)
## Java 8

* [Stream](src/test/java/java8/StreamUtils.java)
* [Functions](src/test/java/java8/Functions.java)
* [CompletableFuture](src/test/java/java8/CompletableFutureFeature.java)
## Java 9

* [Flow](src/test/java/java9/FlowFeatures.java)
* [Features](src/test/java/java9/UtilFeatures.java)
* [Optional](src/test/java/java9/OptionalImprovements.java)
* [Module system](src/test/java/module-info.java.bak)
## Java 10

* [Collections](src/test/java/java10/Collections.java)
* [Local variable type inference](src/test/java/java10/LocalVariableTypeInference.java)
## Java 11

* [HttpClient2](src/test/java/java11/HttpClient2Feature.java)
* [String](src/test/java/java11/StringFeatures.java)
* [File](src/test/java/java11/FileFeatures.java)
* [Collection](src/test/java/java11/CollectionFeatures.java)
* [Local variable](src/test/java/java11/LocalVariableFeature.java)
## Java 12

* [Switch Expression](https://github.com/politrons/reactive/blob/master/src/test/java/java12/Java12Features.java#L16)
* [String API](https://github.com/politrons/reactive/blob/master/src/test/java/java12/Java12Features.java#L50)
* [JVM Constants API](https://github.com/politrons/reactive/blob/master/src/test/java/java12/Java12Features.java#L101)
## Java 14

* [Pattern matching](https://github.com/politrons/reactive/blob/master/src/test/java/java14/Java14Features.java#L11)
* [Multiline text](https://github.com/politrons/reactive/blob/master/src/test/java/java14/Java14Features.java#L31)
* [Record type](https://github.com/politrons/reactive/blob/master/src/test/java/java14/Java14Features.java#L54)
## Java 15
* [Sealed class](src/test/java/java15/Java15Features.java)
## Java 16

* [Features](src/test/java/java16/Java16Features.java)
## Java 17

* [Features](src/test/java/java17/Java17Features.java)
## Java 18
Project Loom feature
* [Features](src/test/java/loom/LoomFeatures.java)
## Java 19
Pattern matching improvements & Virtual Thread
* [Features](src/test/java/java19/Java19Features.java)
## 
Eclipse Collections is one of the best Java collections framework ever that brings happiness to your Java development.
* [feature](src/test/java/eclipse_collection/EclipseCollectionFeature.java)
## 
Examples of patterns using Apache Kafka.
* **[Throttling](kafka/src/test/java/com/politrons/kafka/KafkaThrottling.java)**
* **[Assign](kafka/src/test/java/com/politrons/kafka/KafkaAssignment.java)**
* **[Stream](kafka/src/test/java/com/politrons/kafka/KafkaStreamFeature.java)**
* **[balancing](kafka/src/test/java/com/politrons/kafka/KafkaBalancing.java)**
* **[Sagas](kafka/src/test/java/com/politrons/kafka/sagas/KSaga.java)**
* **[Delay](kafka/src/test/java/com/politrons/kafka/KafkaDelay.java)**
* **[AdminClient](kafka/src/test/java/com/politrons/kafka/KafkaAdminClient.java)**
## Software craftsmanship
* [(S)ingle responsibility principle](src/test/java/good_practices/SRP.java)
* [(O)pen/Closed principle](src/test/java/good_practices/OpenClosedPrinciple.java)
* [(L)iskov substitution principle](src/test/java/good_practices/LiskovSubstitutionPrinciple.java)
* [(I)nterface segregation principle](src/test/java/good_practices/InterfaceSegregationPrinciple.java)
* [(D)on't repeat yourself](src/test/java/good_practices/DRY.java)
## Programs
* [PaymentAPI:](https://github.com/politrons/PaymentAPI) A Reactive microservice with DDD + CQRS + Event Sourcing
* [Reactive StarWars](https://github.com/politrons/reactiveStarWars) A Star wars reactive microservice platform, formed
by four services
| 0 |
lkrnac/book-eiws-code-samples | Examples for book Pivotal Certified Spring Enterprise Integration Specialist Exam A Study Guide | null | [ ](https://codeship.com/projects/68847)
Examples for book **Pivotal Certified Spring Enterprise Integration Specialist Exam A Study Guide** http://www.apress.com/9781484207949
# More information
http://lkrnac.net/blog/2015/10/enterprise-spring-examples-and-integration-tests
# Build
cd 0000-examples-parent
mvn clean install
cd ../0000-examples
mvn clean install
# Possible first time build error
Error message:
[ERROR] Failed to execute goal org.hornetq:hornetq-maven-plugin:1.2.0:start (start) on project 0501-jms11-jndi: Execution start of goal org.hornetq:hornetq-maven-plugin:1.2.0:start failed: A required class was missing while executing org.hornetq:hornetq-maven-plugin:1.2.0:start: org/slf4j/LoggerFactory
Just continue build where it ended:
mvn clean install -rf :0501-jms11-jndi
| 0 |
berndruecker/trip-booking-saga-java | Example implementation of the Saga pattern for the classic trip booking example using the lightweight open source workflow engine (Camunda). | saga-pattern | # Saga example: trip booking
The Saga pattern describes how to solve distributed (business) transactions without two-phase-commit as this does not scale in distributed systems. The basic idea is to break the overall transaction into multiple steps or activities. Only the steps internally can be performed in atomic transactions but the overall consistency is taken care of by the Saga. The Saga has the responsibility to either get the overall business transaction completed or to leave the system in a known termination state. So in case of errors a business rollback procedure is applied which occurs by calling compensation steps or activities in reverse order. A more detailed look on Sagas is available in [Saga: How to implement complex business transactions without two phase commit](
https://blog.bernd-ruecker.com/saga-how-to-implement-complex-business-transactions-without-two-phase-commit-e00aa41a1b1b)
In the example hotel, car and flight booking might be done by different remote services. So there is not technical transaction, but a business transaction. When the flight booking cannot be carried out succesfully you need to cancel hotel and car.

Using [Camunda](https://camunda.org/) you can implement the Saga either by using graphical modeling or by a Java DSL, called Model-API. As Camunda is very lightweight you can start the so called process engine, define the Saga and run instances by a couple of lines of Java code (if you use the default configuration and an in-memory H2 database), see [TripBookingSaga.java](src/main/java/io/flowing/trip/saga/camunda/simple/TripBookingSaga.java):
```java
public class TripBookingSaga {
public static void main(String[] args) {
// Configure and startup (in memory) engine
ProcessEngine camunda =
new StandaloneInMemProcessEngineConfiguration()
.buildProcessEngine();
// define saga as BPMN process
ProcessBuilder saga = Bpmn.createExecutableProcess("trip");
// - flow of activities and compensating actions
saga.startEvent()
.serviceTask("car").name("Reserve car").camundaClass(ReserveCarAdapter.class)
.boundaryEvent().compensateEventDefinition().compensateEventDefinitionDone()
.compensationStart().serviceTask("car-compensate").name("Cancel car").camundaClass(CancelCarAdapter.class).compensationDone()
.serviceTask("hotel").name("Book hotel").camundaClass(BookHotelAdapter.class)
.boundaryEvent().compensateEventDefinition().compensateEventDefinitionDone()
.compensationStart().serviceTask("hotel-compensate").name("Cancel hotel").camundaClass(CancelHotelAdapter.class).compensationDone()
.serviceTask("flight").name("Book flight").camundaClass(BookFlightAdapter.class)
.boundaryEvent().compensateEventDefinition().compensateEventDefinitionDone()
.compensationStart().serviceTask("flight-compensate").name("Cancel flight").camundaClass(CancelFlightAdapter.class).compensationDone()
.endEvent();
// - trigger compensation in case of any exception (other triggers are possible)
saga.eventSubProcess()
.startEvent().error("java.lang.Throwable")
.intermediateThrowEvent().compensateEventDefinition().compensateEventDefinitionDone()
.endEvent();
// finish Saga and deploy it to Camunda
camunda.getRepositoryService().createDeployment() //
.addModelInstance("trip.bpmn", saga.done()) //
.deploy();
// now we can start running instances of our saga - its state will be persisted
camunda.getRuntimeService().startProcessInstanceByKey("trip", Variables.putValue("name", "trip1"));
camunda.getRuntimeService().startProcessInstanceByKey("trip", Variables.putValue("name", "trip2"));
}
}
```
The real logic is attached as Java code by the adapter classes, e.g. the [BookHotelAdapter](src/main/java/io/flowing/trip/saga/camunda/adapter/BookHotelAdapter.java).
The definition might look a bit verbose, as you have to use BPMN terminology. But you could write a thin [SagaBuilder](src/main/java/io/flowing/trip/saga/camunda/springboot/builder/SagaBuilder.java) that improves readability of the Saga definition:
```java
SagaBuilder saga = SagaBuilder.newSaga("trip")
.activity("Reserve car", ReserveCarAdapter.class)
.compensationActivity("Cancel car", CancelCarAdapter.class)
.activity("Book hotel", BookHotelAdapter.class)
.compensationActivity("Cancel hotel", CancelHotelAdapter.class)
.activity("Book flight", BookFlightAdapter.class)
.compensationActivity("Cancel flight", CancelFlightAdapter.class)
.end()
.triggerCompensationOnAnyError();
camunda.getRepositoryService().createDeployment()
.addModelInstance(saga.getModel())
.deploy();
```
The engine will take care of state handling, compensation and could also handle timeouts and escalations.
In real-life scenarios you might configure and run the Camunda engine differently, e.g. by using Spring or Spring Boot. In this example you can also use the [Spring Boot Application](src/main/java/io/flowing/trip/saga/camunda/springboot/Application.java) in order to fire the application up - and afterwords even connect Camundas visual tooling.
A visual representation is automatically created in the background by Camunda. (**You need to use Camunda in a version >= 7.8.0.**)

The flow can also be modeled graphically instead of using the Model API. In this case use the [Camunda Modeler](https://camunda.org/download/modeler/) to draw the BPMN notation:

The [trip.bpmn (BPMN model file)](docs/trip.bpmn)
# Get started
You need
* Java
* Maven
Required steps
* Checkout or download this project
* Run the [Application.java](src/main/java/io/flowing/trip/saga/camunda/springboot/Application.java) class as this is a Spring Boot application running everything at once, starting exactly one Saga that is always "crashing" in the flight booking
* If you like you can access the Camunda database from the outside, e.g. using the ["Camunda Standalone Webapp"](https://camunda.org/download/) to inspect state. Use the follwing connection url: ```jdbc:h2:tcp://localhost:8092/mem:camunda;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE```. Note that you need [Camunda Enterprise](https://camunda.com/trial/) to see historical data.
As an alternative:
* Run the [TripBookingSaga.java](src/main/java/io/flowing/trip/saga/camunda/simple/TripBookingSaga.java) class via your favorite IDE - it also will run instances of the Saga without requiring any infrastructure
| 1 |
douglascraigschmidt/LiveLessons | This repository contains all the source code examples from my LiveLessons course on Java Concurrent Programming" and my various LiveTraining courses | as described at http://www.dre.vanderbilt.edu/~schmidt/DigitalLearning." | LiveLessons and LiveTraining Source Repo
========================================
This GitHub repo contains source code examples from my LiveLessons
courses on [Design Patterns in
Java](http://www.dre.vanderbilt.edu/~schmidt/LiveLessons/DPiJava/) and
[Java
Concurrency](http://www.dre.vanderbilt.edu/~schmidt/LiveLessons/CPiJava/),
as well as my LiveTraining courses on [Java 8
Concurrency](https://www.safaribooksonline.com/live-training/courses/java-8-concurrency/0636920091080/).
| 0 |
codingXiaxw/ssm | :on: a simple example introducing SSM's basic development knowledge with detailed manual | null | ## 一个案例带你快速入门SSM开发
**写在前面的话:**关于SSM框架的工程搭建请点击这里前往我的博客[SSM整合工程的搭建](http://codingxiaxw.cn/2016/11/15/44-ssm%E7%9A%84%E6%95%B4%E5%90%88/)
## 开发环境
IDEA Spring3.x+SpringMVC+Mybatis
没有用到maven管理工具。
## 1.实现商品的列表展示
### 1.1提出需求
功能描述:在页面中展示商品列表。
### 1.2编写表
sql语句见github中.sql文件。
### 1.3持久层mapper的编写
编写好数据库后我们便可以通过MyBatis逆向工程快速生成对单表映射的sql,包括mapper.java、mapper.xml和pojo类。
根据逆向工程生成的这三个文件与单表都是一对一的关系,例如通过Items表会生成ItemsMapper.java、ItemsMapper.xml和Items.java的pojo类,这里我们为了便于需求的扩展,所以另外自己编写一个ItemsCustom.java并继承Items.java和Items.java的包装类ItemsQueryVo.java,代码如下:
```java
public class ItemsQueryVo {
//商品信息
private ItemsCustom itemsCustom;
public ItemsCustom getItemsCustom() {
return itemsCustom;
}
public void setItemsCustom(ItemsCustom itemsCustom) {
this.itemsCustom = itemsCustom;
}
}
```
然后自己编写一个ItemsCustomerMapper.xml:
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.ItemsMapperCustom">
<!-- 商品查询的sql片段
建议是以单表为单位定义查询条件
建议将常用的查询条件都写出来
-->
<sql id="query_items_where">
<if test="itemsCustom!=null">
<if test="itemsCustom.name!=null and itemsCustom.name!=''">
and name like '%${itemsCustom.name}%'
</if>
<if test="itemsCustom.id!=null">
and id = #{itemsCustom.id}
</if>
</if>
</sql>
<!-- 商品查询
parameterType:输入 查询条件
-->
<select id="findItemsList" parameterType="po.ItemsQueryVo"
resultType="po.ItemsCustom">
SELECT * FROM items
<where>
<include refid="query_items_where"/>
</where>
</select>
</mapper>
```
与ItemsCustomMapper.java:
```java
public interface ItemsMapperCustom {
// 商品查询列表
List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
throws Exception;
}
```
至于Mapper的配置我们已经在springmvc.xml中通过spring组件扫描器
```xml
<!--
MapperScannerConfigurer:mapper的扫描器,将包下边的mapper接口自动创建代理对象,
自动创建到spring容器中,bean的id是mapper的类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置扫描包的路径
如果要扫描多个包,中间使用半角逗号分隔
要求mapper.xml和mapper.java同名且在同一个目录
-->
<property name="basePackage" value="mapper"/>
<!-- 使用sqlSessionFactoryBeanName -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
```
进行了统一的配置。
接口里面调用xml文件中查询表中所有商品列表信息的sql语句,然后我们便可以进行业务逻辑层的代码编写.
### 1.4业务逻辑层service的编写
首先我们在service包下创建一个商品的service接口ItemsService.java文件,里面编写的方法和ItemsCustomMapper.java中的方法对应以实现商品列表的查询:
```java
public interface ItemsService {
//商品的查询列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)
throws Exception;
}
```
然后编写其实现类ItemsServiceImpl.java:
```java
public class ItemsServiceImpl implements ItemsService {
//注入mapper
@Autowired
private ItemsMapperCustom itemsMapperCustom;
//商品的查询列表
@Override
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
}
```
代码中通过Spring框架的DI注入依赖对象mapper即itemsMapperCustom对象,然后调用itemsMapperCustom的findItemsList方法实现商品列表查询,然后在spring配置文件applicationContext-service.xml中要进行service的配置,添加如下标签:
```xml
<!--商品配置的service-->
<bean id="itemsService" class="service.impl.ItemsServiceImpl"/>
```
便可。接下来便应该完成控制层Controller.java的代码编写了。
### 1.5控制层Controller的编写
在controller包下创建一个ItemsController.java,里面编写代码:
```java
@Controller
public class ItemsController {
//注入service
@Autowired
private ItemsService itemsService;
@RequestMapping("/queryItems")
public ModelAndView queryItems() throws Exception {
//调用servie来查询商品列表
List<ItemsCustom> itemsList=itemsService.findItemsList(null);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("itemsList",itemsList);
//指定逻辑视图名itemsList
modelAndView.setViewName("itemsList");
return modelAndView;
}
}
```
通过@Autowired注解完成service的依赖注入,通过@Controller注解将Controller自动添加到spring容器IOC中,通过@RequestMapping("/queryItems")注解指明访问该Controller的url。
至于itemsList.jsp的页面编写代码如下:
```xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/items/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td>商品价格</td>
<td>生产日期</td>
<td>商品描述</td>
<td>操作</td>
</tr>
<c:forEach items="${itemsList }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.price }</td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
```
然后我们运行服务器,输入网址`http://localhost:8080/SpringMvcMybatis/queryItems.action`,发现无法看到页面,这是因为我们的spring配置文件没有得到加载,需要在web.xml文件中加入如下内容进行spring容器的配置:
```xml
<!--配置spring容器监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/config/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
```
然后重新运行服务器并输入网址,看到如下页面,说明成功使用SSM框架完成开发显示商品列表的项目:

到此,我们便通过SSM的整合工程项目,完成了对商品列表的查询。接下来我们再实现对商品的另一个功能:修改商品信息。
## 2.实现商品信息的修改
### 2.1需求
功能描述:商品信息修改。操作流程:1.在商品列表页面点击修改连接。2.打开商品修改页面,显示了当前商品的信息(根据商品id查询商品信息)。3.修改商品信息,点击提交(更新商品信息)。
通过此案例,我们也会穿插用SSM进行注解开发的基础知识如: @RequestMapping注解的改善、controller方法返回值、Controller方法中的参数与页面参数的绑定。
### 2.2mapper的编写
此功能涉及到的mapper为ItemsMapper.java与ItemsMapper.xml,已使用逆向工程为我们生成。
### 2.3service的编写
在ItemsService接口中添加方法:
```java
//根据商品id查询商品信息
public ItemsCustom findItemsById(int id) throws Exception;
//更新商品信息
/**
* 定义service接口,遵循单一职责,将业务参数细化(不要使用包装类型,比如map)
* @param id 修改商品的id
* @param itemsCustom 修改商品的信息
* @throws Exception
*/
public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception;
```
然后是实现类ItemsServiceImpl.java:
```java
//注入依赖对象itemsMapper
@Autowired
private ItemsMapper itemsMapper;
@Override
public ItemsCustom findItemsById(int id) throws Exception {
Items items=itemsMapper.selectByPrimaryKey(id);
//在这里以后随着需求的变化,需要查询商品的其它相关信息,返回到controller
//所以这个时候用到扩展类更好,如下
ItemsCustom itemsCustom=new ItemsCustom();
//将items的属性拷贝到itemsCustom
BeanUtils.copyProperties(items,itemsCustom);
return itemsCustom;
}
@Override
public void updateItems(Integer id,ItemsCustom itemsCustom) throws Exception {
//在service中一定要写业务代码
//对于关键业务数据的非空校验
if (id==null)
{
//抛出异常,提示调用接口的用户,id不能唯恐
//...
}
itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
}
```
说一句:对service的开发是整个系统中开发最重要的部分,所以你要把service的开发放在学习的重点上。接下来就要写Controller的代码了,然而写Controller的过程中会学到很多注解开发的基础知识。
### 2.4Controller的编写之@RequestMapping的特性学习
#### 2.4.1窄化请求映射
我们除了在Controller方法的上面加上一个@RequestMapping的注解指定url外(完成url映射),还可以在Controller类的上面指定一个@RequestMapping注解指定访问路径的根url,如这里我们是对商品的操作,所以可以在Controller类上面加上一个@RequestMapping的注解指定访问商品信息的根路径(叫“窄化请求映射”):
```java
@Controller
//定义url的根路径,访问时根路径+方法名的url
@RequestMapping("/items")
public class ItemsController {
}
```
使用窄化请求映射的好处:更新规范系统的url,避免url冲突。
然后继续我们的Controller开发,添加方法:
```java
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
public ModelAndView editItems() throws Exception
{
ModelAndView modelAndView=new ModelAndView();
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(1);
//将模型数据传到jsp
modelAndView.addObject("item",itemsCustom);
//指定逻辑视图名
modelAndView.setViewName("editItem");
return modelAndView;
}
```
编写editItem.jsp页面:
```xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改商品信息</title>
</head>
<body>
<form id="itemForm" action="${pageContext.request.contextPath }/items/editItemSubmit.action" method="post" >
<input type="hidden" name="id" value="${id }"/>
修改商品信息:
<table width="100%" border=1>
<tr>
<td>商品名称</td>
<td><input type="text" name="name" value="${itemsCustom.name }"/></td>
</tr>
<tr>
<td>商品价格</td>
<td><input type="text" name="price" value="${itemsCustom.price }"/></td>
</tr>
<tr>
<td>商品简介</td>
<td>
<textarea rows="3" cols="30" name="detail">${itemsCustom.detail }</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
</body>
</html>
```
然后运行服务器,此时应该输入网址`http://localhost:8080/SpringMvcMybatis/items/queryItems.action`而不是`http://localhost:8080/SpringMvcMybatis/queryItems.action`,然后点击右边的修改链接便可以进去相应的修改页面:
#### 2.4.2限制http请求的方法
不知道你发现没有,我们在Controller的editItems()方法上的注解中加入的是`value = "/editItems",method = RequestMethod.GET`参数而不再是单单的`"/editItems"`参数了,这里我们便用到了使用@RequestMapping注解限制http请求的方法。如果你将这里的`method = RequestMethod.GET`改为`method = RequestMethod.POST`,然后在页面中再点击修改链接时就会报错。
另外method属性的属性值为数组,我们也可以将注解中的参数改为`ethod = {RequestMethod.GET,RequestMethod.POST}`表示请求既可以为POST请求又可以为GET请求。
### 2.5Controller的编写之Controller方法返回值学习
#### 2.5.1返回ModerAndView
目前我们使用的方式都是返回的ModerAndView对象,例如我们已经编写的Controller中的queryItems()方法和editItems()方法。接下来我们看看返回字符串的方法编写。
#### 2.5.2返回字符串
首先注释掉我们返回值为ModerAndView类型的editItems()方法。如果controller方法返回jsp页面,可以简单将方法返回值类型定义 为字符串,最终返回逻辑视图名。编写返回值为String类型的editItems()方法,代码如下:
```java
//方法返回字符串,字符串就是逻辑视图名,Model作用是将数据填充到request域,在页面显示
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
public String editItems(Model model) throws Exception
{
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(1);
model.addAttribute("itemsCustom",itemsCustom);
return "editItem";
}
```
方法中我们需要传入一个Model对象,作用是将数据填充到request域,在页面显示。然后运行服务器,输入`http://localhost:8080/SpringMvcMybatis/items/queryItems.action`照常正确访问该网站。再来介绍返回值为void的方法。
#### 2.5.3返回void
同样注释掉返回值为String类型的editItems()方法,然后加入返回值为void的editItems()方法:
```java
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
public void editItems(HttpServletRequest request, HttpServletResponse response) throws Exception
{
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
request.setAttribute("item",itemsCustom);
//注意如果使用request转向页面,这里需要指定页面的完整路径
request.getRequestDispatcher("/WEB-INF/jsp/editItem.jsp").forward(request,response);
}
```
其实这里就是运用的原生态的Servlet的开发方式,运行服务器,输入`http://localhost:8080/SpringMvcMybatis/items/queryItems.action`仍照常正确访问该网站。
通过这种返回值为void的方法我们容易输出json、xml格式的数据,即通过response指定响应结果,例如响应json数据如下:
```java
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
```
上面我们就通过完成商品信息的编辑功能介绍了Controller中三种返回值类型的方法。而通过返回字符串的方法,有时候会返回一些特殊的字符串(例如返回`return "forward:url路径"`或`return "redirect:url路径"`)。分别代表请求转发和请求冲定向,下面我们通过完善编辑商品信息后进行提交的功能来讲解这两种返回特殊字符串类型的方法。在Controller中添加editItemSubmit()方法:
```java
//商品提交页面
//itemsQueryVo是包装类型的pojo
@RequestMapping("/editItemSubmit")
public String editItemSubmit() throws Exception
{
//请求转发,使用forward进行请求转发,request数据可以共享,url地址栏不会
// return "forward:queryItems.action";
//使用redirect进行重定向,request数据无法共享,url地址栏会发生变化的。由于我们重定向的页面queryItems.action与本页面editItemSubmit.action在同一根目录下,所以不需要加入根路径
return "redirect:queryItems.action";
}
```
运行服务器,然后我们便可以在editItems.jsp页面通过点击"提交"按钮请求转发或者请求重定向到我们的`queryItems.action`页面。如上,我便介绍完Contoller方法返回值的知识。接下来介绍Controller方法中的参数与页面参数绑定的知识。
### 2.6Controller的编写之方法参数与页面参数的绑定
不知你注意到没有,在Controller的方法中我们传入的参数都是我们自己根据需求手动传入的参数,而真正的需求中我们是需要将页面中的参数传递到Controller的方法中的,那如何将页面的参数绑定到Controller的方法中呢?看下方参数绑定的过程图解:

首先我们看看Controller的方法中默认支持的形参(即之前我们根据需求手动传入的参数,这些参数处理适配器会默认识别并进行赋值)有:1.HttpServletRequest:通过request对象获取请求信息。 2.HttpServletResponse:通过response处理响应信息。3.HttpSession:通过session对象得到session中存放的对象。4.Model/modelmap/map:通过model向页面传递数据,页面通过${item.XXXX}获取item对象的属性值,如下:
```java
//调用service查询商品信息
Items item = itemService.findItemById(id);
model.addAttribute("item", item);
```
但是值得我们关心的不是这些默认的参数,而是我们自定义参数传入Controller方法的形参中,继续往下面看。
#### 2.6.1@RequestParam
如果request请求的参数名和controller方法的形参数名称一致,适配器自动进行参数绑定。如果不一致可以通过
@RequestParam 指定request请求的参数名绑定到哪个方法形参上。
对于必须要传的参数,通过@RequestParam中属性required设置为true,如果不传此参数则报错。
对于有些参数如果不传入,还需要设置默认值,使用@RequestParam中属性defaultvalue设置默认值。
例如Controller中的方法:
```java
@RequestMapping(value = "/editItems",method = RequestMethod.GET)
public void editItems(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "item_id",required = false,defaultValue = "1") Integer id) throws Exception
{
//调用service查询商品的信息
ItemsCustom itemsCustom=itemsService.findItemsById(id);
request.setAttribute("item",itemsCustom);
//zhuyi如果使用request转向页面,这里需要指定页面的完整路径
request.getRequestDispatcher("/WEB-INF/jsp/editItem.jsp").forward(request,response);
}
```
没对形参id加上@RequestParam注解时,当我们从页面进入到editItems.action时,只有从页面传入的参数名为id时该id参数值才会传到editItems()方法的id参数值上,如果从页面传入的参数明不为id而为其他参数名时例如`http://localhost:8080/SpringMvcMybatis/items/editItems.action?item_id=1`,此时通过调试会发现editItems()方法中的id属性值为null;而当我们为形参id加上了@RequestParam注解并指定了其属性`value = "item_id"`后,若从页面传入的参数名为item_id,则该参数值会因为添加了`value = "item_id"`该属性而被赋值给id属性。`required`属性若设置为true,则如果从页面进入到editItem.action时没有传入此参数则会报错。`defaultvalue`属性值表示为该参数赋默认值。
#### 2.6.2绑定简单类型
上述那个editItem()方法时原始的servlet开发方法,接下来我们用返回值为String 类型的方法进行注解开发的基础知识讲解。
可以绑定整型、字符串、单精/双精度、日期、布尔型,很简单处理,我不进行讲解,通过下面绑定pojo类型你就会清楚了。
#### 2.6.3绑定pojo类型
绑定pojo类型又可以分为绑定简单pojo类型和绑定包装pojo类型。
##### 2.6.3.1绑定简单pojo类型
简单pojo类型只包括简单类型的属性。绑定过程:request请求的参数名称和pojo的属性名一致,就可以绑定成功。
修改Controller中的editItemSubmit()方法:
```java
//商品提交页面
//itemsQueryVo是包装类型的pojo
@RequestMapping("/editItemSubmit")
public String editItemSubmit(Integer id,ItemsCustom itemsCustom) throws Exception
{
//进行数据回显
model.addAttribute("id",id);
// model.addAttribute("item",itemsCustom);
itemsService.updateItems(id,itemsCustom);
//请求转发
// return "forward:queryItems.action";
//重定向
return "redirect:queryItems.action";
}
```
点击提交按钮,从editItem.jsp页面进入editItemSubmit.action时,就会将编辑页面的参数都映射到该方法的id形参和ItemsCustom对象中,此时我们修改商品的信息,然后点击提交按钮,服务器反应过程如下:点击提交按钮,页面从editItem.jsp进入到editItemSubmit.action并将修改后的商品信息提交到数据库并将这些参数传入到ItemsCustom对象的属性中,然后重定向到queryItems.action进行商品的列表信息展示。
**问题:**如果controller方法形参中有多个pojo且pojo中有重复的属性,使用简单pojo绑定无法有针对性的绑定,比如:方法形参有items和User,pojo同时存在name属性,从http请求过程的name无法有针对性的绑定到items或user。要解决此种方法我们就需要用到下面的绑定包装的pojo类型。
##### 2.6.3.2绑定包装的pojo类型
这里我们复制editItem.jsp页面粘贴出一个editItem2.jsp页面,染护修改editItem2.jsp中的参数名为itemsCustom.name、itemsCustom.price、itemsCustom.detail,修改Controller中的editItemSubmit方法中的形参为`public String editItemSubmit(Integer id,ItemsCustom itemsCustom,ItemsQueryVo itemsQueryVo) throws Exception{...}
`修改editItems的返回值类型为`editItems2`。运行程序,点击提交按钮,页面信息成功传入到itemsQueryVo的属性中。成功运行后我们还是将信息改回成原来的模样,方便后面的测试。
#### 2.6.4使用属性编辑器完成自定义绑定
此时我们在editItem.jsp中添加上日期的信息展示:
```xml
<tr>
<td>商品生产日期</td>
<td><input type="text" name="createtime" value="<fmt:formatDate value="${itemsCustom.createtime}" pattern="yyyy-MM-dd HH-mm-ss"/>"/></td>
</tr>
```
然后运行程序,当点击提交按钮时会报错,你知道为什么吗?原因是因为通过点击提交按钮,页面中参数名为"createtime"的参数名由于跟Controller方法中的形参ItemsCustom有相同的属性名createtime,所以此时页面中的日期会映射到ItemsCustom的Date属性中,但是从页面传过来的日期是字符串类型,而ItemsCustom的属性是java.util.Date类型,所以当然会报错。这样的话,我们就必须完成日期字符串向java类型日期的转换。此时我们就需要自定义日期类型的绑定,即使用属性编辑器来完成自定义的绑定。有如下两种方法:1.使用WebDataBinder(了解),在Controller中添加如下代码:
```java
//自定义属性编辑器
@InitBinder
public void initBinder(WebDataBinder binder) throws Exception{
//Date.class必须是与controller方法形参pojo属性一致的date类型,这里是java.util.Date
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
}
```
运行程序,点击提交按钮后不会再出现报错信息,且editItem.jsp页面的createtime参数也成功传入到了ItemsCustom的createtime属性中。使用这种方法的问题是无法在多个controller共用。那我们就来介绍第二种方法:使用WebBindingInitializer(了解)。首先我们需要编写一个自定义属性编辑器CustomPropertyEditor.java,代码如下:
```java
public class CustomPropertyEditor implements PropertyEditorRegistrar
{
@Override
public void registerCustomEditors(PropertyEditorRegistry binder) {
binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"),true));
}
}
```
然后要在springmvc.xml文件中加入对它的配置:
```xml
<!-- 注册属性编辑器 -->
<bean id="customPropertyEditor" class="cn.itcast.ssm.propertyeditor.CustomPropertyEditor"></bean>
<!-- 自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="customPropertyEditor"/>
</list>
</property>
</bean>
```
然后要在注解适配器的配置标签中加入如下属性:
```xml
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
```
这样我们便可以注释掉第一种属性编辑器的代码了,使用第二种方式虽然配置很繁琐,但是很适用。运行程序,也成功将editItem.jsp页面的createtime参数映射到ItemsCustom的createtime属性中。下面我再讲一种自定义绑定参数的方法。
#### 2.6.5使用转换器完成自定义参数绑定(想往架构师方向发展的要掌握这种方法)
首先要定义一个转换器CustomDateConverter.java完成日期的转换,代码如下:
```java
public class CustomDateConverter implements Converter<String,Date> {
@Override
public Date convert(String source) {
try{
return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").parse(source);
}catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
```
在定义一个StringTrimConverter.java用于去除日期字符串两边的空格,代码如下:
```java
public class StringTrimConverter implements Converter<String,String> {
@Override
public String convert(String source) {
try{
//去掉字符串两边的空格,如果去除后为空则返回null
if (source!=null)
{
source=source.trim();
if (source.equals(""))
return null;
}
}catch (Exception e)
{
e.printStackTrace();
}
return source;
}
}
```
定义好后就需要对转换器进行配置:思路就是先定义一个转换器然后注入到适配器中。而对于转换器在springmvc.xml中的配置有两种方式,第一种方式针对不使用`<mvc:annotation-driven>`,第二种方式针对使用`<mvc:annotation-driven>`,我们就来讲讲第二种方式。在springmvc.xml中添加如下配置:
```xml
<!--mvc的注解驱动器,通过它可以替代下边的处理器映射器和适配器-->
<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
<!--转换器-->
<!-- conversionService -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="controller.converter.CustomDateConverter"/>
<bean class="controller.converter.StringTrimConverter"/>
</list>
</property>
</bean>
```
使用了注解驱动的配置后,我们就可以注释掉处理器映射器与处理器适配器了。运行程序,也成功将editItem.jsp页面的createtime参数映射到ItemsCustom的createtime属性中。
由于往后我们还要进行json数据的开发,所以这里我们还是不采用使用注解驱动的方式,还是采用注解映射器与注解适配器的方式进行开发。修改后的最后的springmvc.xml配置信息如下:
```xml
<!--使用spring组件扫描
一次性配置此包下所有的Handler-->
<context:component-scan base-package="controller"/>
<!--mvc的注解驱动器,通过它可以替代下边的处理器映射器和适配器-->
<!--<mvc:annotation-driven></mvc:annotation-driven>-->
<!--注解处理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!--注解的适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
</bean>
<!--配置视图解析器
要求将jstl的包加到classpath-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"/>
<!--早期的自定义属性编辑器-->
<!--<property name="propertyEditorRegistrars">-->
<!--<list>-->
<!--<ref bean="customPropertyEditor"/>-->
<!--</list>-->
<!--</property>-->
</bean>
<!-- 注册属性编辑器 -->
<bean id="customPropertyEditor" class="controller.propertyeditor.CustomPropertyEditor"></bean>
<!--mvc的注解驱动器,通过它可以替代下边的处理器映射器和适配器-->
<!--<mvc:annotation-driven conversion-service="conversionService">-->
<!--</mvc:annotation-driven>-->
<!--转换器-->
<!-- conversionService -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="controller.converter.CustomDateConverter"/>
<bean class="controller.converter.StringTrimConverter"/>
</list>
</property>
</bean>
```
这个converter的配置是一劳永逸的配置,也就是系统架构级别的配置,希望你能成功掌握。
好了,通过上述的案例,便成功的使用了SSM框架对对商品信息的三个功能。希望通过这个案例,你能成功掌握SSM框架。接下来我将讲解使用SSM进行注解开发的高级知识。博客链接[SSM注解开发的高级知识讲解](http://codingxiaxw.cn/2016/11/19/46-ssm%E9%AB%98%E7%BA%A7%E5%BC%80%E5%8F%91/),源码链接[点击这里前往我的github](https://github.com/codingXiaxw/ssm2)
## 3.联系
If you have some questions after you see this article,you can tell your doubts in the comments area or you can find some info by clicking these links.
- [Blog@codingXiaxw's blog](http://codingxiaxw.cn)
- [Weibo@codingXiaxw](http://weibo.com/u/5023661572?from=hissimilar_home&refer_flag=1005050003_)
- [Zhihu@codingXiaxw](http://www.zhihu.com/people/e9f78fa34b8002652811ac348da3f671)
- [Github@codingXiaxw](https://github.com/codingXiaxw)
| 1 |
wangjianfengnb/Sample | some blog example | null | null | 1 |
boylegu/SpringBoot-vue | A example demo base SpringBooot with vueJS2.x + webpack2.x as Java full stack web practice | null | []()
[]()
[]()
[]()
[]()
<p align="center">
<a href ="##"><img alt="spring_vue" src="https://github.com/boylegu/SpringBoot-vue/blob/master/images/newlogo.jpg?raw=true"></a></p>
<h4 align="center" style="color: #3399FF">
Convenient & efficient and better performance for Java microservice full stack.
</h4>
<p align="center" style="color: #FF66FF">Commemorate the 6 anniversary of enter the profession.</p>
<p align="center" style="color: #FF9933">Give beginner as a present.</p>
<p align="right" style="color: #3399FF">———————By Boyle Gu</p>
### [Chinese README[中文]](https://github.com/boylegu/SpringBoot-vue/blob/master/README-CN.md)
## Overview
Now about Web develop fields. It's very bloated, outmoded and some development efficiency have a lower with each other than other dynamic language when people refers to Java. Even before somebody shouts loudly ‘Java was died’. But is this really the case? In fact, If you often attention to Java in long time, your feel is too deep. Though it's many disadvantages and verbose. It couldn't be denied that Java is still best language in industry member, and advance with the times. This project is a CRUD demo example base Spring Boot with Vue2 + webpack2. I hope pass thought this project for express Java microservice fast full stack base web practice.
## Why Spring Boot
Spring is a very popular Java-based framework for building web and enterprise applications. Unlike many other frameworks, which focus on only one area, Spring framework provides a wide verity of features addressing the modern business needs via its portfolio project. The main goal of the Spring Boot framework is to reduce overall development time and increase efficiency by having a default setup for unit and integration tests.
In relation to Spring,
Spring Boot aims to make it easy to create Spring-powered, production-grade applications and services with minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need.
The diagram below shows Spring Boot as a point of focus on the larger Spring ecosystem:
<p align="center">
<a href ="##"><img alt="spring_vue" src="https://github.com/boylegu/SpringBoot-vue/blob/master/images/springboot.png?raw=true"></a></p>
The primary goals of Spring Boot are:
- To provide a radically faster and widely accessible ‘getting started’ experience for all Spring development.
- To be opinionated out of the box, but get out of the way quickly as requirements start to diverge from the defaults.
- To provide a range of non-functional features that are common to large classes of projects (e.g. embedded servers, security, metrics, health checks, externalized configuration).
**Spring Boot does not generate code and there is absolutely no requirement for XML configuration.**
Below are this project code snippet. Do you think simple?
~~~~java
@RestController
@RequestMapping("/api/persons")
public class MainController {
@RequestMapping(
value = "/detail/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
public ResponseEntity<Persons> getUserDetail(@PathVariable Long id) {
/*
* @api {GET} /api/persons/detail/:id details info
* @apiName GetPersonDetails
* @apiGroup Info Manage
* @apiVersion 1.0.0
*
* @apiExample {httpie} Example usage:
*
* http GET http://127.0.0.1:8000/api/persons/detail/1
*
* @apiSuccess {String} email
* @apiSuccess {String} id
* @apiSuccess {String} phone
* @apiSuccess {String} sex
* @apiSuccess {String} username
* @apiSuccess {String} zone
*/
Persons user = personsRepository.findById(id);
return new ResponseEntity<>(user, HttpStatus.OK);
}
}
~~~~
## Why MVVM
Although it seems similar to MVC (except with a "view model" object in place of the controller), there's one major difference — the view owns the view model. Unlike a controller, a view model has no knowledge of the specific view that's using it.
This seemingly minor change offers huge benefits:
1. View models are testable. Since they don't need a view to do their work, presentation behavior can be tested without any UI automation or stubbing.
2. View models can be used like models. If desired, view models can be copied or serialized just like a domain model. This can be used to quickly implement UI restoration and similar behaviors.
3. View models are (mostly) platform-agnostic. Since the actual UI code lives in the view, well-designed view models can be used on the iPhone, iPad, and Mac, with only minor tweaking for each platform.
4. Views and view controllers are simpler. Once the important logic is moved elsewhere, views and VCs become dumb UI objects. This makes them easier to understand and redesign.
In short, replacing MVC with MVVM can lead to more versatile and rigorous UI code.
> *In short, replacing MVC with MVVM can lead to more versatile and rigorous UI code.*
## Why to choose Vue.js
Vue.js is relatively new and is gaining lot of traction among the community of developers. VueJs works with MVVM design paradigm and has a very simple API. Vue is inspired by AngularJS, ReactiveJs and updates model and view via two way data binding.
Components are one of the most powerful features of Vue. They help you extend basic HTML elements to encapsulate reusable code. At a high level, components are custom elements that Vue’s compiler attaches behavior to.
<p align="center">
<a href ="##"><img style="box-shadow: 8px 8px 5px #888888;"alt="spring_vue" src="http://i2.muimg.com/536217/5ae4b10becac44b0.png"></a>
## What's Webpack
Webpack is a powerful tool that bundles your app source code efficiently and loads that code from a server into a browser. It‘s excellent solution in frontend automation project.
## Demo
This's a sample ShangHai people information system as example demo.
[]()
### Feature (v0.1)
- Spring Boot (Back-end)
- Build RestFul-API on SpringBoot with `@RequestMapping` and base CRUD logic implementation
- Handle CORS(Cross-origin resource sharing)
- Unit test on SpringBoot
- Support hot reload
- Add interface documents about it's rest-api
- Pagination implementation of RestFul-API with JPA and SpringBoot
- VueJS & webpack (front-end)
- Follow ECMAScript 6
- What about coding by single file components in vueJS
- Simple none parent-child communication and parent-child communication
- Interworking is between data and back-end
- How grace import third JS package in vue
- Handle format datetime
- Pagination implementation
- Reusable components
- DbHeader.vue
- DbFooter.vue (sticky footer)
- DbFilterinput.vue
- DbModal.vue
- DbSidebar.vue
- DbTable.vue
- Config front-end env on webpack2 (include in vue2, handle static file, build different environment...... with webpack2)
### Main technology stack
- Java 1.8+
- Spring Boot 1.5.x
- Maven
- sqlite (not recommend, only convenience example)
- vueJS 2.x
- webpack 2.x
- element ui
- axios
### Preparation
- Please must install Java 1.8 or even higher version
- install Node.js / NPM
- Clone Repository
git clone https://github.com/boylegu/SpringBoot-vue.git
cd springboot_vue
### Installation
- Build front-end environment
cd springboot_vue/frontend
npm install
### Usage
- Run back-end server
cd springboot_vue/target/
java -jar springboot_vue-0.0.1-SNAPSHOT.jar
[]()
- Run Front-end Web Page
cd springboot_vue/frontend
npm run dev
> You can also run `cd springboot_vue/frontend;npm run build` and it's with Nginx in the production environment
## Future Plan
This project can be reference,study or teaching demonstration. After, I will update at every increment version in succession. In future,I have already some plan to below:
1. User Authentication
2. state manage with vuex
3. use vue-route
4. add docker deploy method
5. support yarn
... ...
## Support
1. Github Issue
2. To e-mail: gubaoer@hotmail.com
3. You can also join to QQ Group: 315308272
## Related projects
- [Sanic-Vue for Python](https://github.com/boylegu/SanicCRUD-vue)
## My Final Thoughts
```
. ____ _
/\\ / ___'_ __ _ _(_)_ __ __ _
( ( )\___ | '_ | '_| | '_ \/ _` |
\\/ ___)| |_)| | | | | || (_| |
' |____| .__|_| |_|_| |_\__, |
\ ===========|_|==============|___/== ▀
\- ▌ SpringBoot-vue ▀
- ▌ (o) ▀
/- ▌ Go Go Go ! ▀
/ =================================== ▀
██
```
| 1 |
coditori/javatori | Code Tutorials, Examples, and Best Practices. | best-practices cxf examples hamcrest hibernate java jax-rs junit mockito spring spring-boot spring-data-jpa spring-mvc spring-security swagger-ui tutorial tutorial-code tutorial-exercises tutorials | # Java Code Tutorials, Spring boot Integrations
These projects usually are a simple Enterprise combination of existing technologies. The following sample applications are provided:
<table>
<thead>
<tr>
<th>Sample</th>
<th align="center">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2"><strong>projects</strong></td>
</tr>
<tr>
<td><a href="/projects/spring-boot-reactive-restful-nosql-mongodb">Spring Boot, WebFlux, MongoDB</a></td>
<td align="center">WebFlux API with entire reactive process and Integration Test</td>
</tr>
<tr>
<td><a href="/projects/spring-boot-reactive-restful-rdbms">Spring Boot, WebFlux, H2</a></td>
<td align="center">WebFlux API with reactive web and service layer (not repository layer) and Integration (End-To-End) Test</td>
</tr>
<tr>
<td><a href="/projects/spring-boot-actuator-logger">Spring Boot Actuator</a></td>
<td align="center">If need Log files rather than Actuator Endpoints according to Security concerns, Can be used alongside Syslog and Elasticsearch</td>
</tr>
<tr>
<td><a href="/projects/spring-boot-cxf">Spring Boot, CXF JAX-RS</a></td>
<td align="center">CXF is good for "both" JAX-RS and JAX-WS</td>
</tr>
<tr>
<td><a href="/projects/spring-boot-restful">Spring Boot RESTful</a></td>
<td align="center">If don't care about JAX-RS standards use Spring RESTful</td>
</tr>
<tr>
<td><a href="/projects/spring-boot-maven-modules/spring-boot-restful">"Modular" Spring Boot RESTful</a></td>
<td align="center">A Separated layers project but a Modular application is an old approach take a look at Microservices</td>
</tr>
<tr>
<td><a href="/projects/hibernate">Hibernate</a></td>
<td align="center">A bare Hibernate layer to work on just Data Access Layer (working on DB)</td>
</tr>
</tbody>
</table>
| 0 |
aws-samples/serverless-snippets | Snippets of code used for Serverless Development. Code examples hosted on serverlessland.com/snippets | aws serverless snippets | <div align="center">
<h1>⚡️ Serverless Snippets</h1>
<p>Discover, Explore and Share Serverless Snippets.</>
<hr />
<img alt="header" src="./snippets.png" />
<h3>Features: Discover and explore reuseable code samples, Filter snippets, 1 click deploy, Supports any programming language, and much more...</h3>
[View Snippets](https://serverlessland.com/snippets)
</div>
<hr/>
This repo contains Serverless Snippets that you can copy to help develop your own projects.
These snippets are hosted on [Serverless Land](https://serverlessland.com/snippets).
## Why Serverless Snippets was created?
Across the community and internet there are hundreds of examples of how to use AWS Services with code, tutorials and examples. Often developers are repeating small tasks going back to previous local code snippets and reusing them.
This collection on [ServerlessLand](https://serverlessland.com) is designed to help engineers share useful code with each other.
With Serverless Snippets engineers can find, explore and filter snippets, and as contributions grow we hope Severless Snippets can simplify your development experince.
---
## How can you contribute?
Serverless Snippets is designed to help the community find and explore code and tools. We welcome contributions to the Snippet list. You can add simple snippets, multi stage snippets (instructions), or tabbed snippets (think snippets supporting multiple run times).
- Learn more about these snippets at https://serverlessland.com/snippets.
- To learn more about submitting a snippet, read the [adding snippet guide](https://github.com/aws-samples/serverless-snippets/blob/main/ADDING_SNIPPET.md).
---
## Linking Snippets Directly into the AWS Console.
Thanks to [https://twitter.com/lajacobsson](https://twitter.com/lajacobsson) it is possible to enable the CloudWatch Insights Queries directly into your AWS console and have them update every 12 hours.
Check the project [https://github.com/ljacobsson/cw-logs-insights-snippets](https://github.com/ljacobsson/cw-logs-insights-snippets) to get started.
<img width="1277" alt="image" src="https://user-images.githubusercontent.com/3268013/184601436-61ceb2e0-a128-4490-abc8-6e9ffd5577ca.png">
---
Important: this application could use various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.
----
Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: MIT-0
| 0 |
storm-book/examples-ch06-real-life-app | A Storm Based DRPC Search Engine | null | null | 0 |
bbilger/jrestless-examples | JRestless Examples | api-gateway aws-lambda java jax-rs jersey jrestless serverless | # JRestless Examples
[](https://travis-ci.org/bbilger/jrestless-examples)
[](https://github.com/bbilger/jrestless-examples/issues)
[](https://raw.githubusercontent.com/bbilger/jrestless-examples/master/LICENSE)
This repository contains examples for [JRestlesss](https://github.com/bbilger/jrestless).
## Deployment
JRestless does not depend on the [serverless framework](https://github.com/serverless/serverless) but it simplifies the necessary AWS configuration tremendously. So all examples contain a `serverless` configuration and the installation descriptions assume you have `serverless` installed and configured.
You can install `serverless` as described in the docs https://serverless.com/framework/docs/guide/installing-serverless/
To run the AWS examples setup your AWS account as described in the docs https://serverless.com/framework/docs/providers/aws/guide/credentials/
## Build
All examples can be built either with Gradle or Maven. The default build system, however, is Gradle.
If you want to use Maven you have to replace `artifact: build/distributions/SOME-EXAMPLE.zip` by `artifact: target/SOME-EXAMPLE.jar` in all `serverless.yml` files or at least the example you want to try out. You can run the following script to do this automatically:
```bash
git clone https://github.com/bbilger/jrestless-examples.git
cd jrestless-examples
find . -path ./.git -prune -o -name 'serverless.yml' -type f -exec sed -i 's/artifact: build\/distributions\/\([a-z0-9-]\+\)\.zip/artifact: target\/\1.jar/' {} +
```
The descriptions of the examples are also valid for Gradle, only. If you use Maven, use "mvn package" instead of "./gradlew build".
## Examples
* [AWS](aws)
* [API Gateway](aws/gateway)
* [aws-gateway-showcase](aws/gateway/aws-gateway-showcase)
* Example showing JRestless' features.
* [aws-gateway-spring](aws/gateway/aws-gateway-spring)
* Example showing how to use Spring in JRestless.
* [aws-gateway-cdi](aws/gateway/aws-gateway-cdi)
* Example showing how to use CDI/Weld in JRestless.
* [aws-gateway-cors](aws/gateway/aws-gateway-cors-frontend)
* Example showing how to use CORS in JRestless.
* [aws-gateway-guice](aws/gateway/aws-gateway-guice)
* Example showing how to use Guice in JRestless.
* [aws-gateway-usage-example](aws/gateway/aws-gateway-usage-example)
* Simple JRestless usage example.
* [aws-gateway-binary](aws/gateway/aws-gateway-binary)
* Example showing how to return and receive binary data.
* [aws-gateway-security-cognito-authorizer](aws/gateway/aws-gateway-security-cognito-authorizer)
* Example showing how to use a cognito user pool authorizer.
* [aws-gateway-security-custom-authorizer](aws/gateway/aws-gateway-security-custom-authorizer)
* Example showing how to use a custom authorizer.
* [Lambda Service Function](aws/service)
* [aws-service-usage-example](aws/service/aws-service-usage-example)
* Example showing how to invoke one Lambda (service) function from another (API Gateway).
* [SNS Function](aws/sns)
* [aws-sns-usage-example](aws/sns/aws-sns-usage-example)
* Example showing how to use JRestless to handle SNS notifications.
| 0 |
jonsychen/microservices-examples | 基于Spring Boot/Spring Cloud 的微服务架构 | microservice spring-boot spring-cloud | # 基于Spring Boot/Spring Cloud 的微服务架构
## 项目介绍
### 预备知识
+ <a href="https://start.spring.io/" target="_blank">创建一个Spring Boot初始项目</a>
+ <a href="https://springcloud.cc/" target="_blank">Spring Cloud 相关项目</a>
### 项目结构
+ config : 配置文件仓库
+ api-config : 配置管理中心
+ api-registry : 服务注册中心
+ api-gateway : 服务网关
+ api-monitor : 服务监控中心
+ api-service1 : 测试服务1
+ api-service2 : 测试服务2
### 项目架构

## RUN DEMO
### 运行api-registry
访问地址:http://localhost:8761/

### 运行api-config
### 运行api-gateway
### 运行api-service1,api-service2
### 运行api-monitor
### 运行结束后,配置中心如下:

### 下面开始测试同步/异步接口,同步使用restful,异步使用基于rabbitmq的消息队列实现。
### 示例1(同步)
1.使用postman通过网关访问service1提供的sayhi服务。
2.网关收到请求后,解析请求的url,并匹配动态路由表,找到对应的服务名后向注册中心获取service1服务的当前运行的所有实例,再通过客服端负载均衡,将请求发送到指定的server1服务示例上。
3.service1服务实例收到sayhi请求,同样经过客户端负载均衡后,调用service2服务的指定实例。
4.service2服务实例收到sayhi请求,开始执行sayhi方法,打印并返回“hi from service2”。

### 示例2(异步)
1.使用postman通过网关访问service1提供的send服务。
2.网关收到请求后,解析请求的url,并匹配动态路由表,找到对应的服务名后向注册中心获取service1服务的当前运行的所有实例,再通过客服端负载均衡,将请求发送到指定的service1服务示例上。
3.service1服务实例收到send请求,接收请求参数,并将参数继续发送到指定的队列,等待其他服务处理后续操作,同步返回"message has been sent successfully"。
4.service2监听指定队列,接收到待处理的消息,打印消息内容。
5.service2处理完消息后,将处理结果发送到指定队列。
6.service1监听指定结果通知队列,接收到待处理的消息,打印消息内容。

### 示例3(实现动态配置的更改)
1.使用http get "localhost:8881/author", 来使用网关提供的打印author服务。
2.网关收到打印author的请求,开始打印并返回author为"Jonsy(author.name具体的值定义在配置文件中)。

###
3.修改配置仓库中service1-dev.properties中的author.name为"frank"。
4.使用http post "localhost:8881/bus/refresh?destination=gateway:**",刷新服务名为gateway的所有服务实例。

###
5.再次使用http get "localhost:8881/author", 来使用网关提供的打印author服务。
6.网关收到打印author的请求,开始打印并返回author为"frank”(配置修改已生效)

### 需要注意的地方
1.这个架构使用rabbitmq作为消息总线,所以需要用户自行安装rabbitmq,并修改配置仓库中的相关配置。
2.配置中心里面配置的仓库地址,需要修改为自己的仓库地址。
3.IOC容器中的对象引用配置文件变量的时候,需要在类名上加上@RefreshScope来强制更新,否则动态修改的配置文件内容不会重新加载。
## 联系我
Email: jonsychen@hotmail.com/i@jonsy.me
OICQ: 903352005
WeChat: Jonsychen_2013
| 0 |
dkpro/dkpro-core-examples | Ready-to-use examples of dkpro-core components and pipelines. | null | # Ready-to-use examples of dkpro-core components and pipelines
This package, *dkpro-core-examples*, demonstrates the use of [DKPro Core](http://dkpro.github.io/) components, such as readers, annotators, and writers.
Each module in this project refers to a DKPro core component, providing a simple pipeline that is
usable as is.
This branch uses DKPro Core version 1.9.0-SNAPSHOT.
## Content
So far, *dkpro-core-examples* comprises the following examples:
* **nameannotation-asl**: a dictionary-based name annotator that uses a custom annotation type.
* **lda-asl**: pipelines to demonstrates how to estimate an LDA model and how to use it to infer topic proportions
in documents. Note that the API and hence the examples have changed in v1.9.x.
* **tokenizedwriter-asl**: demonstrates the `TokenizedTextWriter` which writes all tokens from all documents separated
by whitespaces, one sentence per line; can be used to prepare data for external tools such as Word2Vec.
* **stanfordcorecomponents-gpl**: demonstrates the usage of the Stanford Core NLP tools; mind that they are
GPL-licensed!
* **wordembeddings-asl**: a pipeline that shows how to generate [word embeddings](https://en.wikipedia.org/wiki/Word_embedding) from a custom corpus and how to use them with an annotator.
* **phraseannotator-asl**: pipelines demonstrating the usage of the classes `FrequencyCounter` and `PhraseAnnotator` to detect lexical phrases in a frequency-based manner.
## Contact
In case you have any questions or problems with these examples, we are happy to help you -- this is a tutorial project, so we are glad to improve things and make life easier for both new and experienced [DKPro Core](http://dkpro.github.io/) users.
The easiest ways to get in touch are the [DKPro Core mailing lists](https://dkpro.github.io/dkpro-core/pages/mailinglists/) or to [submit an issue](https://github.com/dkpro/dkpro-core-examples/issues).
| 0 |
LorenzoBettini/packtpub-xtext-book-examples | Examples for the book Implementing Domain-Specific Languages with Xtext and Xtend" 978-1782160304" | null | Implementing Domain-Specific Languages with Xtext and Xtend
============================
This repository contains the sources of the Examples for the book
*"Implementing Domain-Specific Languages with Xtext and Xtend"*
ISBN: 978-1782160304
http://www.packtpub.com/implementing-domain-specific-languages-with-xtext-and-xtend/book
ERRATA and changes in new versions of Xtext
====
The book was written using Xtext 2.4.2 and some changes were introduced in new versions of Xtext that require some modifications in the sources (and make some parts written in the book not consistent).
In the following we detail the changes required to adapt the examples to the new versions of Xtext.
## General Book ERRATA
Some initial ERRATA, related to errors and typos in the text of the book can be found on the publisher web site: select "Support", search for the book, e.g., type "Xtext" and select the book title. It should be possible to access it directly following [this link](https://www.packtpub.com/books/content/support/12928).
As reported in Issue https://github.com/LorenzoBettini/packtpub-xtext-book-examples/issues/1 in the ExpressionsTypeProvider and ExpressionsInterpreter xtend files, you get compilation errors "Cannot convert..." if you have only one dispatch method for an Expression class; as soon as you add another dispatch method, say, e.g., one for Variable, the error will go away, since a method accepting AbstractElement will be generated.
## Xtext 2.4.3
Xtext 2.4.3 generates the .ecore (and the corresponding .genmodel) file in the directory model/generated underneath the project directory, and not in the src-gen folder.
This is due to a new generation fragment in the mwe2 file: instead of
fragment = ecore.EcoreGeneratorFragment auto-inject {
(which is now deprecated) the following fragment is now used by default in new Xtext projects
fragment = ecore.EMFGeneratorFragment auto-inject {
and this fragment generates the .ecore and the .genmodel files in the folder "model/generated"
## Xtext 2.5
To specify a type literal you can simply write its name: there's no need to use the keyword **typeof** anymore.
For example, instead of
typeof(String)
you can simply write
String
## Xtext 2.6
### Xbase
The Xbase rule **XExpressionInsideBlock** has changed into **XExpressionOrVarDeclaration**.
Thus, the Xbase Expressions example's grammar now reads:
ExpressionsModel returns XBlockExpression:
{ExpressionsModel}
(expressions+=XExpressionOrVarDeclaration)*;
## Xtext 2.7
### Testing with CompilationTestHelper
The class **org.eclipse.xtext.xbase.compiler.CompilationTestHelper** (contained in the bundle _org.eclipse.xtext.xbase.junit_) requires additional bindings which are created by default when your grammar uses Xbase. However, this class could be used also for testing code generation also in languages that do not use Xbase (this is the case in the book, Chapter 7, for the examples Entities and Expressions); see also [this discussion in the Xtext forum](https://www.eclipse.org/forums/index.php/t/807828/).
The symptom is this exception when running the Junit tests that use CompilationTestHelper
com.google.inject.ConfigurationException: Guice configuration errors:
1) No implementation for org.eclipse.xtend.lib.macro.file.MutableFileSystemSupport was bound.
while locating org.eclipse.xtend.lib.macro.file.MutableFileSystemSupport
for field at org.eclipse.xtext.generator.FileSystemSupportBasedFileSystemAccess.fileSystemSupport(Unknown Source)
while locating com.google.inject.Provider<org.eclipse.xtext.xbase.compiler.RegisteringFileSystemAccess>
for field at org.eclipse.xtext.xbase.compiler.CompilationTestHelper$Result.fileSystemAccessProvider(Unknown Source)
while locating com.google.inject.Provider<org.eclipse.xtext.xbase.compiler.CompilationTestHelper$Result>
for field at org.eclipse.xtext.xbase.compiler.CompilationTestHelper.resultProvider(Unknown Source)
while locating org.eclipse.xtext.xbase.compiler.CompilationTestHelper
for field at org.example.expressions.tests.ExpressionsGeneratorTest._compilationTestHelper(Unknown Source)
while locating org.example.expressions.tests.ExpressionsGeneratorTest
To solve this problem the missing bindings in languages that do not use Xbase must be added explicitly; there are two ways of solving this:
**1. Add the bindings in the runtime module of the language**
For example, for the Entities example, you must add the following bindings in the _EntitiesRuntimeModule_ (first, make sure you have the following dependencies in the MANIFEST.MF: _org.eclipse.xtend.lib.macro_ and _org.eclipse.xtext.xbase_):
```javascript
public class EntitiesRuntimeModule extends org.example.entities.AbstractEntitiesRuntimeModule {
//... existing bindings
// this is required only by the CompilationTestHelper since Xtext 2.7
public Class<? extends org.eclipse.xtend.lib.macro.file.MutableFileSystemSupport> bindMutableFileSystemSupport() {
return org.eclipse.xtext.xbase.file.JavaIOFileSystemSupport.class;
}
// this is required only by the CompilationTestHelper since Xtext 2.7
public Class<? extends com.google.inject.Provider<org.eclipse.xtext.xbase.file.WorkspaceConfig>> provideWorkspaceConfig() {
return org.eclipse.xtext.xbase.file.RuntimeWorkspaceConfigProvider.class;
}
}
```
**2. Add the bindings in a custom InjectorProvider in the tests project**
If you do not want to add these bindings in the main DSL runtime module (after all, you need them only for testing), you can create a custom injector provider in the tests project (inheriting from the generated one in src-gen folder) to be used only for the test(s) that use CompilationTestHelper. This custom injector provider must define a custom Guice module, inheriting from the DSL main module, and provide the additional bindings.
For example, for the Expressions example, you must add the following class in the test project (first, make sure you have the following dependencies in the MANIFEST.MF: _org.eclipse.xtend.lib.macro_ and _org.eclipse.xtext.xbase_):
```javascript
package org.example.expressions.tests;
import org.example.expressions.ExpressionsInjectorProvider;
import org.example.expressions.ExpressionsRuntimeModule;
import org.example.expressions.ExpressionsStandaloneSetup;
import com.google.inject.Guice;
import com.google.inject.Injector;
public class ExpressionsInjectorProviderCustom extends ExpressionsInjectorProvider {
@Override
protected Injector internalCreateInjector() {
return new ExpressionsStandaloneSetup() {
@Override
public Injector createInjector() {
return Guice.createInjector(new ExpressionsRuntimeModule() {
// this is required only by the CompilationTestHelper since
// Xtext 2.7
@SuppressWarnings("unused")
public Class<? extends org.eclipse.xtend.lib.macro.file.MutableFileSystemSupport> bindMutableFileSystemSupport() {
return org.eclipse.xtext.xbase.file.JavaIOFileSystemSupport.class;
}
// this is required only by the CompilationTestHelper since
// Xtext 2.7
@SuppressWarnings("unused")
public Class<? extends com.google.inject.Provider<org.eclipse.xtext.xbase.file.WorkspaceConfig>> provideWorkspaceConfig() {
return org.eclipse.xtext.xbase.file.RuntimeWorkspaceConfigProvider.class;
}
});
}
}.createInjectorAndDoEMFRegistration();
}
}
```
And then you must use this injector provider in the @InjectWith annotation of the test that uses CompilationTestHelper; in this example:
```javascript
@RunWith(typeof(XtextRunner))
@InjectWith(typeof(ExpressionsInjectorProviderCustom))
class ExpressionsGeneratorTest {
@Inject extension CompilationTestHelper
...
```
### Inject Xtext TemporaryFolder when using CompilationTestHelper
This is not a strict requirement, but Xtext 2.7 introduced an improved version of _TemporaryFolder_ (see org.junit.rules.TemporaryFolder), it "allows creation of files and folders that are guaranteed to be deleted when the test method finishes (whether it passes or fails)".
If you want to use this improved version, you need to inject it with the @Rule annotation, e.g.,
```javascript
import org.eclipse.xtext.junit4.TemporaryFolder
@RunWith(typeof(XtextRunner))
@InjectWith(typeof(EntitiesInjectorProvider))
class EntitiesGeneratorTest {
@Rule
@Inject public TemporaryFolder temporaryFolder
@Inject extension CompilationTestHelper
...
```
### Model inferrer in Xbase
Some methods in the JvmModelInferrer have been deprecated and should be updated in the examples as follows:
Instead of the following acceptor invocation
acceptor.accept(entity.toClass("entities."+entity.name)).initializeLater [
You should now pass directly as the last argument a lambda expression
acceptor.accept(entity.toClass("entities."+entity.name)) [
This method in the JvmTypesBuilder has been deprecated
```javascript
@Deprecated
public JvmTypeReference newTypeRef(EObject ctx, Class<?> clazz, JvmTypeReference... typeArgs) {
return references.getTypeForName(clazz, ctx, typeArgs);
}
```
In the inferrer you should call directly
```javascript
public JvmTypeReference typeRef(Class<?> clazz, JvmTypeReference... typeArgs) {
```
(So the EObject context is not required anymore).
For example, instead of
entity.toMethod("toString", entity.newTypeRef(typeof(String)))
You should write (recall that typeof is not required anymore to specify a type literal):
entity.toMethod("toString", typeRef(String))
### Xtext Buckminster Wizard
This wizard provided by Xtext was not updated and it generates the projects-platform.rmap incorrectly (see also [this forum post](https://www.eclipse.org/forums/index.php/t/811323/)); the quickiest way to fix it is to change the property _eclipse.target.platform_ from _juno_ (or _kepler_) to _luna_ so that the new version of EMF, required by Xtext 2.7, will be found in the Luna update site.
Moreover, recently, another architecture fragment has been introduced, "pcc64le", which is only available from the "Luna Updates" site, not from the main "Luna Releases"; you should then update the target plaform RMAP in order to use also the eclipse/updates/4.4 update site
(see the updated [projects-platform.rmap](https://github.com/LorenzoBettini/packtpub-xtext-book-examples/blob/master/org.example.build.hello.buckminster/projects-platform.rmap "projects-platform.rmap") file in the org.example.build.hello.buckminster example).
The sympthom of this problem is this error during target platform resolution:
```
ERROR [0007] : No suitable provider for component
org.eclipse.core.filesystem.linux.ppc64le:osgi.bundle/[1.4.0.v20140808-1353,1.4.0.v20140808-1353]
(&(target.arch=ppc64le)(target.os=linux))
was found in resourceMap ... projects-platform.rmap
```
## Xtext 2.8
All Xtext plug-ins now require JavaSE-1.6 as execution environment. If you start from scratch new Xtext projects, you don't have to worry about that. However, if you had previously created Xtext projects, you need to adjust them all so that at least JavaSE-1.6 is specified as the execution environment.
You can do that with a Search-Replace in the workspace:
- in the files org.eclipse.jdt.core.prefs you need to replace 1.5 with 1.6
- in MANIFEST.MF and .classpath files you need to replace J2SE-1.5 with JavaSE-1.6
Running the mwe2 workflows requires in the classpath. Again, if you start from scratch new Xtext projects, you don't have to worry about that. Otherwise, you will experience such errors when running the mwe2 workflow
```
Could not load class: org.eclipse.core.runtime.OperationCanceledException
Add org.eclipse.equinox.common to the class path.
```
To solve this, just add org.eclipse.equinox.common as dependency in your DSL main project.
Just like with every new version of Xtext, please run mwe2 to re-generate all the artifacts, and make sure to merge the plugin.xml with the plugin.xml_gen.
### Xtext 2.8 new formatter API
Xtext 2.8 introduced a new formatter API (currently provisional), more details can be found here: https://www.eclipse.org/Xtext/releasenotes.html#/releasenotes/2015/03/11/version-2-8-0.
To enable the new formatter API, the mwe2 file should be changed:
fragment = formatting2.Formatter2Fragment {}
Please note that the new formatter API is completely different from the previous one, described in the book.
| 0 |
NationalSecurityAgency/skills-client-examples | SkillTree skills-client-examples | null | # SkillTree Integration Examples
SkillTree is an innovative approach to implementing application training.
To learn about the SkillTree platform please visit our [Official Documentation](https://code.nsa.gov/skills-docs/).
These pages provide in-depth guidance on the installation, usage and contribution.
# Workflows Status
[](https://github.com/NationalSecurityAgency/skills-client-examples/actions?query=workflow%3A%22Continuous+Integration%22)
| 0 |
rubel007cse/MasteringJava | Best of Java Examples for Learning | null | # MasteringJava
Best of Java Examples for Learning.
[Go to [/src ](https://github.com/rubel007cse/MasteringJava/tree/master/src "Click to go to '/src' ")folder from above for exploring details examples with comments to each code line.]
## Example of Following topics
1. HelloWorld : My first Java program
2. Learning Basic Java Syntax
3. Java DataTypes examples
4. Java Variables
5. Knowing Java Operators
6. Java Number and Java String learning
7. Practicing Java if-else Loops
8. Learning Java Switch Statement
9. Java Array Practicing Examples
10. Working with Java Methods
11. Understanding the Java Class and Objects
12. Testing Java Exception
13. Java Exception throwing examples
14. Java Inheritance
15. Java Overriding , OverLoading
16. Java Polymorphism
17. Abstraction in Java
18. Learning Java Interfaces
19. Encapsulation in Java & Getter Setter
20. Java Thread
21. Java Constructor
22. IS A, HAS A Relation
23. This Keyword
24. Java Operators
25. Java Access Modifier
26. Super KeyWord
27. Java Enum
28. Java Singleton
29. Generics
30. Collections
31. ArrayList
32. Iterating
33. LinkedList
34. Map
35. File i/o

# [Order Book from Rokomari ](https://goo.gl/zjo5yY)
## About Me
Software Specialist | Java/Android Dev | Author | Lecturer at Southeast University (Part time)
Find me on Socials :
[ [Linkedin ](https://www.linkedin.com/in/rubel007cse "Click to go to 'Linkedin' ") ]
[ [Facebook ](https://www.facebook.com/rubel007cse "Click to go to 'Facebook' ") ]
[ [Web ](http://mrubel.com "Click to go to 'MRubel.com' ") ]
| 0 |
aspose-email/Aspose.Email-for-Java | Aspose.Email for Java Examples | null |  
# Java Email API
[Aspose.Email for Java](https://products.aspose.com/email/java) is a complete set of Email Processing APIs to create, read and manipulate emails from within your applications. It makes it easier to work with many Outlook email message formats such as MSG, EML, EMLX and MHT files without the need of installing Microsoft Outlook. It also enables you to manage message storage files - Personal Storage Files (PST), Offline Storage Files (OST) along with message sending and receiving capabilities. You can also read and extract Outlook PST file that can be saved to disk in MSG format.
Directory | Description
--------- | -----------
[Examples](https://github.com/aspose-email/Aspose.Email-for-Java/tree/master/Examples) | A collection of Java examples that help you learn the product features.
[Plugins](https://github.com/aspose-email/Aspose.Email-for-Java/tree/master/Plugins) | Plugins that will demonstrate one or more features of Aspose.Email for Java.
<p align="center">
<a title="Download complete Aspose.Email for Java source code" href="https://github.com/asposeemail/Aspose_Email_Java/archive/master.zip">
<img src="https://raw.githubusercontent.com/AsposeExamples/java-examples-dashboard/master/images/downloadZip-Button-Large.png" />
</a>
</p>
## Email API Features
- Create messages from scratch or load existing email files for editing.
- Create and Set contents of MIME messages.
- Extract contents from emails.
- Load and save [appointment in ICS format](https://docs.aspose.com/email/java/working-with-appointments/).
- Ability to connect to SMTP, POP3, IMAP, Exchange server.
- Works with Thunderbird, Zimbra and IBM Notes.
## Read & Write Email Formats
**Microsoft Outlook:** MSG, PST, OST, OFT\
**Email:** EML, EMLX, MBOX\
**Others:** ICS, VCF, HTML, MHTML
## Read Email Formats
**Mac Outlook:** OLM
## Supported Environments
- **Microsoft Windows:** Windows Desktop & Server (x86, x64)
- **macOS:** Mac OS X
- **Linux:** Ubuntu, OpenSUSE, CentOS, and others
- **Java Versions:** `J2SE 7.0 (1.7)`, `J2SE 8.0 (1.8)`
## Get Started with Aspose.Email for Java
Aspose hosts all Java APIs at the [Aspose Repository](https://repository.aspose.com/webapp/#/artifacts/browse/tree/General/repo/com/aspose/aspose-email). You can easily use Aspose.BarCode for Java API directly in your Maven projects with simple configurations. For the detailed instructions please visit [Installing Aspose.Email for Java from Maven Repository](https://docs.aspose.com/email/java/installation/) documentation page.
## Perform IMAP Message Backup Operation using Java
```java
ImapClient imapClient = new ImapClient();
imapClient.setHost("<HOST>");
imapClient.setPort(993);
imapClient.setUsername("<USERNAME>");
imapClient.setPassword("<PASSWORD>");
imapClient.setSupportedEncryption(EncryptionProtocols.Tls);
imapClient.setSecurityOptions(SecurityOptions.SSLImplicit);
ImapMailboxInfo mailboxInfo = imapClient.getMailboxInfo();
ImapFolderInfo info = imapClient.getFolderInfo(mailboxInfo.getInbox().getName());
ImapFolderInfoCollection infos = new ImapFolderInfoCollection();
infos.add(info);
imapClient.backup(infos, dataDir + "\\ImapBackup.pst", BackupOptions.None);
```
[Home](https://www.aspose.com/) | [Product Page](https://products.aspose.com/email/java) | [Docs](https://docs.aspose.com/email/java/) | [Demos](https://products.aspose.app/email/family) | [API Reference](https://apireference.aspose.com/email/java) | [Examples](https://github.com/aspose-email/Aspose.Email-for-Java) | [Blog](https://blog.aspose.com/category/email/) | [Search](https://search.aspose.com/) | [Free Support](https://forum.aspose.com/c/email) | [Temporary License](https://purchase.aspose.com/temporary-license)
| 0 |
stuartaroth/programmersguidetothegalaxy | Syntax Examples across Languages | null | ##### www.programmersguidetothegalaxy.com is a project with a simple goal:
##### Allow engineers to quickly learn how to do "x" in "y" language.
While programming concepts are universal, syntax is not. This project aims to give users a tool that will allow them to get working quickly on technology stacks that are new to them.
This project can help add to your tool belt, allowing you to easily use the best libraries and frameworks for the task at hand, regardless of your current experience and knowledge.
> If all you have is a hammer, everything looks like a nail
##### Contributing
Pull requests are very welcome! All new code should follow the established style.
Currently the focus should be adding new languages, across all the currently included folders/concepts.
New folders/concepts should try to include examples across all supported languages.
Before pull requesting, you should run the command ./run_all_examples.sh
When doing this all your code should compile and run.
Issues can be used to report bugs / request languages and folders.
Here is the current site repo:
https://github.com/stuartaroth/programmersguidetothegalaxy-site-jquery
| 0 |
rosshambrick/AsyncExamples | null | null | # AsyncExamples
| 0 |
jonashackt/spring-boot-vuejs | Example project showing how to build a Spring Boot App providing a GUI with Vue.js | axios backend docker frontend heroku jest nightwatch rest-api rest-backend spring-boot vue vue-cli vue-cli-3 vue-cli-plugin vue-frontend vuejs vuejs2 webpack | # spring-boot-vuejs
[](https://github.com/jonashackt/spring-boot-vuejs/actions)
[](https://codecov.io/gh/jonashackt/spring-boot-vuejs)
[](https://github.com/jonashackt/spring-boot-vuejs/blob/master/LICENSE)
[](https://renovatebot.com)
[](https://github.com/spring-projects/spring-boot)
[](https://github.com/spring-projects/spring-boot)
[](https://vuejs.org/)
[](https://www.typescriptlang.org/)
[](https://getbootstrap.com/)
[](https://nodejs.org/en/)
[](https://webpack.js.org/)
[](https://github.com/axios/axios)
[](https://jestjs.io/)
[](http://nightwatchjs.org/)
[](https://spring-boot-vuejs.herokuapp.com/)
[](https://hub.docker.com/r/jonashackt/spring-boot-vuejs)
> **If you´re a JavaMagazin / blog.codecentric.de / Softwerker reader**, consider switching to [vue-cli-v2-webpack-v3](https://github.com/jonashackt/spring-boot-vuejs/tree/vue-cli-v2-webpack-v3)

A live deployment is available on Heroku: https://spring-boot-vuejs.herokuapp.com
This project is used as example in a variety of articles & as eBook:
[](https://jaxenter.de/ausgaben/java-magazin-8-18)
[](https://www.amazon.com/Vue-js-f%C3%BCr-alle-Wissenswertes-Einsteiger-ebook/dp/B07HQF9VX4/ref=sr_1_1?ie=UTF8&qid=1538484852&sr=8-1&keywords=Vue-js-f%C3%BCr-alle-Wissenswertes-Einsteiger-ebook)
[](https://info.codecentric.de/softwerker-vol-12)
[blog.codecentric.de/en/2018/04/spring-boot-vuejs](https://blog.codecentric.de/en/2018/04/spring-boot-vuejs) | [JavaMagazin 8.2018](https://jaxenter.de/ausgaben/java-magazin-8-18) | [entwickler.press shortcuts 229](https://www.amazon.com/Vue-js-f%C3%BCr-alle-Wissenswertes-Einsteiger-ebook/dp/B07HQF9VX4/ref=sr_1_1?ie=UTF8&qid=1538484852&sr=8-1&keywords=Vue-js-f%C3%BCr-alle-Wissenswertes-Einsteiger-ebook) | [softwerker Vol.12](https://info.codecentric.de/softwerker-vol-12)
## Upgrade procedure
Get newest node & npm:
```shell
brew upgrade node
npm install -g npm@latest
```
Update vue-cli
```shell
npm install -g @vue/cli
```
Update Vue components/plugins (see https://cli.vuejs.org/migrating-from-v3/#upgrade-all-plugins-at-once)
```shell
vue upgrade
```
## In Search of a new Web Frontend-Framework after 2 Years of absence...
Well, I’m not a Frontend developer. I’m more like playing around with Spring Boot, Web- & Microservices & Docker, automating things with Ansible and Docker, Scaling things with Spring Cloud, Docker Compose, and Traefik... And the only GUIs I’m building are the "new JS framework in town"-app every two years... :) So the last one was Angular 1 - and it felt, as it was a good choice! I loved the coding experience and after a day of training, I felt able to write awesome Frontends...
But now we’re 2 years later and I heard from afar, that there was a complete rewrite of Angular (2), a new kid in town from Facebook (React) and lots of ES201x stuff and dependency managers like bower and Co. So I’m now in the new 2-year-cycle of trying to cope up again - and so glad I found this article: https://medium.com/reverdev/why-we-moved-from-angular-2-to-vue-js-and-why-we-didnt-choose-react-ef807d9f4163
Key points are:
* Angular 2 isn’t the way to go if you know version 1 (complete re-write, only with Typescript, loss of many of 1’s advantages, Angular 4 is coming)
* React (facebookish problems (licence), need to choose btw. Redux & MObX, harder learning curve, slower coding speed)

And the [introduction phrase](https://vuejs.org/v2/guide/index.html) sounds really great:
> Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only and is very easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.
So I think, it could be a good idea to invest a day or so into Vue.js. Let’s have a look here!
## Setup Vue.js & Spring Boot
### Prerequisites
#### MacOSX
```
brew install node
npm install -g @vue/cli
```
#### Linux
```
sudo apt update
sudo apt install node
npm install -g @vue/cli
```
#### Windows
```
choco install npm
npm install -g @vue/cli
```
## Project setup
```
spring-boot-vuejs
├─┬ backend → backend module with Spring Boot code
│ ├── src
│ └── pom.xml
├─┬ frontend → frontend module with Vue.js code
│ ├── src
│ └── pom.xml
└── pom.xml → Maven parent pom managing both modules
```
## Backend
Go to https://start.spring.io/ and initialize a Spring Boot app with `Web` and `Actuator`. Place the zip’s contents in the backend folder.
Customize pom to copy content from Frontend for serving it later with the embedded Tomcat:
```xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy Vue.js frontend content</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources/public</outputDirectory>
<overwrite>true</overwrite>
<resources>
<resource>
<directory>${project.parent.basedir}/frontend/target/dist</directory>
<includes>
<include>static/</include>
<include>index.html</include>
<include>favicon.ico</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
## Frontend
Creating our `frontend` project is done by the slightly changed (we use `--no-git` here, because our parent project is already a git repository and otherwise vue CLI 3 would initialize an new one):
```
vue create frontend --no-git
```
see https://cli.vuejs.org/guide/
This will initialize a project skeleton for Vue.js in /frontend directory - it, therefore, asks some questions in the cli:

__Do not__ choose the default preset with `default (babel, eslint)`, because we need some more plugins for our project here (choose the Plugins with the __space bar__):

You can now also use the new `vue ui` command/feature to configure your project:

If you want to learn more about installing Vue.js, head over to the docs: https://vuejs.org/v2/guide/installation.html
### Use frontend-maven-plugin to handle NPM, Node, Bower, Grunt, Gulp, Webpack and so on :)
If you’re a backend dev like me, this Maven plugin here https://github.com/eirslett/frontend-maven-plugin is a great help for you - because, if you know Maven, that’s everything you need! Just add this plugin to the frontend’s `pom.xml`:
```xml
<build>
<plugins>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>${frontend-maven-plugin.version}</version>
<executions>
<!-- Install our node and npm version to run npm/node scripts-->
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v10.10.0</nodeVersion>
</configuration>
</execution>
<!-- Install all project dependencies -->
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
<!-- optional: default phase is "generate-resources" -->
<phase>generate-resources</phase>
<!-- Optional configuration which provides for running any npm command -->
<configuration>
<arguments>install</arguments>
</configuration>
</execution>
<!-- Build and minify static files -->
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
### Tell Webpack to output the dist/ contents to target/
Commonly, node projects will create a dist/ directory for builds which contains the minified source code of the web app - but we want it all in `/target`. Therefore we need to create the optional [vue.config.js](https://cli.vuejs.org/config/#vue-config-js) and configure the `outputDir` and `assetsDir` correctly:
```javascript
module.exports = {
...
// Change build paths to make them Maven compatible
// see https://cli.vuejs.org/config/
outputDir;: 'target/dist',
assetsDir;: 'static';
}
```
## First App run
Inside the root directory, do a:
```
mvn clean install
```
Run our complete Spring Boot App:
```
mvn --projects backend spring-boot:run
```
Now go to http://localhost:8098/ and have a look at your first Vue.js Spring Boot App.
## Faster feedback with webpack-dev-server
The webpack-dev-server, which will update and build every change through all the parts of the JavaScript build-chain, is pre-configured in Vue.js out-of-the-box! So the only thing needed to get fast feedback development-cycle is to cd into `frontend` and run:
```
npm run serve
```
That’s it!
## Browser developer tools extension
Install vue-devtools Browser extension https://github.com/vuejs/vue-devtools and get better feedback, e.g. in Chrome:

## IntelliJ integration
There's a blog post: https://blog.jetbrains.com/webstorm/2018/01/working-with-vue-js-in-webstorm/
Especially the `New... Vue Component` looks quite cool :)
## HTTP calls from Vue.js to (Spring Boot) REST backend
Prior to Vue 2.0, there was a build in solution (vue-resource). But from 2.0 on, 3rd party libraries are necessary. One of them is [Axios](https://github.com/mzabriskie/axios) - also see blog post https://alligator.io/vuejs/rest-api-axios/
```
npm install axios --save
```
Calling a REST service with Axios is simple. Go into the script area of your component, e.g. Hello.vue and add:
```js
import axios from 'axios'
data ();{
return {
response: [],
errors: []
}
},
callRestService ();{
axios.get(`api/hello`)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
```
In your template area you can now request a service call via calling `callRestService()` method and access `response` data:
```html
<button class=”Search__button” @click="callRestService()">CALL Spring Boot REST backend service</button>
<h3>{{ response }}</h3>
```
### The problem with SOP
Single-Origin Policy (SOP) could be a problem if we want to develop our app. Because the webpack-dev-server runs on http://localhost:8080 and our Spring Boot REST backend on http://localhost:8098.
We need to use Cross-Origin Resource Sharing Protocol (CORS) to handle that (read more background info about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
#### Enabling Axios CORS support
Create a central Axios configuration file called `http-commons.js`:
```js
import axios from 'axios'
export const AXIOS = axios.create({
baseURL: `http://localhost:8098`,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:8080'
}
})
```
Here we allow requests to the base URL of our Spring Boot App on port 8098 to be accessible from 8080.
Now we could use this configuration inside our Components, e.g. in `Hello.vue`:
```js
import {AXIOS} from './http-common'
export default {
name: 'hello',
data () {
return {
posts: [],
errors: []
}
},
methods: {
// Fetches posts when the component is created.
callRestService () {
AXIOS.get(`hello`)
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
```
#### Enabling Spring Boot CORS support
Additionally, we need to configure our Spring Boot backend to answer with the appropriate CORS HTTP Headers in its responses (there's a good tutorial here: https://spring.io/guides/gs/rest-service-cors/). Therefore we add the annotation `@CrossOrigin` to our BackendController:
```java
@CrossOrigin(origins = "http://localhost:8080")
@RequestMapping(path = "/hello")
public @ResponseBody String sayHello() {
LOG.info("GET called on /hello resource");
return HELLO_TEXT;
}
```
Now our Backend will respond CORS-enabled and will accept requests from 8080. But as this only enables CORS on one method, we have to repeatedly add this annotation to all of our REST endpoints, which isn’t a nice style. We should use a global solution to allow access with CORS enabled to all of our REST resources. This could be done in the `SpringBootVuejsApplication.class`:
```java
// Enable CORS globally
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/*").allowedOrigins("http://localhost:8080");
}
};
}
```
Now all calls to resources behind `api/` will return the correct CORS headers.
#### But STOP! Webpack & Vue have something much smarter for us to help us with SOP!
Thanks to my colleague [Daniel](https://www.codecentric.de/team/dre/) who pointed me to the nice proxying feature of Webpack dev-server, we don't need to configure all the complex CORS stuff anymore!
According to the [Vue CLI 3 docs](https://cli.vuejs.org/config) the only thing we need to [configure is a devserver-proxy](https://cli.vuejs.org/config/#devserver-proxy) for our webpack devserver requests. This could be done easily in the optional [vue.config.js](https://cli.vuejs.org/config/#vue-config-js) inside `devServer.proxy`:
```js
module.exports = {
// proxy all webpack dev-server requests starting with /api
// to our Spring Boot backend (localhost:8098) using http-proxy-middleware
// see https://cli.vuejs.org/config/#devserver-proxy
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8098',
ws: true,
changeOrigin: true
}
}
},
...
}
```
With this configuration in place, the webpack dev-server uses the [http-proxy-middleware](https://github.com/chimurai/http-proxy-middleware), which is a really handy component, to proxy all frontend-requests from http://localhost:8080 --> http://localhost:8098 - incl. Changing the Origin accordingly.
This is used in the webpack build process to configure the proxyMiddleware (you don't need to change something here!):
```js
// proxy api requests
Object.keys(proxyTable).forEach(function (context) {
var options = proxyTable[context];
if (typeof options === 'string') {
options = { target: options }
}
app.use(proxyMiddleware(options.filter || context, options))
})
```
## Using history mode for nicer URLs
If we use the default configuration of the generated Vue.js template, we see URLs with a `#` inside them - like this:
```
http://localhost:8098/#/bootstrap
or
http://localhost:8098/#/user
```
With the usage of __[HTML5 history mode](https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode)__, we can achieve much nicer URLs without the `#` in them. Only thing to do in the Vue.js frontend is to configure our router accordingly inside the [router.js](frontend/src/router.js):
```
...
Vue.use(Router);
const router = new Router({
mode: 'history', // uris without hashes #, see https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode
routes: [
{ path: '/', component: Hello },
{ path: '/callservice', component: Service },
...
```
That's nearly everything. BUT only nearly! If one clicks on a link inside our frontend, the user is correctly send to the wished component.
But if the user enters the URL directly into the Browser, we get a `Whitelabel Error Page` because our Spring Boot backend gives us a __HTTP 404__ - since this URL isn't present in the backend:

The solution is to redirect or better forward the user to the frontend (router) again. The [Vue.js docs don't provide an example configuration for Spring Boot](https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations), but luckily [there are other resources](https://www.baeldung.com/spring-redirect-and-forward). In essence we have to implement a forwarding controller in our [BackendController](backend/src/main/java/de/jonashackt/springbootvuejs/controller/BackendController.java):
```
// Forwards all routes to FrontEnd except: '/', '/index.html', '/api', '/api/**'
// Required because of 'mode: history' usage in frontend routing, see README for further details
@RequestMapping(value = "{_:^(?!index\\.html|api).$}")
public String redirectApi() {
LOG.info("URL entered directly into the Browser, so we need to redirect...");
return "forward:/";
}
```
This controller will forward every request other then `'/', '/index.html', '/api', '/api/**'` to our Vue.js frontend.
## Bootstrap & Vue.js
There’s a nice integration of Bootstrap in Vue.js: https://bootstrap-vue.js.org/
```
npm install bootstrap-vue
```
Now you can use all the pretty Bootstrap stuff with ease like:
```
<b-btn @click="callRestService()">CALL Spring Boot REST backend service</b-btn>
```
instead of
```
<button type="button" class=”btn” @click="callRestService()">CALL Spring Boot REST backend service</button>
```
The docs contain all the possible components: https://bootstrap-vue.js.org/docs/components/alert/
See some elements, when you go to http://localhost:8080/#/bootstrap/ - this should look like this:

A good discussion about various UI component frameworks: http://vuetips.com/bootstrap
## Heroku Deployment
As you may already read, the app is automatically deployed to Heroku on https://spring-boot-vuejs.herokuapp.com/.
The project makes use of the nice Heroku Pipelines feature, where we do get a full Continuous Delivery pipeline with nearly no effort:

And with the help of super cool `Automatic deploys`, we have our GitHub Actions build our app after every push to master - and with the checkbox set to `Wait for CI to pass before deploy` - the app gets also automatically deployed to Heroku - but only, if the GitHub Actions (and Codegov...) build succeeded:

You only have to connect your Heroku app to GitHub, activate Automatic deploys and set the named checkbox. That's everything!
#### Accessing Spring Boot REST backend on Heroku from Vue.js frontend
Frontend needs to know the Port of our Spring Boot backend API, which is [automatically set by Heroku every time, we (re-)start our App](https://stackoverflow.com/a/12023039/4964553).
> You can [try out your Heroku app locally](https://devcenter.heroku.com/articles/heroku-local)! Just create a .env-File with all your Environment variables and run `heroku local`!
To access the Heroku set port, we need to use relative paths inside our Vue.js application instead of hard-coded hosts and ports!
All we need to do is to configure Axios in such a way inside our [frontend/src/components/http-common.js](https://github.com/jonashackt/spring-boot-vuejs/blob/master/frontend/src/components/http-common.js):
```
export const AXIOS = axios.create({
baseURL: `/api`
})
```
#### Using Heroku's Postgres as Database for Spring Boot backend and Vue.js frontend
First, add [Heroku Postgres database](https://elements.heroku.com/addons/heroku-postgresql) for your Heroku app.
Then follow these instructions on Stackoverflow to configure all needed Environment variables in Heroku: https://stackoverflow.com/a/49978310/4964553
Mind the addition to the backend's [pom.xml](backend/pom.xml) described here: https://stackoverflow.com/a/49970142/4964553
Now you're able to use Spring Data's magic - all you need is an Interface like [UserRepository.java](backend/src/main/java/de/jonashackt/springbootvuejs/repository/UserRepository.java):
```java
package de.jonashackt.springbootvuejs.repository;
import de.jonashackt.springbootvuejs.domain.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByLastName(@Param("lastname") String lastname);
List<User> findByFirstName(@Param("firstname") String firstname);
}
```
Now write your Testcases accordingly like [UserRepositoryTest.java](backend/src/test/java/de/jonashackt/springbootvuejs/repository/UserRepositoryTest.java):
```java
package de.jonashackt.springbootvuejs.repository;
import de.jonashackt.springbootvuejs.domain.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository users;
private final User norbertSiegmund = new User("Norbert", "Siegmund");
private final User jonasHecht = new User("Jonas", "Hecht");
@Before
public void fillSomeDataIntoOurDb() {
// Add new Users to Database
entityManager.persist(norbertSiegmund);
entityManager.persist(jonasHecht);
}
@Test
public void testFindByLastName() throws Exception {
// Search for specific User in Database according to lastname
List<User> usersWithLastNameSiegmund = users.findByLastName("Siegmund");
assertThat(usersWithLastNameSiegmund, contains(norbertSiegmund));
}
@Test
public void testFindByFirstName() throws Exception {
// Search for specific User in Database according to firstname
List<User> usersWithFirstNameJonas = users.findByFirstName("Jonas");
assertThat(usersWithFirstNameJonas, contains(jonasHecht));
}
}
```
Then include this functionality in your REST-API - see [BackendController.java](backend/src/main/java/de/jonashackt/springbootvuejs/controller/BackendController.java):
```java
@RequestMapping(path = "/user", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody long addNewUser (@RequestParam String firstName, @RequestParam String lastName) {
User user = new User(firstName, lastName);
userRepository.save(user);
LOG.info(user.toString() + " successfully saved into DB");
return user.getId();
}
```
and use it from the Vue.js frontend, see [User.vue](frontend/src/components/User.vue):
```html
<template>
<div class="user">
<h1>Create User</h1>
<h3>Just some database interaction...</h3>
<input type="text" v-model="user.firstName" placeholder="first name">
<input type="text" v-model="user.lastName" placeholder="last name">
<button @click="createUser()">Create User</button>
<div v-if="showResponse"><h6>User created with Id: {{ response }}</h6></div>
<button v-if="showResponse" @click="retrieveUser()">Retrieve user {{user.id}} data from database</button>
<h4 v-if="showRetrievedUser">Retrieved User {{retrievedUser.firstName}} {{retrievedUser.lastName}}</h4>
</div>
</template>
<script>
// import axios from 'axios'
import {AXIOS} from './http-common'
export default {
name: 'user',
data () {
return {
response: [],
errors: [],
user: {
lastName: '',
firstName: '',
id: 0
},
showResponse: false,
retrievedUser: {},
showRetrievedUser: false
}
},
methods: {
// Fetches posts when the component is created.
createUser () {
var params = new URLSearchParams();
params.append('firstName', this.user.firstName);
params.append('lastName', this.user.lastName);
AXIOS.post(`/user`, params)
.then(response => {
// JSON responses are automatically parsed.
this.response = response.data;
this.user.id = response.data;
console.log(response.data);
this.showResponse = true
})
.catch(e => {
this.errors.push(e)
})
},
retrieveUser () {
AXIOS.get(`/user/` + this.user.id)
.then(response => {
// JSON responses are automatically parsed.
this.retrievedUser = response.data;
console.log(response.data);
this.showRetrievedUser = true
})
.catch(e => {
this.errors.push(e)
})
}
}
}
</script>
```
## Testing
### Install vue-test-utils
https://github.com/vuejs/vue-test-utils
`npm install --save-dev @vue/test-utils`
### Jest
Jest is a new shooting star in the sky of JavaScript testing frameworks: https://facebook.github.io/jest/
Intro-Blogpost: https://blog.codecentric.de/2017/06/javascript-unit-tests-sind-schwer-aufzusetzen-keep-calm-use-jest/
Examples: https://github.com/vuejs/vue-test-utils-jest-example
Vue.js Jest Docs: https://vue-test-utils.vuejs.org/guides/#testing-single-file-components-with-jest
A Jest Unittest looks like [Hello.spec.js](frontend/test/components/Hello.spec.js):
```js
import { shallowMount } from '@vue/test-utils';
import Hello from '@/components/Hello'
describe('Hello.vue', () => {
it('should render correct hello message', () => {
// Given
const hellowrapped = shallowMount(Hello, {
propsData: { hellomsg: 'Welcome to your Jest powered Vue.js App' },
stubs: ['router-link', 'router-view']
});
// When
const contentH1 = hellowrapped.find('h1');
// Then
expect(contentH1.text()).toEqual('Welcome to your Jest powered Vue.js App');
})
})
```
To pass Component props while using Vue.js Router, see https://stackoverflow.com/a/37940045/4964553.
How to test components with `router-view` or `router-link` https://vue-test-utils.vuejs.org/guides/using-with-vue-router.html#testing-components-that-use-router-link-or-router-view.
The test files itself could be named `xyz.spec.js` or `xyz.test.js` - and could reside nearly everywhere in the project.
##### Jest Configuration
The Jest run-configuration is done inside the [package.json](frontend/package.json):
```js
"scripts";: {
...
"test:unit";: "vue-cli-service test:unit --coverage",;
....
},
```
Jest can be configured via `jest.config.js` in your project root, or the `jest` field in [package.json](frontend/package.json). In our case we especially need to configure `coverageDirectory`:
```json
],
"jest": {
...
"coverageDirectory": "<rootDir>/tests/unit/coverage",
"collectCoverageFrom": [
"src/**/*.{js,vue}",
"!src/main.js",
"!src/router/index.js",
"!**/node_modules/**"
]
}
}
```
Jest needs to know the right output directory `/tests/unit/coverage` to show a correct output when `npm run test:unit` is run (or the corresponding Maven build). If you run the Jest Unit tests now with:
`npm run test:unit`
- you´ll recognize the table of test covered files:

##### Integration in Maven build (via frontend-maven-plugin)
Inside the [pom.xml](pom.xml) we always automatically run the Jest Unittests with the following configuration:
```xml
<!-- Run Unit tests -->
<execution>
<id>npm run test:unit</id>
<goals>
<goal>npm</goal>
</goals>
<!-- optional: default phase is "generate-resources" -->
<phase>test</phase>
<!-- Optional configuration which provides for running any npm command -->
<configuration>
<arguments>run test:unit</arguments>
</configuration>
</execution>
```
This will integrate the Jest Unittests right after the npm run build command, just you are used to in Java-style projects:

And don't mind the depiction with `ERROR` - this is just a known bug: https://github.com/eirslett/frontend-maven-plugin/issues/584
##### Run Jest tests inside IntelliJ
First, we need to install the NodeJS IntelliJ plugin (https://www.jetbrains.com/help/idea/developing-node-js-applications.html), which isn't bundled with IntelliJ by default:

IntelliJ Jest integration docs: https://www.jetbrains.com/help/idea/running-unit-tests-on-jest.html
The automatic search inside the [package.json](frontend/package.json) for the Jest configuration file [jest.conf.js](frontend/test/unit/jest.conf.js) doesn't seem to work right now, so we have to manually configure the `scripts` part of:
```
"unit": "jest --config test/unit/jest.conf.js --coverage",
```
inside the Run Configuration under `Jest` and `All Tests`:

Now, when running `All Tests`, this should look like you're already used to Unittest IntelliJ-Integration:

## End-2-End (E2E) tests with Nightwatch
Great tooling: http://nightwatchjs.org/ - Nightwatch controls WebDriver / Selenium standalone Server in own child process and abstracts from those, providing a handy DSL for Acceptance tests:
Docs: http://nightwatchjs.org/gettingstarted/#browser-drivers-setup

Nightwatch is configured through the [nightwatch.conf.js](/frontend/test/e2e/nightwatch.conf.js). Watch out for breaking changes in 1.x: https://github.com/nightwatchjs/nightwatch/wiki/Migrating-to-Nightwatch-1.0
More options could be found in the docs: http://nightwatchjs.org/gettingstarted/#settings-file
#### Write Nightwatch tests
An example Nightwatch test is provided in [HelloAcceptance.test.js](/frontend/test/e2e/specs/HelloAcceptance.test.js):
```js
module.exports = {
'default e2e tests': browser => {
browser
.url(process.env.VUE_DEV_SERVER_URL)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to your Vue.js powered Spring Boot App')
.assert.elementCount('img', 1)
.end()
}
}
```
##### Run E2E Tests
`npm run test:e2e`
## Run all tests
`npm test`
## NPM Security
npm Security - npm@6
https://medium.com/npm-inc/announcing-npm-6-5d0b1799a905
`npm audit`
https://blog.npmjs.org/post/173719309445/npm-audit-identify-and-fix-insecure
Run `npm audit fix` to update the vulnerable packages. Only in situations, where nothing else helps, try `npm audit fix --force` (this will also install braking changes)
https://nodejs.org/en/blog/vulnerability/june-2018-security-releases/
---> __Update NPM regularly__
https://docs.npmjs.com/troubleshooting/try-the-latest-stable-version-of-npm
`npm install -g npm@latest`
---> __Update Packages regularly__
https://docs.npmjs.com/getting-started/updating-local-packages
`npm outdated`
`npm update`
## Shift from templates to plugin-based architecture in Vue Cli 3
In the long run, templates like the main [webpack](https://github.com/vuejs-templates/webpack) are deprecated in the Vue.js universe:
https://vuejsdevelopers.com/2018/03/26/vue-cli-3/
Plugins bring the following benefits compared to templates:
* No lock in, as plugins can be added at any point in the development lifecycle
* Zero config plugins allow you to spend time developing rather than configuring
* Easy to upgrade, as configuration can be customized without “ejecting”
* Allows developers to make their own plugins and presets
Starting point: https://cli.vuejs.org/
#### OMG! My package.json is so small - Vue CLI 3 Plugins
From https://cli.vuejs.org/guide/plugins-and-presets.html:
> Vue CLI uses a plugin-based architecture. If you inspect a newly created project's package.json, you will find dependencies that start with `@vue/cli-plugin-`. Plugins can modify the internal webpack configuration and inject commands to `vue-cli-service`. Most of the features listed during the project creation process are implemented as plugins.
With plugings, extensions to an existing project could also be made via: `vue add pluginName`. E.g. if you want to add Nightwatch E2E tests to your project, just run `vue add @vue/e2e-nightwatch`. All scoped packages are available here: https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue
These new Vue CLI 3 plugin architecture cleans our big `package.json` to a really neat compact thing. This was the old big dependency block:
````json
"devDependencies": {
"@vue/test-utils": "^1.0.0-beta.25",
"autoprefixer": "^7.1.2",
"babel-core": "^6.26.3",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-jest": "^21.0.2",
"babel-loader": "^7.1.5",
"babel-plugin-dynamic-import-node": "^1.2.0",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"chalk": "^2.4.1",
"chromedriver": "^2.41.0",
"copy-webpack-plugin": "^4.5.2",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.4",
"friendly-errors-webpack-plugin": "^1.6.1",
"html-webpack-plugin": "^2.30.1",
"jest": "^22.0.4",
"jest-serializer-vue": "^0.3.0",
"nightwatch": "^1.0.11",
"node-notifier": "^5.1.2",
"optimize-css-assets-webpack-plugin": "^3.2.0",
"ora": "^1.2.0",
"portfinder": "^1.0.17",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.1.6",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"selenium-server": "^3.14.0",
"semver": "^5.5.1",
"shelljs": "^0.7.6",
"uglifyjs-webpack-plugin": "^1.3.0",
"url-loader": "^1.1.1",
"vue-jest": "^1.0.2",
"vue-loader": "^13.7.3",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.5.17",
"webpack": "^3.6.0",
"webpack-bundle-analyzer": "^2.13.1",
"webpack-dev-server": "^2.11.3",
"webpack-merge": "^4.1.4"
},
````
As you can see, we´re not only maintaining our high-level libraries of choice like nightwatch, jest and so on. We´re also maintaining libraries that they use itself. Now this is over with Vue CLI 3. Let´s have a look at the super clean dependency block now:
```json
"devDependencies": {
"@vue/cli-plugin-babel": "^3.0.3",
"@vue/cli-plugin-e2e-nightwatch": "^3.0.3",
"@vue/cli-plugin-unit-jest": "^3.0.3",
"@vue/cli-service": "^3.0.3",
"@vue/test-utils": "^1.0.0-beta.20",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^23.0.1",
"node-sass": "^4.9.0",
"sass-loader": "^7.0.1",
"vue-template-compiler": "^2.5.17"
},
```
As you dig into the directories like `node_modules/@vue/cli-plugin-e2e-nightwatch`, you´ll find where the used libraries of nightwatch are configured - in the respective `package.json` there:
```json
"dependencies": {
"@vue/cli-shared-utils": "^3.0.2",
"chromedriver": "^2.40.0",
"deepmerge": "^2.1.1",
"execa": "^0.10.0",
"nightwatch": "^0.9.21",
"selenium-server": "^3.13.0"
},
```
This is really cool, I have to admit!
#### The vue.config.js file
Vue CLI 3 removes the need for explicit configuration files - and thus you wont find any `build` or `config` directories in your projects root any more. This now implements a "convention over configuration" approach, which makes it much easier to kick-start a Vue.js project, as it provides widly used defaults to webpack etc. It also eases the upgradeability of Vue.js projects - or even makes it possible.
__But__: How do we configure webpack etc. for CORS handling, the build directories and so on? This could be done with the optional [vue.config.js](https://cli.vuejs.org/config/#vue-config-js):
```javascript
module.exports = {
// proxy all webpack dev-server requests starting with /api
// to our Spring Boot backend (localhost:8098) using http-proxy-middleware
// see https://cli.vuejs.org/config/#devserver-proxy
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8098',
ws: true,
changeOrigin: true
}
}
},
// Change build paths to make them Maven compatible
// see https://cli.vuejs.org/config/
outputDir: 'target/dist'
}
```
#### Updating Vue in an existing project
Update your local `@vue/cli` to the latest version:
```
npm install -g @vue/cli
```
Then update Vue.js and all your other JS dependencies with:
```
cd frontend
npm update
```
## Upgrade to Vue.js 3.x/4.x next
Let's move from 2.6.x -> 3.x/4.x next here.
> Be aware that [the latest version of vue currently is `2.6.x` and `3.x` is considered `next`](https://www.npmjs.com/package/vue)!
There are some resources:
https://v3.vuejs.org/guide/migration/introduction.html#quickstart
https://johnpapa.net/vue2-to-vue3/
And if we are using 3.x, we can even migrate to 4.x: https://cli.vuejs.org/migrating-from-v3/
#### Upgrade from 2.x to 3.x
There's a migration tooling, simply use:
```shell
vue add vue-next
```
This took around 3 minutes or more on my MacBook and changed some files:

The [package.json](frontend/package.json) got some new or upgraded deps:

[As John stated in his post](https://johnpapa.net/vue2-to-vue3/) it's strange to find `beta` versions with `vue`, `vue-router` and `vuex`.
So in order to see what a fresh skeleton would produce, let's also create one in another dir ([I assume you have `npm install -g @vue/cli` installed](https://v3.vuejs.org/guide/migration/introduction.html#quickstart):
```shell
mkdir vue3test && cd vue3test
vue create hello-vue3
```
I aligned my project to match the latest skeleton generation much better: So router, store and api got their own directories. The views are now in the correct folder `views` - and I extracted one component to use from the newly introduced `Home.vue` view: the `HelloSpringWorld.vue` component.
I also went over the [package.json](frontend/package.json) and upgraded to the latest release versions instead of alphas (except `@vue/test-utils` which only has a `rc` atm).
All imports were refactored too. Coming from this style:
```javascript
import Vue from 'vue'
import Router from 'vue-router'
```
everything now reads:
```javascript
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router'
```
Also check your `router.js` or [router/index.js](frontend/src/router/index.js)! Using a path redirect like this leads to a non working routing configuration:
```javascript
// otherwise redirect to home
{ path: '*', redirect: '/' }
```
The error in the Browser console states:
```shell
Uncaught Error: Catch all routes ("*") must now be defined using a param with a custom regexp.
See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.
```
I changed it to the new param with regex syntax like this:
```javascript
// otherwise redirect to home
{ path: '/:pathMatch(.*)*', redirect: '/' }
```
A crucial point to get jest to work again, was to add the following to the [jest.config.js](frontend/jest.config.js):
```javascript
transform: {
'^.+\\.vue$': 'vue-jest'
}
```
Otherwise my tests ran into the following error:
```shell
npm run test:unit
> frontend@4.0.0 test:unit
> vue-cli-service test:unit --coverage
FAIL tests/unit/views/User.spec.js
● Test suite failed to run
Vue packages version mismatch:
- vue@3.0.11 (/Users/jonashecht/dev/spring-boot/spring-boot-vuejs/frontend/node_modules/vue/index.js)
- vue-template-compiler@2.6.12 (/Users/jonashecht/dev/spring-boot/spring-boot-vuejs/frontend/node_modules/vue-template-compiler/package.json)
This may cause things to work incorrectly. Make sure to use the same version for both.
If you are using vue-loader@>=10.0, simply update vue-template-compiler.
If you are using vue-loader@<10.0 or vueify, re-installing vue-loader/vueify should bump vue-template-compiler to the latest.
at Object.<anonymous> (node_modules/vue-template-compiler/index.js:10:9)
```
Luckily this so answer helped me out: https://stackoverflow.com/a/65111966/4964553
And finally Bootstrap Vue doesn't support Vue 3.x right now: https://github.com/bootstrap-vue/bootstrap-vue/issues/5196 - So I temporarily commented out the imports.
#### Add TypeScript
Vue 3.x is now build with TypeScript: https://v3.vuejs.org/guide/typescript-support.html
> A static type system can help prevent many potential runtime errors as applications grow, which is why Vue 3 is written in TypeScript. This means you don't need any additional tooling to use TypeScript with Vue - it has first-class citizen support.
There's also a huge documentation of TypeScript itself at https://www.typescriptlang.org/docs/ I can also recommend https://medium.com/js-dojo/adding-typescript-to-your-existing-vuejs-2-6-app-aaa896c2d40a
To migrate your project there's the command:
```shell
vue add typescript
```
The first question arises: `Use class-style component syntax? (Y/n)` whether to use class-style component syntax or not. I didn't use it. I think the interface definitions of components are concise enough without the class-style. But let's see how this will work out.
So this was the output:
```shell
vue add typescript
WARN There are uncommitted changes in the current repository, it's recommended to commit or stash them first.
? Still proceed? Yes
📦 Installing @vue/cli-plugin-typescript...
added 59 packages, removed 58 packages, and audited 2219 packages in 6s
85 packages are looking for funding
run `npm fund` for details
3 low severity vulnerabilities
To address all issues (including breaking changes), run:
npm audit fix --force
Run `npm audit` for details.
✔ Successfully installed plugin: @vue/cli-plugin-typescript
? Use class-style component syntax? No
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
? Use TSLint? Yes
? Pick lint features: Lint on save
? Convert all .js files to .ts? Yes
? Allow .js files to be compiled? Yes
? Skip type checking of all declaration files (recommended for apps)? Yes
🚀 Invoking generator for @vue/cli-plugin-typescript...
📦 Installing additional dependencies...
added 2 packages, and audited 2221 packages in 3s
...
✔ Successfully invoked generator for plugin: @vue/cli-plugin-typescript
```
Now I went through all the componentes and views and extended `<script>` to `<script lang="ts">`.
Also I changed
```javascript
export default {
```
to
```javascript
import { defineComponent } from 'vue';
export default defineComponent({
```
Now we need to transform our JavaScript code into TypeScript.
A really good introduction could be found here: https://www.vuemastery.com/blog/getting-started-with-typescript-and-vuejs/
> This process will take a while, depending on your code - and mainly on your knowledge about TypeScript. But I think it's a great path to go!
Don't forget to deactivate source control for `.js` and `.map` files in `src`, because these will now be generated (aka transpiled) from TypeScript and [shouldn't be checked in (anymore)](https://stackoverflow.com/a/26464907/4964553).
I enhanced my [frontend/.gitignore](frontend/.gitignore) like this:
```shell
# TypeScript
*.map
src/*.js
test/*.js
```
##### Vuex Store with TypeScript
According to https://next.vuex.vuejs.org/guide/typescript-support.html#typing-store-property-in-vue-component in order to use vuex store with TypeScript, we:
> must declare your own module augmentation.
TLDR; we need to create a file [src/vuex.d.ts](frontend/src/vuex.d.ts):
```javascript
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
declare module '@vue/runtime-core' {
// declare your own store states
interface State {
count: number
}
// provide typings for `this.$store`
interface ComponentCustomProperties {
$store: Store<State>
}
}
```
#### Bootstrap support for Vue.js 3/Next
Our View [Bootstrap.vue](frontend/src/views/Bootstrap.vue) is based on the library `bootstrap-vue`, which brings in some nice Bootstrap CSS stylings & components.
But bootstrap-vue isn't compatible with Vue.js 3/Next: https://github.com/bootstrap-vue/bootstrap-vue/issues/5196 and it's unclear, when it's going to support it - or even if at all.
With the upgrade to Vue.js 3.x our `bootstrap-vue` based component view stopped working.
There's also another change: [Bootstrap 5.x is here to be the next evolutionary step - and it even dropped the need for JQuery](https://blog.getbootstrap.com/2020/06/16/bootstrap-5-alpha/).
But also Bootstrap 5.x isn't supported by `bootstrap-vue` right now. So let's try to use Bootstrap without it?!
Therefore install bootstrap next (which - as like Vue.js - stands for the new version 5):
```shell
npm i bootstrap@next
npm i @popperjs/core
```
Since Bootstrap 5 depends on `popperjs` for tooltips (see https://getbootstrap.com/docs/5.0/getting-started/introduction/#js), we also need to include it.
We can remove `"bootstrap-vue": "2.21.2"` and `"jquery": "3.6.0",` from our `package.json`.
We also need to import Bootstrap inside our [main.ts](frontend/src/main.ts):
```javascript
import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
```
Let's try to use Bootstrap 5 inside our [Bootstrap.vue](frontend/src/views/Bootstrap.vue).
And also inside the `Login.vue` and the `Protected.vue`. Using Bootstrap 5.x components without `bootstrap-vue` seems to be no problem (see docs how to use here: https://getbootstrap.com/docs/5.0/components/badge/).
## Build and run with Docker
In the issue [jonashackt/spring-boot-vuejs/issues/25](https://github.com/jonashackt/spring-boot-vuejs/issues/25) the question on how to build and run our spring-boot-vuejs app with Docker.
As already stated in the issue there are multiple ways of doing this. One I want to outline here is a more in-depth variant, where you'll know exacltly what's going on behind the scenes.
First we'll make use of [Docker's multi-stage build feature](https://docs.docker.com/develop/develop-images/multistage-build/) - in __the first stage__ we'll build our Spring Boot Vue.js app using our established Maven build process. Let's have a look into our [Dockerfile](Dockerfile):
```dockerfile
# Docker multi-stage build
# 1. Building the App with Maven
FROM maven:3-jdk-11
ADD . /springbootvuejs
WORKDIR /springbootvuejs
# Just echo so we can see, if everything is there :)
RUN ls -l
# Run Maven build
RUN mvn clean install
```
A crucial part here is to add all necessary files into our Docker build context - but leaving out the underlying OS specific node libraries! As not leaving them out would lead [to errors like](https://stackoverflow.com/questions/37986800/node-sass-could-not-find-a-binding-for-your-current-environment?page=1&tab=active#tab-top):
```
Node Sass could not find a binding for your current environment: Linux 64-bit with Node.js 11.x
```
Therefore we create a [.dockerignore](.dockerignore) file and leave out the directories `frontend/node_modules` & `frontend/node` completely using the `frontend/node*` configuration:
```
# exclude underlying OS specific node modules
frontend/node*
# also leave out pre-build output folders
frontend/target
backend/target
```
We also ignore the pre-build output directories.
In __the second stage__ of our [Dockerfile](Dockerfile) we use the build output of the first stage and prepare everything to run our Spring Boot powered Vue.js app later:
```dockerfile
# Just using the build artifact and then removing the build-container
FROM openjdk:11-jdk
MAINTAINER Jonas Hecht
VOLUME /tmp
# Add Spring Boot app.jar to Container
COPY --from=0 "/springbootvuejs/backend/target/backend-0.0.1-SNAPSHOT.jar" app.jar
ENV JAVA_OPTS=""
# Fire up our Spring Boot app by default
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
```
Now we should everything prepared to run our Docker build:
```
docker build . --tag spring-boot-vuejs:latest
```
This build can take a while, since all Maven and NPM dependencies need to be downloaded for the build.
When the build is finished, simply start a Docker container based on the newly build image and prepare the correct port to be bound to the Docker host for easier access later:
```
docker run -d -p 8098:8098 --name myspringvuejs spring-boot-vuejs
```
Have a look into your running Docker containers with `docker ps` and you should see the new container:
```
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
745e854d7781 spring-boot-vuejs "sh -c 'java $JAVA_O…" 12 seconds ago Up 11 seconds 0.0.0.0:8098->8098/tcp myspringvuejs
```
If you want to see the typical Spring Boot startup logs, just use `docker logs 745e854d7781 --follow`:
```
$ docker logs 745e854d7781 --follow
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.2.RELEASE)
2019-01-29 09:42:07.621 INFO 8 --- [ main] d.j.s.SpringBootVuejsApplication : Starting SpringBootVuejsApplication v0.0.1-SNAPSHOT on 745e854d7781 with PID 8 (/app.jar started by root in /)
2019-01-29 09:42:07.627 INFO 8 --- [ main] d.j.s.SpringBootVuejsApplication : No active profile set, falling back to default profiles: default
2019-01-29 09:42:09.001 INFO 8 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-01-29 09:42:09.103 INFO 8 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 90ms. Found 1 repository interfaces.
2019-01-29 09:42:09.899 INFO 8 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$bb072d94] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-01-29 09:42:10.715 INFO 8 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8098 (http)
2019-01-29 09:42:10.765 INFO 8 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-01-29 09:42:10.765 INFO 8 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.14]
2019-01-29 09:42:10.783 INFO 8 --- [ main] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib]
2019-01-29 09:42:10.920 INFO 8 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-01-29 09:42:10.921 INFO 8 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3209 ms
2019-01-29 09:42:11.822 INFO 8 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-01-29 09:42:12.177 INFO 8 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-01-29 09:42:12.350 INFO 8 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2019-01-29 09:42:12.520 INFO 8 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final}
2019-01-29 09:42:12.522 INFO 8 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2019-01-29 09:42:12.984 INFO 8 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
2019-01-29 09:42:13.894 INFO 8 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2019-01-29 09:42:15.644 INFO 8 --- [ main] o.h.t.schema.internal.SchemaCreatorImpl : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@64524dd'
2019-01-29 09:42:15.649 INFO 8 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-01-29 09:42:16.810 INFO 8 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-01-29 09:42:16.903 WARN 8 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-01-29 09:42:17.116 INFO 8 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [public/index.html]
2019-01-29 09:42:17.604 INFO 8 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-01-29 09:42:17.740 INFO 8 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8098 (http) with context path ''
2019-01-29 09:42:17.745 INFO 8 --- [ main] d.j.s.SpringBootVuejsApplication : Started SpringBootVuejsApplication in 10.823 seconds (JVM running for 11.485)
```
Now access your Dockerized Spring Boot powererd Vue.js app inside your Browser at [http://localhost:8098](http://localhost:8098).
If you have played enough with your Dockerized app, don't forget to stop (`docker stop 745e854d7781`) and remove (`docker rm 745e854d7781`) it in the end.
#### Autorelease to Docker Hub on hub.docker.com
We also want to have the current version of our code build and released to https://hub.docker.com/. Therefore head to the repositories tab in Docker Hub and click `Create Repository`:

As the docs state, there are some config options to [setup automated builds](https://docs.docker.com/docker-hub/builds/).
Finally, we should see our Docker images released on https://hub.docker.com/r/jonashackt/spring-boot-vuejs and could run this app simply by executing:
```
docker run -p 8098:8098 jonashackt/spring-boot-vuejs:latest
```
This pulls the latest `jonashackt/spring-boot-vuejs` image and runs our app locally:
```
docker run -p 8098:8098 jonashackt/spring-boot-vuejs:latest
Unable to find image 'jonashackt/spring-boot-vuejs:latest' locally
latest: Pulling from jonashackt/spring-boot-vuejs
9a0b0ce99936: Pull complete
db3b6004c61a: Pull complete
f8f075920295: Pull complete
6ef14aff1139: Pull complete
962785d3b7f9: Pull complete
e275e7110d81: Pull complete
0ce121b6a2ff: Pull complete
71607a6adeb3: Pull complete
Digest: sha256:4037576ba5f6c58ed067eeef3ab2870a9de8dd1966a5906cb3d36d0ad98fa541
Status: Downloaded newer image for jonashackt/spring-boot-vuejs:latest
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.0.RELEASE)
2019-11-02 16:15:37.967 INFO 7 --- [ main] d.j.s.SpringBootVuejsApplication : Starting SpringBootVuejsApplication v0.0.1-SNAPSHOT on aa490bc6ddf4 with PID 7 (/app.jar started by root in /)
2019-11-02 16:15:37.973 INFO 7 --- [ main] d.j.s.SpringBootVuejsApplication : No active profile set, falling back to default profiles: default
2019-11-02 16:15:39.166 INFO 7 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-11-02 16:15:39.285 INFO 7 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 99ms. Found 1 repository interfaces.
2019-11-02 16:15:39.932 INFO 7 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-11-02 16:15:40.400 INFO 7 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8098 (http)
2019-11-02 16:15:40.418 INFO 7 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
...
2019-11-02 16:15:54.048 INFO 7 --- [nio-8098-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-11-02 16:15:54.081 INFO 7 --- [nio-8098-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 32 ms
```
Now head over to [http://localhost:8098/](http://localhost:8098/) and see the app live :)
# Run with JDK 8, 9 or 11 ff
As with Spring Boot, we can define the desired Java version simply by editing our backend's [pom.xml](backend/pom.xml):
```
<properties>
<java.version>1.8</java.version>
</properties>
```
If you want to have `JDK9`, place a `<java.version>9</java.version>` or other versions just as you like to (see [this stackoverflow answer](https://stackoverflow.com/questions/54467287/how-to-specify-java-11-version-in-spring-spring-boot-pom-xml)).
Spring Boot handles the needed `maven.compiler.release`, which tell's Java from version 9 on to build for a specific target.
We just set `1.8` as the baseline here, since if we set a newer version as the standard, builds on older versions then 8 will fail (see [this build log for example](https://travis-ci.org/jonashackt/spring-boot-vuejs/builds/547227298).
Additionally, we use GitHub Actions to run the Maven build on some mayor Java versions - have a look into the [build.yml](.github/workflows/build.yml) workflow:
```yaml
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java-version: [ 8, 11, 15 ]
```
# Secure Spring Boot backend and protect Vue.js frontend
Securing parts of our application must consist of two parts: securing the Spring Boot backend - and reacting on that secured backend in the Vue.js frontend.
https://spring.io/guides/tutorials/spring-security-and-angular-js/
https://developer.okta.com/blog/2018/11/20/build-crud-spring-and-vue
https://auth0.com/blog/vuejs2-authentication-tutorial/
https://medium.com/@zitko/structuring-a-vue-project-authentication-87032e5bfe16
## Secure the backend API with Spring Security
https://spring.io/guides/tutorials/spring-boot-oauth2
https://spring.io/guides/gs/securing-web/
https://www.baeldung.com/rest-assured-authentication
Now let's focus on securing our Spring Boot backend first! Therefore we introduce a new RESTful resource, that we want to secure specifically:
+---+ +---+ +---+
| | /api/hello | | /api/user | | /api/secured
+---+ +---+ +---+
| | |
+-----------------------------------------------------------------------+
| |
| |
| |
| |
| |
| Spring Boot backend |
| |
+-----------------------------------------------------------------------+
#### Configure Spring Security
First we add a new REST resource `/secured` inside our `BackendController we want to secure - and use in a separate frontend later:
```
@GetMapping(path="/secured")
public @ResponseBody String getSecured() {
LOG.info("GET successfully called on /secured resource");
return SECURED_TEXT;
}
```
With Spring it is relatively easy to secure our API. Let's add `spring-boot-starter-security` to our [pom.xml](backend/pom.xml):
```xml
<!-- Secure backend API -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
```
Also create a new @Configuration annotated class called [WebSecurityConfiguration.class](backend/src/main/java/de/jonashackt/springbootvuejs/configuration/WebSecurityConfiguration.java):
```java
package de.jonashackt.springbootvuejs.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No session will be created or used by spring security
.and()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/api/hello").permitAll()
.antMatchers("/api/user/**").permitAll() // allow every URI, that begins with '/api/user/'
.antMatchers("/api/secured").authenticated()
.anyRequest().authenticated() // protect all other requests
.and()
.csrf().disable(); // disable cross site request forgery, as we don't use cookies - otherwise ALL PUT, POST, DELETE will get HTTP 403!
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("foo").password("{noop}bar").roles("USER");
}
}
```
Using a simple `http.httpBasic()` we configure to provide a Basic Authentication for our secured resources.
To deep dive into the Matcher configurations, have a look into https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#jc-authorize-requests
#### Be aware of CSRF!
__BUT:__ Be aware of the CSRF (cross site request forgery) part! The defaults will render a [HTTP 403 FORBIDDEN for any HTTP verb that modifies state (PATCH, POST, PUT, DELETE)](https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#csrf-configure):
> by default Spring Security’s CSRF protection will produce an HTTP 403 access denied.
For now we can disable the default behavior with `http.csrf().disable()`
#### Testing the secured Backend
See https://www.baeldung.com/rest-assured-authentication
Inside our [BackendControllerTest](backend/src/test/java/de/jonashackt/springbootvuejs/controller/BackendControllerTest.java) we should check, whether our API reacts with correct HTTP 401 UNAUTHORIZED, when called without our User credentials:
```
@Test
public void secured_api_should_react_with_unauthorized_per_default() {
given()
.when()
.get("/api/secured")
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
}
```
Using `rest-assured` we can also test, if one could access the API correctly with the credentials included:
```
@Test
public void secured_api_should_give_http_200_when_authorized() {
given()
.auth().basic("foo", "bar")
.when()
.get("/api/secured")
.then()
.statusCode(HttpStatus.SC_OK)
.assertThat()
.body(is(equalTo(BackendController.SECURED_TEXT)));
}
```
The crucial point here is to use the `given().auth().basic("foo", "bar")` configuration to inject the correct credentials properly.
#### Configure credentials inside application.properties and environment variables
Defining the users (and passwords) inside code (like our [WebSecurityConfiguration.class](backend/src/main/java/de/jonashackt/springbootvuejs/configuration/WebSecurityConfiguration.java)) that should be given access to our application is a test-only practice!
For our super simple example application, we could have a solution quite similar - but much more safe: If we would be able to extract this code into configuration and later use Spring's powerful mechanism of overriding these configuration with environment variables, we could then store them safely inside our deployment pipelines settings, that are again secured by another login - e.g. as Heroku Config Vars.
Therefore the first step would be to delete the following code:
```
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("foo").password("{noop}bar").roles("USER");
}
```
and add the following configuration to our [application.properties](backend/src/main/resources/application.properties):
```
spring.security.user.name=sina
spring.security.user.password=miller
```
Running our tests using the old credentials should fail now. Providing the newer one, the test should go green again.
Now introducing environment variables to the game could also be done locally inside our IDE for example. First change the test `secured_api_should_give_http_200_when_authorized` again and choose some new credentials like user `maik` with pw `meyer`.
Don't change the `application.properties` right now - use your IDE's run configuration and insert two environment variables:
```
SPRING_SECURITY_USER_NAME=maik
SPRING_SECURITY_USER_PASSWORD=meyer
```
Now the test should run green again with this new values.
## Protect parts of Vue.js frontend
Now that we have secured a specific part of our backend API, let's also secure a part of our Vue.js frontend:
+-----------------------------------------------------------------------+
| Vue.js frontend |
| |
| +-----------------+ +-----------------+ +-----------------+ |
| | | | | | | |
| | | | | | Protected | |
| | | | | | | |
| | | | | | Vue.js View | |
| | | | | | | |
| +-----------------+ +-----------------+ +-----------------+ |
| |
+-----------------------------------------------------------------------+
+---+ +---+ +---+
| | /api/hello | | /api/user | | /api/secured
+---+ +---+ +---+
| | |
+-----------------------------------------------------------------------+
| |
| |
| |
| |
| |
| |
| Spring Boot backend |
+-----------------------------------------------------------------------+
#### Create a new Vue Login component
As there is already a secured Backend API, we also want to have a secured frontend part.
Every solution you find on the net seems to be quite overengineered for the "super-small-we-have-to-ship-today-app". Why should we bother with a frontend auth store like vuex at the beginning? Why start with OAuth right up front? These could be easily added later on!
The simplest solution one could think about how to secure our frontend, would be to create a simple Login.vue component, that simply accesses the `/api/secured` resource every time the login is used.
Therefore we use [Vue.js conditionals](https://vuejs.org/v2/guide/conditional.html) to show something on our new [Login.vue](frontend/src/components/Login.vue):
```
<template>
<div class="protected" v-if="loginSuccess">
<h1><b-badge variant="success">Access to protected site granted!</b-badge></h1>
<h5>If you're able to read this, you've successfully logged in.</h5>
</div>
<div class="unprotected" v-else-if="loginError">
<h1><b-badge variant="danger">You don't have rights here, mate :D</b-badge></h1>
<h5>Seams that you don't have access rights... </h5>
</div>
<div class="unprotected" v-else>
<h1><b-badge variant="info">Please login to get access!</b-badge></h1>
<h5>You're not logged in - so you don't see much here. Try to log in:</h5>
<form @submit.prevent="callLogin()">
<input type="text" placeholder="username" v-model="user">
<input type="password" placeholder="password" v-model="password">
<b-btn variant="success" type="submit">Login</b-btn>
<p v-if="error" class="error">Bad login information</p>
</form>
</div>
</template>
<script>
import api from './backend-api'
export default {
name: 'login',
data () {
return {
loginSuccess: false,
loginError: false,
user: '',
password: '',
error: false
}
}
}
</script>
```
For now the conditional is only handled by two boolean values: `loginSuccess` and `loginError`.
To bring those to life, we implement the `callLogin()` method:
```
,
methods: {
callLogin() {
api.getSecured(this.user, this.password).then(response => {
console.log("Response: '" + response.data + "' with Statuscode " + response.status)
if(response.status == 200) {
this.loginSuccess = true
}
}).catch(error => {
console.log("Error: " + error)
this.loginError = true
})
}
}
```
With this simple implementation, the Login component asks the Spring Boot backend, if a user is allowed to access the `/api/secured` resource. The [backend-api.js](frontend/src/components/backend-api.js) provides an method, which uses axios' Basic Auth feature:
```
getSecured(user, password) {
return AXIOS.get(`/secured/`,{
auth: {
username: user,
password: password
}});
}
```
Now the Login component works for the first time:

#### Protect multiple Vue.js components
Now we have a working Login component. Now let's create a new `Protected.vue` component, since we want to have something that's only accessible, if somebody has logged in correctly:
```
<template>
<div class="protected" v-if="loginSuccess">
<h1><b-badge variant="success">Access to protected site granted!</b-badge></h1>
<h5>If you're able to read this, you've successfully logged in.</h5>
</div>
<div class="unprotected" v-else>
<h1><b-badge variant="info">Please login to get access!</b-badge></h1>
<h5>You're not logged in - so you don't see much here. Try to log in:</h5>
<router-link :to="{ name: 'Login' }" exact target="_blank">Login</router-link>
</div>
</template>
<script>
import api from './backend-api'
export default {
name: 'protected',
data () {
return {
loginSuccess: false,
error: false
}
},
methods: {
//
}
}
</script>
```
This component should only be visible, if the appropriate access was granted at the Login. Therefore we need to solve 2 problems:
* __Store the login state__
* __Redirect user from Protected.vue to Login.vue, if not authenticated before__
#### Store login information with vuex
The super dooper simple solution would be to simply use `LocalStorage`. But with [vuex](https://github.com/vuejs/vuex) there is a centralized state management in Vue.js, which is pretty popular. So we should invest some time to get familiar with it. There's a full guide available: https://vuex.vuejs.org/guide/ and a great introductory blog post here: https://pusher.com/tutorials/authentication-vue-vuex
You could also initialize a new Vue.js project with Vue CLI and mark the `vuex` checkbox. But we try to extend the current project here.
First we add [the vuex dependency](https://www.npmjs.com/package/vuex) into our [package.json](frontend/package.json):
```
...
"vue": "^2.6.10",
"vue-router": "^3.0.6",
"vuex": "^3.1.1"
},
```
> There are four things that go into a Vuex module: the initial [state](https://vuex.vuejs.org/guide/state.html), [getters](https://vuex.vuejs.org/guide/getters.html), [mutations](https://vuex.vuejs.org/guide/mutations.html) and [actions](https://vuex.vuejs.org/guide/actions.html)
#### Define the vuex state
To implement them, we create a new [store.js](frontend/src/store.js) file:
```
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
loginSuccess: false,
loginError: false,
userName: null
},
mutations: {
},
actions: {
},
getters: {
}
})
```
We only have an initial state here, which is that a login could be successful or not - and there should be a `userName`.
#### Define a vuex action login() and the mutations login_success & login_error
Then we have a look onto __vuex actions: They provide a way to commit mutations to the vuex store.__
As our app here is super simple, we only have one action to implement here: `login`. We omit the `logout` and `register` actions, because we only define one admin user in the Spring Boot backend right now and don't need an implemented logout right now. Both could be implemented later!
We just shift our logic on how to login a user from the `Login.vue` to our vuex action method:
```
mutations: {
login_success(state, name){
state.loginSuccess = true
state.userName = name
},
login_error(state){
state.loginError = true
state.userName = name
}
},
actions: {
async login({commit}, user, password) {
api.getSecured(user, password)
.then(response => {
console.log("Response: '" + response.data + "' with Statuscode " + response.status);
if(response.status == 200) {
// place the loginSuccess state into our vuex store
return commit('login_success', name);
}
}).catch(error => {
console.log("Error: " + error);
// place the loginError state into our vuex store
commit('login_error', name);
return Promise.reject("Invald credentials!")
})
}
},
```
Instead of directly setting a boolean to a variable, we `commit` a mutation to our store if the authentication request was successful or unsuccessful. We therefore implement two simple mutations: `login_success` & `login_error`
#### Last but not least: define getters for the vuex state
To be able to access vuex state from within other components, we need to implement getters inside our vuex store. As we only want some simple info, we need the following getters:
```
getters: {
isLoggedIn: state => state.loginSuccess,
hasLoginErrored: state => state.loginError
}
```
#### Use vuex Store inside the Login component and forward to Protected.vue, if Login succeeded
Instead of directly calling the auth endpoint via axios inside our Login component, we now want to use our vuex store and its actions instead. Therefore we don't even need to import the [store.js](frontend/src/store.js) inside our `Login.vue`, we can simply access it through `$store`. Thy is that? Because we already did that inside our [main.js](frontend/src/main.js):
```
import store from './store'
...
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
```
With that configuration `store` and `router` are accessible from within every Vue component with the `$` prefixed :)
If we have a look into our `Login.vue` we see that in action:
```
callLogin() {
this.$store.dispatch('login', { user: this.user, password: this.password})
.then(() => this.$router.push('/Protected'))
.catch(error => {
this.error.push(error)
})
}
```
Here we access our vuex store action `login` and issue a login request to our Spring Boot backend. If this succeeds, we use the Vue `$router` to forward the user to our `Protected.vue` component.
#### Redirect user from Protected.vue to Login.vue, if not authenticated before
Now let's enhance our [router.js](frontend/src/router.js) slightly. We use the Vue.js routers' [meta field](https://router.vuejs.org/guide/advanced/meta.html) feature to check, whether a user is loggin in already and therefore should be able to access our Protected component with the URI `/protected` :
```
{
path: '/protected',
component: Protected,
meta: {
requiresAuth: true
}
},
```
We also add a new behavior to our router, that checks if it requires authentication every time a route is accessed. If so, it will redirect to our Login component:
```
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!store.getters.isLoggedIn) {
next({
path: '/login'
})
} else {
next();
}
} else {
next(); // make sure to always call next()!
}
});
```
Now if one clicks onto `Protected` and didn't login prior, our application redirects to `Login` automatically:

With this redirect, we also don't need the part with `<div class="protected" v-if="loginSuccess">` inside our Login.vue, since in case of a successful login, the user is directly redirected to the Protected.vue.
## Check auth state at secured backend endpoints
We're now already where we wanted to be at the first place: Our Spring Boot backend has a secured API endpoint, which works with simple user/password authentication. And our Vue.js frontend uses this endpoint to do a Login and protect the `Protected` component, if the user didn't log in before. The login state is held in the frontend, using the `vuex` store.
Now if we want to go a step ahead and call a secured API endpoint in the backend from within our `Protected` frontend component, we need to fully store the credentials inside our `vuex` store, so we could access our secured resource
+-----------------------------------------------------------------------+
| Vue.js frontend |
| +----------------------------------------+ |
| | vuex store | |
| +----------------------------------------+ |
| | | |
| +-----------------+ +-----------------+ +-----------------+ |
| | | | | | | |
| | | | Login.vue | | Protected | |
| | | | | | | |
| +-----------------+ +-----------------+ +-----------------+ |
| | | |
+-------------------------------------------|---------------|-----------+
|-------------| |
+---+ +---+ +---+
| | /api/hello | | /api/user | | /api/secured
+---+ +---+ +---+
| | |
+-----------------------------------------------------------------------+
| |
| |
| |
| |
| |
| |
| Spring Boot backend |
+-----------------------------------------------------------------------+
Therefore we enhance our [store.js](frontend/src/store.js):
```
export default new Vuex.Store({
state: {
loginSuccess: false,
loginError: false,
userName: null,
userPass: null,
response: []
},
mutations: {
login_success(state, payload){
state.loginSuccess = true;
state.userName = payload.userName;
state.userPass = payload.userPass;
},
...
},
actions: {
login({commit}, {user, password}) {
...
// place the loginSuccess state into our vuex store
commit('login_success', {
userName: user,
userPass: password
});
...
getters: {
isLoggedIn: state => state.loginSuccess,
hasLoginErrored: state => state.loginError,
getUserName: state => state.userName,
getUserPass: state => state.userPass
}
```
> Be sure to use the current way to define and [interact with vuex mutations](https://vuex.vuejs.org/guide/mutations.html). Lot's of blog posts are using an old way of committing multiple parameters like `commit('auth_success', token, user)`. This DOES NOT work anymore. Only the first parameter will be set, the others are lost!
Now inside our [Protected.vue](frontend/src/components/Protected.vue), we can use the stored credentials to access our `/secured` endpoint:
```
<script>
import api from './backend-api'
import store from './../store'
export default {
name: 'protected',
data () {
return {
backendResponse: '',
securedApiCallSuccess: false,
errors: null
}
},
methods: {
getSecuredTextFromBackend() {
api.getSecured(store.getters.getUserName, store.getters.getUserPass)
.then(response => {
console.log("Response: '" + response.data + "' with Statuscode " + response.status);
this.securedApiCallSuccess = true;
this.backendResponse = response.data;
})
.catch(error => {
console.log("Error: " + error);
this.errors = error;
})
}
}
}
```
Feel free to create a nice GUI based on `securedApiCallSuccess`, `backendResponse` and `errors` :)
# Links
Nice introductory video: https://www.youtube.com/watch?v=z6hQqgvGI4Y
Examples: https://vuejs.org/v2/examples/
Easy to use web-based Editor: https://vuejs.org/v2/examples/
| 1 |
TimothyWrightSoftware/Fundamental-2D-Game-Programming-With-Java | Source code examples for the book Fundamental 2D Game Programming with Java"" | null | # Fundamental-2D-Game-Programming-With-Java
Source code examples for the book "Fundamental 2D Game Programming with Java"
| 0 |
carlphilipp/clean-architecture-example | An example to create a clean architecture with Java 11 | clean-architecture | ## Clean Architecture Example
### Blog post
https://medium.com/slalom-engineering/clean-architecture-with-java-11-f78bba431041
### Pre-requisite
Java 11
```
> java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
```
### Compile
`./gradlew clean build`
### Run Spring example
`java -jar application/spring-app/build/libs/spring-app-1.0.0.jar`
### Run Vertx example
`java -jar application/vertx-app/build/libs/vertx-app-1.0.0-fat.jar`
### Use the webbapps
#### Create User
```
POST: http://localhost:8080/users
Body:
{
"email": "test@test.com",
"password": "mypassword",
"lastName": "Doe",
"firstName": "John"
}
```
#### Get all users
```
GET: http://localhost:8080/users
```
#### Get one user
```
GET: http://localhost:8080/users/0675171368e011e882d5acde48001122
```
#### Login
```
GET: http://localhost:8080/login?email=test@test.com&password=mypassword
```
| 1 |
cstew/Splash | An example of a splash screen done the right way | null | # Splash
An example of a splash screen done the right way on Android

| 1 |
RameshMF/gof-java-design-patterns | Repository for all GOF design patterns with examples in Java. | design-patterns gof-patterns | <div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-dXzvWYhPucA/WwgfWrX75CI/AAAAAAAACR8/Tz_HGOSwSoARRBXJBOpHtW0C7u1dIBkwgCLcBGAs/s1600/design_patterns_gof.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: "verdana" , sans-serif;"><img border="0" data-original-height="88" data-original-width="365" height="154" src="https://3.bp.blogspot.com/-dXzvWYhPucA/WwgfWrX75CI/AAAAAAAACR8/Tz_HGOSwSoARRBXJBOpHtW0C7u1dIBkwgCLcBGAs/s640/design_patterns_gof.png" width="640"></span></a></div>
<span style="font-family: "verdana" , sans-serif;">List of all design patterns referred from the book: <a href="https://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612v" target="_blank">Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series)</a><img alt="" border="0" height="1" src="//ir-in.amazon-adsystem.com/e/ir?t=rameshfadatar-21&l=am2&o=31&a=B000SEIBB8" style="border: none !important; margin: 0px !important;" width="1"></span><br>
<span style="font-family: "verdana" , sans-serif;">All the design patterns explained by real-world examples, class diagrams, source code, applicability, references etc.</span><br>
<h3 style="text-align: left;">
<span style="font-family: "verdana" , sans-serif;">Design Patterns(GOF)</span></h3>
<div class="widget LinkList" data-version="2" id="LinkList1">
<div class="widget-content">
<ul>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/design-patterns-overview.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Design Patterns Overview</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2018/01/object-oriented-design-principles.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Object Oriented Design Principles</span></a></li>
</ul>
</div>
</div>
<div class="widget LinkList" data-version="2" id="LinkList2">
<h3 class="title">
<span style="font-family: "verdana" , sans-serif;"> Creational Patterns </span></h3>
<div class="widget-content">
<ul>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/singleton-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Singleton Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/factory-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Factory Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/abstract-factory-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Abstract Factory Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/builder-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Builder Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/prototype-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Prototype Design Pattern</span></a></li>
<li><a href="http://ramesh-java-design-patterns.blogspot.com/2018/05/object-pool-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Object Pool Design Pattern</span></a></li>
</ul>
</div>
</div>
<div class="widget LinkList" data-version="2" id="LinkList3">
<h3 class="title">
<span style="font-family: "verdana" , sans-serif;"> Structural Patterns </span></h3>
<div class="widget-content">
<ul>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/adapter-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Adapter Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/bridge-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Bridge Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/composite-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Composite Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/decorator-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Decorator Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/facade-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Facade Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/flyweight-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Flyweight Design Pattern</span></a></li>
<li><a href="http://ramesh-java-design-patterns.blogspot.in/2017/12/proxy-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Proxy Design Pattern</span></a></li>
</ul>
</div>
</div>
<div class="widget LinkList" data-version="2" id="LinkList4">
<h3 class="title">
<span style="font-family: "verdana" , sans-serif;"> Behavioral Patterns </span></h3>
<div class="widget-content">
<ul>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/chain-of-responsibility.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Chain of responsibility</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/command-design-pattern_23.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Command Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/iterator-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Iterator Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2018/03/mediator-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Mediator Design Pattern</span></a></li>
<li><a href="http://ramesh-java-design-patterns.blogspot.in/2018/03/memento-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Memento Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/observer-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Observer Design Pattern</span></a></li>
<li><a href="http://ramesh-java-design-patterns.blogspot.in/2018/02/state-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">State Design Pattern</span></a></li>
<li><a href="http://ramesh-java-design-patterns.blogspot.in/2018/02/strategy-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Strategy Design Pattern</span></a></li>
<li><a href="https://ramesh-java-design-patterns.blogspot.in/2017/12/template-method-design-pattern.html" target="_blank"><span style="font-family: "verdana" , sans-serif;">Template Method Design Pattern</span></a></li>
<li><span style="font-family: "verdana" , sans-serif;"><a href="https://ramesh-java-design-patterns.blogspot.in/2018/05/delegation-pattern.html" target="_blank">Delegation Pattern</a></span></li>
</ul>
<div>
<span style="font-family: "verdana" , sans-serif;">Download source code from our Github Repository :</span></div>
<div>
<span style="font-family: "verdana" , sans-serif;"><a href="https://github.com/RameshMF/gof-java-design-patterns" target="_blank">https://github.com/RameshMF/gof-java-design-patterns</a></span></div>
</div>
</div>
</div>
| 0 |
chcordova/design-patterns-head-first-book | O'Reilly Head First Design Patterns - Java 8 Examples | null | # [O'Reilly Head First Design Patterns] - Java 8 Examples

| 0 |
florina-muntenescu/DroidconMVVM | Hello | World!" example of the Model-View-ViewModel pattern" | # Model-View-ViewModel "Hello, World!"
This is a "Hello, World!" project done for a Droidcon Zagreb 2016 talk on [MVVM & RxJava – the perfect mix][droidcon].
The project contains an exemplification of the Model-View-ViewModel pattern used together with RxJava.
A "Hello, World!" greeting will be displayed based on the selected language.
The `DataModel` provides supported languages and also retrieval of the greeting based on the language.
The `ViewModel` exposes greetings and supported languages as stream of events through [RxJava Observables][observables]. The ViewModel also allows setting the selected language.
The `View` is an Activity that contains a Spinner with the supported languages and a text view that displays a greeting, based on the selected language.

[droidcon]: <http://droidcon.hr/en/sessions/mvvm-rxjava-perfect-mix/>
[observables]: <http://reactivex.io/documentation/observable.html>
| 0 |
gridgain/gridgain-advanced-examples | null | null | gridgain-advanced-examples
=========================
This project contains advanced examples of GridGain usage, above and beyond the examples that are included with the GridGain distributions.
| 0 |
gzz2017gzz/spring-boot2-example | spring-boot2- example | null | null | 1 |
MahmoudElSharkawy/Automation-Practice | Test Automation Practice Examples | null | # Automation-Practice
This is where I practice Test Automation!
### The main Frameworks included in the project:
* Selenium Webdriver
* Rest-Assured
* TestNG
* Allure Report
* Extent Reports
* Apachi POI
### Project Design:
* Page Object Model (POM) design pattern
* Data Driven framework
* Fluent design approach (method chaining)
* Have a supporting Utilities package in *src/main/java* file path, named ***"Utils"*** that includes many wrapper methods in static classes which services as a core engine for the project
* Implementing the ***Test Automation Pyramid*** by have 2 different test automation levels which are SERVICE and GUI layers
### How to check the execution logs and open the latest execution reports from GitHub Actions:
* You need to be logged-in to the GitHub as a prerequisite
* Open the GitHub Actions tab
* Open the latest workflow run from the list
* To check the execution logs, click on "Test on Ubuntu" job and open the "Run Tests - Chrome Headless" step and then you can see and check the execution logs
* To open the Allure report, in the *Artifacts* section, Click on the "Allure Report" and then unzip the archive file and then open the "index.html" file (If you are on Windows and the report opened with empty data, you need to open the "allow-file-access_open-report_chrome_windows.bat" file to be able to see the report data)
* To open the Extent report, in the *Artifacts* section, Click on the "Extent Report" and then unzip the archive file and then open the "ExtentReports.html" file
### How to run the project main test cases locally:
* A properties file ***"automationPractice.properties"*** can be found it *src/main/resources* file path including all the configurations needed in the execution
* Can find the test cases in the *src/test/java* folder mainly in the *phptravels.tests* and *restfulbooker.tests* packages
* Can find the test suite for all the main practice test cases in the *src/test/resources/TestSuits* folder in the *automationPractice.xml* file
* To start the execution, please make sure that the "execution.type" property is "Local" if you are running locally then right click on the test suite xml file and click Run As >> TestNG Suit
* After executing, you can easily generate the ***Allure Report*** by opening a command-line terminal on the project root path and type `mvn allure:serve` (needs to be able to execute mvn commands); Or you can find the Extent Report ***ExtentReports.html*** in the project root path for the latest execution
###### Finally, you can also find a [playlist on Youtube](https://youtube.com/playlist?list=PLmayvCz0Xqr6TT-XJHlPtjDSdJ8WArBHi) (Arabic content) that summarizes and executing the project for some cases
| 0 |
JenniferRanjani/Object-Oriented-Programming-with-Java | Contains basic examples for understanding Java concepts. | null | # Object-Oriented-Programming-with-Java
Contains the codes used for demonstrating the concepts
| 0 |
LB-Yu/data_systems_learning | Learning summary and examples about data systems. | big-data distributed-systems flink hbase spark | This repository contains some demos for learning data systems. Specifically contains:
+ Demos of SQL parsing tools, such as Apache callcite, Antlr.
+ Demo of big data storage and computing framework, such as Hadoop, Kafka, Flink. | 0 |
javaturk/OOP | Examples of OOP with Java course. | null | Programming examples for OOP with Java.
This is a repository that has all of the examples of OOP with Java course.
The presentations and other materials can be found at www.javaturk.org address.
Please contact me at akin@javaturk.org if you need further help.
Thanks.
| 0 |
forax/loom-fiber | Continuation & Fiber examples using the OpenJDK project Loom prototype | null | # loom-fiber
This repository contains both my experimentation of the OpenJDK project Loom prototype
and a presentation and examples showing how to use it.
There is a [presentation of the loom project](loom%20is%20looming.pdf)
wiht the [examples](src/main/java/fr/umlv/loom/example).
## How to build
Download the latest early access build of jdk-20 [http://jdk.java.net/](http://jdk.java.net/)
set the environment variable JAVA_HOME to point to that JDK and then use Maven.
```
export JAVA_HOME=/path/to/jdk
mvn package
```
## How to run the examples
On top of each example, there is the command line to run it.
- Loom is a preview version so `--enable-preview` is required,
- For `ScopeLocal` and `StructuredTaskScope`, these are not yet part of the official API
and are declared in module/package `jdk.incubator.concurrent`so this module
has to be added to the command line with `--add-modules jdk.incubator.concurrent`,
- If you want to play with the internals, the class `Continuation` is hidden thus
`--add-exports java.base/jdk.internal.vm=ALL-UNNAMED` should be added to the command line.
## AsyncScope
This repository also contains a high-level structured concurrency construct named
[src/main/java/fr/umlv/loom/structured/AsyncScope.java](AsyncScope) that is a proposed replacement
to the more low level `StructuredTaskScope` currently provided by the OpenJDK loom repository.
## Loom actor framework
At some point of the history, this project was containing an actor system based on loom.
It has now its own repository [https://github.com/forax/loom-actor](https://github.com/forax/loom-actor).
## Loom expressjs
There is a re-implementation of the [expressjs API](https://expressjs.com/en/4x/api.html) in Java using Loom
[JExpressLoom.java](https://github.com/forax/jexpress/blob/master/src/main/java/JExpressLoom.java).
| 0 |
suyash248/spring_framework | Examples on Spring(Core, AOP, DAO, Transaction Management) | java spring spring-aop spring-core spring-dao spring-di spring-transaction-manager | # Spring Framework
- Spring Core(IOC & DI)
- Spring AOP
- Spring DAO & Integrations
- Spring Transaction Management
| 0 |
njnareshjoshi/articles | This repository along with the exercises repository (https://github.com/njnareshjoshi/exercises) contains coding examples for my blog ProgrammingMitra | java java-8 java-cloning java-serialization jpa-auditing spring spring-data | This repository along with the [exercises](https://github.com/njnareshjoshi/exercises) repository contains coding examples for my blog [ProgrammingMitra](https://www.programmingmitra.com).
### Spring
* [Introduction To Spring](https://www.programmingmitra.com/2016/05/introduction-to-spring.html)
* [Spring Modular Architecture](https://www.programmingmitra.com/2018/07/spring-modular-architecture.html)
### Spring Data
* [Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate Automatically](https://www.programmingmitra.com/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html)
* [JPA Auditing: Persisting Audit Logs Automatically Using EntityListeners](https://www.programmingmitra.com/2017/02/automatic-jpa-auditing-persisting-audit-logs-automatically-using-entityListeners.html)
* [AutoWiring Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners](https://www.programmingmitra.com/2017/03/AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners.html)
* [Implementing Our Own Custom Spring Data Solr Repository](https://www.programmingmitra.com/2016/01/how-to-write-custom-implementation-for.html)
### What In Java
* [What is Variable Shadowing And Hiding In Java](https://www.programmingmitra.com/2018/02/what-is-variable-shadowing-and-hiding.html)
* [Everything About Method Overloading Vs Method Overriding](https://www.programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html)
* [Everything About ClassNotFoundException Vs NoClassDefFoundError](https://www.programmingmitra.com/2017/04/Difference-Between-ClassNotFoundException-and-NoClassDefFoundError.html)
* [Java Cloning - Copy Constructor versus Cloning](https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html)
* [Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example](https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html)
* [Java Lambda Expression Explained With Example](https://www.programmingmitra.com/2016/06/java-lambda-expression-explained-with-example.html)
* [What are JDK And JRE? JDK And JRE File Structure Explained](https://www.programmingmitra.com/2016/05/jdk-and-jre-file-structure.html)
* [What are 5 Different Ways To Create Objects In Java? Explained With Example](https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html)
* [Plain Old Java Object (POJO) Explained](https://www.programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html)
* [Types Of References In Java(Strong Soft Weak Phantom)](https://www.programmingmitra.com/2016/05/types-of-references-in-javastrong-soft.html)
* [What is Serialization? Everything About Java Serialization Explained With Example](https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html)
* [Java Serialization Magic Methods And Their Uses With Example](https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html)
### Why In Java
* [Java Integer Cache - Why Integer.valueOf(127) == Integer.valueOf(127) Is True](https://www.programmingmitra.com/2018/11/java-integer-cache.html)
* [Why Instance Variable Of Super Class Is Not Overridden In Sub Class](https://www.programmingmitra.com/2018/11/why-instance-variable-of-super-class-is-not-overridden-In-sub-class.html)
* [Why String is Immutable And Final In Java](https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html)
* [Why String is Stored In String Constant Pool](https://www.programmingmitra.com/2018/02/why-string-is-stored-in-constant-pool.html)
* [Why We Should Follow Method Overriding Rules](https://www.programmingmitra.com/2017/12/why-we-should-follow-method-overriding-rules.html)
* [Why Should We Follow Method Overloading Rules](https://www.programmingmitra.com/2017/12/why-to-follow-method-overloading-rules.html)
* [How Does JVM Handle Method Overloading And Overriding Internally](https://www.programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html)
* [Java Cloning - Why Even Copy Constructors Are Not Sufficient](https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html)
* [Java Cloning - Copy Constructor versus Cloning](https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html)
* [Why An outer Java class can’t be static](https://www.programmingmitra.com/2016/10/why-outer-java-class-cant-be-static.html)
* [Why An outer Java class can’t be private or protected](https://www.programmingmitra.com/2016/10/why-a-java-class-can-not-be-private-or-protected.html)
* [Why Java is Purely Object Oriented Language Or Why Not](https://www.programmingmitra.com/2016/06/why-java-is-purely-object-oriented-or-why-not.html)
* [Why Single Java Source File Can Not Have More Than One public class](https://www.programmingmitra.com/2016/05/Why-Single-Java-Source-File-Can-Not-Have-More-Than-One-public-class.html)
### How In Java
* [How To Customize Serialization In Java By Using Externalizable Interface](https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html)
* [What are 5 Different Ways To Create Objects In Java? Explained With Example](https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html)
* [How To Create Objects By Using Reflection APIs In Java With Example](https://www.programmingmitra.com/2016/05/creating-objects-through-reflection-in-java-with-example.html)
* [How To Install Multiple Versions Of Java On The Same Machine](https://www.programmingmitra.com/2019/03/how-to-install-multiple-versions-of-java-on-the-same-machine.html)
* [How To Create An Immutable Class In Java With Example](https://www.programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html)
* [How Does JVM Handle Polymorphism (Method Overloading And Method Overriding) Internally](https://www.programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html)
* [Java Cloning - How Copy Constructors are Better Than Cloning](https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html)
* [How To Create An Immutable Class In Java With Example](https://www.programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html)
### Useful Dev Tools
* [How To Install Multiple Versions Of Java On The Same Machine](https://www.programmingmitra.com/2019/03/how-to-install-multiple-versions-of-java-on-the-same-machine.html)
* [Project Lombok : The Boilerplate Code Extractor](https://www.programmingmitra.com/2017/01/Project-Lombok-The-Boilerplate-Code-Extractor.html)
* [Useful Git Commands](https://www.programmingmitra.com/2019/01/useful-git-commands.html)
### ClassNotFoundException Vs NoClassDefFoundError
* [Difference Between ClassNotFoundException And NoClassDefFoundError](https://www.programmingmitra.com/2017/04/Difference-Between-ClassNotFoundException-and-NoClassDefFoundError.html)
### Java Cloning Vs Copy Constructors Vs Defensive Copy Methods
* [Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example](https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html)
* [Java Cloning Copy Constructor Versus Object Clone Or Cloning](https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html)
* [Java Cloning Why Copy Constructors Are Not Sufficient Or Good](https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html)
### Immutability In Java
* [How To Create Immutable Class In Java](https://www.programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html)
* [Why String Is Immutable And Final In Java](https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html)
### Java Integer Cache
* [Java Integer Cache - Why Integer.valueOf(127) == Integer.valueOf(127) Is True](https://www.programmingmitra.com/2018/11/java-integer-cache.html)
### Java 8 - Lambda
* [Java Lambda Expression Explained With Example](https://www.programmingmitra.com/2016/06/java-lambda-expression-explained-with-example.html)
* [How To Install Multiple Versions Of Java On The Same Machine](https://www.programmingmitra.com/2019/03/how-to-install-multiple-versions-of-java-on-the-same-machine.html)
### Java Object Creation
* [Different Ways To Create Objects In Java With Example](https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html)
* [How To Create Objects By Using Reflection APIs In Java With Example](https://www.programmingmitra.com/2016/05/creating-objects-through-reflection-in-java-with-example.html)
### Java Method Overloading And Overriding
* [Everything About Method Overloading Vs Method Overriding](https://www.programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html)
* [Why We Should Follow Method Overriding Rules](https://www.programmingmitra.com/2017/12/why-we-should-follow-method-overriding-rules.html)
* [How Does JVM Handle Method Overloading And Overriding Internally](https://www.programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html)
* [Why Instance Variable Of Super Class Is Not Overridden In Sub Class](https://www.programmingmitra.com/2018/11/why-instance-variable-of-super-class-is-not-overridden-In-sub-class.html)
### Java Serialization And Externalization
* [What is Serialization? Everything About Java Serialization Explained With Example](https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html)
* [How To Customize Serialization In Java By Using Externalizable Interface](https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html)
* [What are 5 Different Ways To Create Objects In Java? Explained With Example](https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html)
* [Java Serialization Magic Methods And Their Uses With Example](https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html) | 0 |
RandyAbernethy/ThriftBook | Source for the examples in the Programmer's Guide to Apache Thrift | null | The Programmer's Guide to Apache Thrift
=======================================
Source for the examples in: The Programmer's Guide to Apache Thrift
http://www.manning.com/abernethy/
The book is organized into three parts:
Part I - Apache Thrift Overview
-------------------------------
A high level introduction to Apache Thrift and its architecture. Examples from this part are hello worldish. This part also covers basic Apache Thrift setup and debugging.
Part II - Programming Apache Thrift
-----------------------------------
This part digs into each layer of the Apache Thrift framework, examining transports, protocols, types, services, servers and the Apache Thrift interface definition language in detail. Examples from these chapters use C++, Java and Python as the demonstration languages. C++ examples provide makefiles and Java examples provide Build.xml files for building with make/ant respectively. Build scripts and code have been tested with various Apache Thrift versions. In general you should use the latest version of Apache Thrift. The Ant builds depend on SLF4J. The python examples are directly executable. You can checkout older version of this repo for examples compatible with older versions of Apache Thrift.
Part III - Apache Thrift Language Libraries
-------------------------------------------
This part of the book provides jump starts for the most popular platforms and languages used with Apache Thrift. The Web, and backend systems are examined through the lens of C++, Java, C#, JavaScript, Python, PHP, Perl and Ruby. Web chapters are complete or in-progress for Haxe, Go and Rust (code is/will-be found here). Part III also includes the final chapter, "Apache Thrift in the Enterprise", which demonstrates Apache Thrift in use with messaging systems and takes a pragmatic look at the key advantages of Apache Thrift and some of the common best practices for developing with the framework.
Tools - Miscellaneous Thrift Stuff
----------------------------------
This folder is for various Thrift related stuff. Presently only a GEdit language file for Apache Thrift IDL.
Development Environment
-----------------------
The Dockerfile in the root of this repo defines a development environment for the book which will make it easy to build and test all of the examples in the book. This file is configured to support C++, Java and Python as built but it is easy to add additional language support to the container or similarly configured system by following the instruction in the book. Apache Thrift is undergoing an important change on the way to v1.0.
- Switch out of the build platform (compiler and all libs) from autotools to cmake
As things migrate I will update this Dockerfile. You can "$ docker run -it randyabernethy/thrift-book" to run the prebuilt image on Docker Hub (https://hub.docker.com/r/randyabernethy/thrift-book/).
[](https://microbadger.com/images/randyabernethy/thrift-book "Thrift Book Layers")
| 0 |
bekwam/examples-javafx-repos1 | Repository of JavaFX examples | null | # examples-fx-repos1
Repository of JavaFX examples
| 0 |
AutomateThePlanet/Design-Patterns-for-High-Quality-Automated-Tests-Java-Edition | Examples for Design Patterns for High-quality Automated Tests Java Edtion | null | ## Before You Get Started ##
You need to have prior experience in OOP programming language such as C#, Java, etc. I believe that you can get the book's ideas just from reading the presented code. However, it is recommended to download and run all of the solutions on your machine.
**As a bonus to the book, you can find video recordings with explanations for each chapter.** To get them, you can join for free the book's LinkedIn group. There you can find even more info about design patterns in automated testing and best practices or use it as an easy way to reach me. Before joining, you need to provide proof that you purchased the book. Just go to https://bit.ly/3eGTAUl
To build and execute the code, you will need a Java IDE, such as IntelliJ, Eclipse, or NetBeans. My preferred choice is IntelliJ. Also, it is recommended to install the latest version of the Java SDK. I show examples of new Java versions’ features through the book, so I encourage you to install the latest possible version. For software project management, I used Maven, and for unit testing framework TestNG, which means that depending on the IDE you picked, you will have to install the required plugins.
## Questions/Reader feedback/Errata ##
You can contact me at LinkedIn - [https://bit.ly/2NjWJ19](https://bit.ly/2NjWJ19) if you are having any problems with any aspect of the book, and I will do my best to address it.
## Foreword ##
Since I usually skip the Foreword chapters of other books, I will try to be short. My core belief is that to achieve high-quality test automation that brings value- you need to understand core programming concepts such as SOLID and the usage of design patterns. After you master them, the usual career transition is into more architecture roles, such as choosing the best possible approaches for solving particular test automation challenges. This is the essence of the book. No more “Hello world” examples but some serious literature about test automation practices!
P.S. After the first book's success, Design Patterns for High-Quality Automated Tests C# Edition, many people asked me when there will be a version for Java. This is why I started refreshing my Java knowledge and started writing. One year later, the book is here. More or less, the book explains the same concepts, but all code examples and specifics target the Java world. If you have read the C# edition, you can skip some of the more theoretical chapters or recheck them for a refresher.
You may notice that I have changed the sub-title for those of you who have purchased the C# version. I believe that the new sub-title communicates much better the ideas of the book. I won't bother you with lengthy introductions and discussions about what clean code means. There are whole books about the subject. But if I had to summarize what clean code means in one sentence, I would say: "Clean code is code that is easy to understand and easy to change." Easy to understand means the code is easy to read, whether that reader is the original author of the code or somebody else. Its meaning is clear, so it minimizes the need for guesswork and the possibility of misunderstandings. It is easy to understand on every level. Easy to change means the code is easy to extend and refactor, and it's easy to fix bugs in the codebase. This can be achieved if the person making the changes understands the code and feels confident that the code changes do not break any existing functionality. I will end the intro with two quotes by two famous authors Robert C. Martin and Michael Feathers.
"If you want your code to be easy to write, make it easy to read."
"Clean code always looks like it
### Who Is This Book For? ###
The book is not a getting started guide. If you don't have any prior programming experience in writing automated tests through WebDriver, this book won't be very useful to you. I believe it might be invaluable for the readers that have a couple of years of experience and whose job is to create/maintain test automation frameworks, or to write high-quality reliable automated tests.
The book is written in Java. However, I believe that you can use the approaches and practices in every OOP language. If you have a Python background, you will get everything you need, don't worry. However, if you are a C# developer, I would suggest checking the book's C# version.
Even if you don't get all the concepts from the first read, try to use and incorporate some of them. Later you can return and reread them. I believe with the accumulation of experience using high-quality practices- you will become a hard-core test automation ninja!
## What this book covers ##
### Chapter 1. Defining High-Quality Test Attributes ###
I think many terms are misunderstood and engineers are using them without fully understanding them, such as a library, framework, test framework. I believe this is the basic knowledge that all test engineers should have. The reader will learn about the top-quality attributes each test library should strive to have, which we will discuss in much more detail in the next chapters. Moreover, since we want to treat the test code as production one, we will talk about SOLID principles and how we can incorporate them into the development of the tests.
### Chapter 2. Optimizing and Refactoring Legacy Flaky Tests ###
We will discuss the Hermetic test pattern where each test should be isolated from others. Will learn about the Adapter design pattern where some of the unstable behaviours of WebDriver will be wrapped in a class and fixed. The same pattern will be used to improve the WebDriver API for locating elements and making it easier to use. Finally, we will talk about the random run order principle where the tests should be able to run no matter their order.
### Chapter 3. Strategies for Speeding-up the Tests ###
After the tests are stabilized and always passing the next step is to improve their speed. One of the approaches will be login to a website through cookies instead of using the UI. Next, the readers will see how to reuse the WebDriver browser instead of restarting it all the time earning more than 40% decrease in test execution time. We will talk about how to handle asynchronous requests and make test code parallelizable. Finally, we will mention the “Black Hole Proxy” approach isolating 3rd party services’ requests while further improving the speed of the automated tests.
### Chapter 4. Test Readability ###
Learn how to hide nitty-gritty low-level WebDriver API details in the so-called page objects, making the tests much more readable. Also, the readers will see how to create two different types of page objects depending on their needs. In the second part of the chapter, we will talk about coding standards - naming the variables and methods right, as well as placing the correct comments. At the end of the section, we will discuss various tools that can help us to enforce all these standards.
### Chapter 5. Enhancing the Test Maintainability and Reusability ###
We will talk about how to reuse more code across page objects by using the Template Method design pattern. Also, we will see a 3rd type of page object model where the assertions and elements will be used as properties instead of coming from base classes, which will introduce the benefits of the composition over the inheritance principle. In the second part of the chapter, we will discuss how to reuse common test workflows through the Facade design pattern. At the end of the section, we will talk about an enhanced version of the pattern where we can test different versions of the same web page (new and old).
### Chapter 6. API Usability ###
In this chapter, we will learn how to make the test library API easy to use, learn, and understand. First, we will talk about different approaches on how to use already developed page object models through the Singleton design pattern or Factory design pattern. After that, we will look at another approach called Fluent API or Chaining Methods. At the end of the section, we will discuss whether it is a good idea to expose the page objects elements to the users of your test library.
### Chapter 7. Building Extensibility in Your Test Library ###
If you create a well-designed library, most probably other teams can start using it too, so you need to be sure that your library is easily extensible. It should allow everyone to modify it and add new features to it without causing you to spend tons of time rewriting existing logic or making already written tests to fail. In this chapter, the reader will learn how to improve extensibility for finding elements by creating custom selectors through the Strategy design pattern. After that, we will investigate ways on how we can add additional behaviors to existing WebDriver actions via Observer design pattern or built-in EventFiringWebDriver.
### Chapter 8. Assessment System for Tests’ Architecture Design ###
In this chapter, we will look into an assessment system that can help you decide which design solution is better- for example, to choose one between 5 different versions of page objects. We will talk about the various criteria of the system and why they are essential. In the second part of the section, we will use the system to evaluate some of the design patterns we used previously and assign them ratings.
### Chapter 9. Benchmarking for Assessing Automated Test Components Performance ###
The evaluation of core quality attributes is not enough to finally decide which implementation is better or not. The test execution time should be a key component too. In this chapter, we will examine a library that can help us measure the performance of our automated tests’ components.
### Chapter 10. Test Data Preparation and Configuring Test Environments ###
One of the essential parts of each automated test is the test data which we use in it. It is important that the data is relevant and accessible. In the chapter, we will discuss how we can create such data through fixtures, APIs, DB layers or custom tools. Also, we will review how to set up the right way the environment in which the tests run.
### Appendix 1. Defining the Primary Problems that Test Automation Frameworks Solve ###
In the first appendix chapter, we will define the problems that the automation framework is trying to solve. To determine what is needed to deliver high-quality software, we need to understand what the issues are in the first place.
### Appendix 2. Most Exhaustive CSS Selectors Cheat Sheet ###
A big part of the job of writing maintainable and stable web automation is related to finding the proper element's selectors. Here will look into a comprehensive list of CSS selectors.
### Appendix 3. Most Exhaustive XPath Selectors Cheat Sheet ###
The other types of very useful locators are the XPath ones. Knowing them in detail can help you significantly improve the stability and the readability of your tests.
| 0 |
Sensebloom/OSCeleton-examples | A few processing sketches that read OSCeleton messages via OSC to demonstrate the message format. | null | OSCeleton-examples
=========
What is this?
-------------
Just a few simple demos we created to demonstrate how
to use [OSCeleton](https://github.com/Sensebloom/OSCeleton).
We have 2 processing sketches and 1 animata skeleton animation.
How do I use it?
----------------
Go get [OSCeleton](https://github.com/Sensebloom/OSCeleton), follow
the instructions there and run the OSCeleton executable.
For the processing examples you need to get and install the
[OscP5 library](http://www.sojamo.de/libraries/oscP5/).
For the stickmanetic processing sketch you additionally need to get
and install
[pbox2d](http://code.google.com/p/pbox2d/).
Run the skecthes ;)
We also have an animata demo. Run OSCeleton with the options you see
in the .bat file, open the animata animation and have fun!
OSC Message format
------------------
Check the README on
[OSCeleton](https://github.com/Sensebloom/OSCeleton)
and check the following method on the processing sketches:
void oscEvent(OscMessage msg)
Other
-----
### For death threats and other stuff, come join the fun in our [google group](http://groups.google.com/group/osceleton)!
Have fun!
| 0 |
MammatusTech/qbit-microservices-examples | Qbit Microservices Examples | null | [-qbit docs-](https://github.com/advantageous/qbit/wiki)

## Tutorials and examples
Qbit Microservices Examples
1. [QBit Microservice Hello World tutorial](https://github.com/MammatusTech/qbit-microservices-examples/wiki/Getting-started-with-QBit-Microservice-Lib)
2. [QBit Microservice Reactive programming tutorial](https://github.com/MammatusTech/qbit-microservices-examples/wiki/Reactor-tutorial--%7C-reactively-handling-async-calls-with-QBit-Reactive-Microservices)
Go see the wiki. All of the tutorials are there.
## Background information.
[Reactive Programming](http://rick-hightower.blogspot.com/2015/03/reactive-programming-service-discovery.html), [Java Microservices](http://rick-hightower.blogspot.com/2015/03/java-microservices-architecture.html), [Rick Hightower](http://www.linkedin.com/in/rickhigh)
[High-speed microservices consulting firm and authors of QBit with lots of experience with Vertx - Mammatus Technology](http://www.mammatustech.com/)
[Highly recommended consulting and training firm who specializes in microservices architecture and mobile development that are already very familiar with QBit and Vertx as well as iOS and Android - About Objects](http://www.aboutobjects.com/)
[Java Microservices Architecture](http://www.mammatustech.com/java-microservices-architecture)
[Microservice Service Discovery with Consul] (http://www.mammatustech.com/Microservice-Service-Discovery-with-Consul)
[Microservices Service Discovery Tutorial with Consul](http://www.mammatustech.com/consul-service-discovery-and-health-for-microservices-architecture-tutorial)
[Reactive Microservices]
(http://www.mammatustech.com/reactive-microservices)
[High Speed Microservices]
(http://www.mammatustech.com/high-speed-microservices)
[Java Microservices Consulting](http://www.mammatustech.com/java-microservices-consulting)
[Microservices Training](http://www.mammatustech.com/java-reactive-microservice-training)
| 0 |
gokhanyavas/Java-Programming-Examples-and-Notes | Java Programalama Ornek ve Notlari | null | # Java-Programalama-Ornek-ve-Notlari
Java Programalama üzerine başlangıç seviyesinden orta seviyeye kadar birçok konuyla ilgili örnekler bulunmaktadır. Örneklerin içinde konuyla ilgili detaylı bilgiler yer almaktadır.
gokhanyavas.com
| 0 |
nmcl/JavaSim | JavaSim simulation classes and examples | null | JavaSIM is an object-oriented simulation package based upon C++SIM and has been in use since 1997. It provides discrete event process-based simulation similar to SIMULA's simulation class and libraries. A complete list of the capabilities provided follows:
- The core of the system gives SIMULA-like simulation routines, random number generators, queueing algorithms and in C++SIM there are thread package interfaces, though for Java that's not necessary.
- Entity and set manipulation facilities similar to SIMSET.
- Classes allow "non-causal" events, such as interrupts, to be handled.
- Various routines for gathering statistics, such as histogram and variance classes.
The system also comes with complete examples and tests which illustrate many of the issues raised in using the simulation package.
Over the years C++SIM and JavaSim have been used by many commercial and academic organisations.
Prior to 2007 both C++SIM and JavaSim were freely available in source and binary from Newcastle University, under the University's own licence. However, in late 2007 Newcastle University decided that everything could be released into open source under LGPL. In 2015 the code was moved from Codehaus to github. All JIRAs from there were also recreated as github issues.
You can find details of the releases in the https://github.com/nmcl/JavaSim/releases section as well as binary downloads for some releases.
----
To build:
mvn compile
Run tests:
mvn test
Run tests and create installation:
mvn install
To run the examples check the README in that directory.
| 0 |
TechPrimers/stock-price-viewer-microservices-part1 | Spring Cloud services with 5 microservices - End to End Example | spring-boot spring-cloud spring-cloud-config spring-cloud-eureka spring-cloud-microservice spring-cloud-netflix spring-jpa spring-mvc | # Stock Viewer Example - Part 1
In this Part, we covered the below microservices:s
- `db-service` - For interactive with MySQL DB
- `stock-service` - For pulling Stock Price from YahooFinance API
- `eureka-service` - Service Registry for registering all microservices
## Architecture Diagram:

## Dockerized Version
Dockernized version of this project is available at in [master-docker](https://github.com/TechPrimers/stock-price-viewer-microservices-part1/tree/master-docker) branch
| 1 |
draptik/angulardemorestful | AngularJs intro: Focusing on the REST part with examples in java, nodejs and even dotnet ;-) This repo is from 2013 and is still being cloned... | null | angulardemorestful
==================
This is a sample project for some of my blog posts at [http://draptik.github.io](http://draptik.github.io).
## Git instructions for specific blog posts
- [http://draptik.github.io/blog/2013/07/13/angularjs-example-using-a-java-restful-web-service/](http://draptik.github.io/blog/2013/07/13/angularjs-example-using-a-java-restful-web-service/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step1
```
- [http://draptik.github.io/blog/2013/07/18/guice-in-java-web-application/](http://draptik.github.io/blog/2013/07/18/guice-in-java-web-application/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step2-guice
```
- [http://draptik.github.io/blog/2013/07/19/unit-testing-restful-services/](http://draptik.github.io/blog/2013/07/19/unit-testing-restful-services/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step3-backend-test
```
- [http://draptik.github.io/blog/2013/07/28/restful-crud-with-angularjs/](http://draptik.github.io/blog/2013/07/28/restful-crud-with-angularjs/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step4-angularjs-crud
```
- [http://draptik.github.io/blog/2013/08/19/angularjs-and-cors/](http://draptik.github.io/blog/2013/08/19/angularjs-and-cors/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step5-split-frontend-backend-cors
```
- [http://draptik.github.io/blog/2013/10/01/node-dot-js-backend-providing-rest/](http://draptik.github.io/blog/2013/10/01/node-dot-js-backend-providing-rest/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step6-nodejs-backend
```
- [http://draptik.github.io/blog/2014/07/18/dot-net-backend-providing-rest/](http://draptik.github.io/blog/2014/07/18/dot-net-backend-providing-rest/)
``` sh
git clone git@github.com:draptik/angulardemorestful.git
cd angulardemorestful
git checkout -f step7-aspnet-webapi-backend
```
| 0 |
allure-examples/testng-java-maven | Example of Allure Report usage with TestNG, Java and Maven | allure allure-report example java maven testng | # Allure Example
> Example of Allure Report usage with TestNG, Java and Maven
<!--<img src="https://allurereport.org/public/img/allure-report.svg" alt="Allure Report logo" style="float: right" />-->
- Learn more about Allure Report at https://allurereport.org
- 📚 [Documentation](https://allurereport.org/docs/) – discover official documentation for Allure Report
- ❓ [Questions and Support](https://github.com/orgs/allure-framework/discussions/categories/questions-support) – get help from the team and community
- 📢 [Official annoucements](https://github.com/orgs/allure-framework/discussions/categories/announcements) – be in touch with the latest updates
- 💬 [General Discussion ](https://github.com/orgs/allure-framework/discussions/categories/general-discussion) – engage in casual conversations, share insights and ideas with the community
---
The generated report is available here: [https://allure-examples.github.io/testng-java-maven](https://allure-examples.github.io/testng-java-maven/)
| 1 |
bentolor/java9to13 | Power Catchup – Java 9 to 13: HTML5 Presentation and Code Examples | null | null | 0 |
g0t4/jgsu-spring-petclinic | WIP update of spring-petclinic example used in my Jenkins Getting Started course on Pluralsight | null | null | 1 |
alexjlockwood/adp-path-morph-play-to-pause | Play-to-pause path morphing example | null | # material-pause-play-animation
View the animation on [YouTube](http://youtu.be/46zeFyiMBS4).

| 1 |
habuma/spring-boot-in-action-samples | Example code from Spring Boot in Action | null | # Spring Boot in Action Sample Code
This repository contains example code from Spring Boot in Action. In as much as is possible when writing compilable/verifiable code to be injected into a not-easily-verifiable work of prose, the code should be aligned with what was printed. There may be slight variations, however.
This code will be tagged with FIRST_PRINTING to indicate that the code aligns with the first printing of the first edition of the book. This allows for further evolution of the code after publication while still maintaining a reference back to the code as it aligns with the printed book.
Please feel free to offer suggestions in the form of pull requests if you see opportunity for improvement.
And I'd certainly appreciate it if you'd please purchase a copy of _Spring Boot in Action_ ([Amazon](http://www.amazon.com/Spring-Boot-Action-Craig-Walls/dp/1617292540) | [Manning](https://www.manning.com/books/spring-boot-in-action) | [Barnes & Noble](http://www.barnesandnoble.com/w/spring-boot-in-action-craig-walls/1121907935)).
| 1 |
frogermcs/GithubClient | Example of Github API client implemented on top of Dagger 2 DI framework. | null | # GithubClient
Example of Github API client implemented on top of Dagger 2 DI framework.
This code was created as an example for Dependency Injection with Dagger 2 series on my dev-blog:
- [Introdution to Dependency Injection](http://frogermcs.github.io/dependency-injection-with-dagger-2-introdution-to-di/)
- [Dagger 2 API](http://frogermcs.github.io/dependency-injection-with-dagger-2-the-api/)
- [Dagger 2 - custom scopes](http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/)
- [Dagger 2 - graph creation performance](http://frogermcs.github.io/dagger-graph-creation-performance/)
- [Dependency injection with Dagger 2 - Producers](http://frogermcs.github.io/dependency-injection-with-dagger-2-producers/)
- [Inject everything - ViewHolder and Dagger 2 (with Multibinding and AutoFactory example)](http://frogermcs.github.io/inject-everything-viewholder-and-dagger-2-example/)
This code was originally prepared for my presentation at Google I/O Extended 2015 in Tech Space Cracow. http://www.meetup.com/GDG-Krakow/events/221822600/
| 1 |
asaharland/beam-pipeline-examples | Apache Beam examples for running on Google Cloud Dataflow. | apache-beam aws-s3 google-cloud google-cloud-dataflow google-cloud-platform google-cloud-pubsub google-cloud-storage | # Apache Beam Examples
## About
This repository contains Apache Beam code examples for running on Google Cloud Dataflow. The following examples are contained in this repository:
* Streaming pipeline
* Reading CSVs from a Cloud Storage bucket and streaming the data into BigQuery
* Batch pipeline
* Reading from AWS S3 and writing to Google BigQuery
* Reading from Google Cloud Storage and writing to Google BigQuery
## Streaming pipeline
The goal of this example is to overcome the limitations of micro-batching with BigQuery.
This exapmle covers the following steps:
* Reads a number of CSV files from Cloud Storage
* Covers the CSV files into a Java Object
* Writes the rows into BigQuery
For more details on the limitations of micro-batching within BigQuery, check out my blog.
### Running the example
#### Setup & Configuration
* Ensure that you have billing enabled for your project
* Enable the following Google Cloud Platform APIs:
* Cloud Dataflow, Compute Engine, Stackdriver Logging, Google Cloud Storage, Google Cloud Storage JSON, BigQuery, Google Cloud Pub/Sub, Google Cloud Datastore, and Google Cloud Resource Manager APIs.
* Create a Google Cloud Storage bucket to stage your Cloud Dataflow code. Make sure you note the bucket name as you will need it later.
* Create a BigQuery dataset called finance. Keep note of the fully qualified dataset name which is in the format projectName:finance
* Upload the sample_1.csv and sample_2.csv to your Google Cloud Storage bucket
* Validate that the data has been loaded into BigQuery
#### Reading from Cloud Storage and writing to BigQuery
```
mvn compile exec:java \
-Dexec.mainClass=com.harland.example.batch.BigQueryImportPipeline \
-Dexec.args="--project=<GCP PROJECT ID> \
--bucketUrl=gs://<GCS BUCKET NAME> \
--bqTableName=<BIGQUERY TABLE e.g. project:finance.transactions> \
--runner=DataflowRunner \
--region=europe-west1 \
--stagingLocation=gs://<DATAFLOW BUCKET>/stage/ \
--tempLocation=gs://<DATAFLOW BUCKET>/temp/"
```
## Batch Pipeline
The goal of the example code is to calculate the total amount transferred for each user_id in the transfers_july.csv.
This is purely fictitious example that covers the following steps:
* Reads a CSV file from AWS S3
* Converts the CSV file into a Java Object
* Creates key, value pairs where user_id is the key and amount is the value
* Sums the amount for each user_id
* Writes the result to BigQuery
### Running the example
#### Setup & Configuration
* Ensure that you have billing enabled for your project
* Enable the following Google Cloud Platform APIs:
* Cloud Dataflow, Compute Engine, Stackdriver Logging, Google Cloud Storage, Google Cloud Storage JSON, BigQuery, Google Cloud Pub/Sub, Google Cloud Datastore, and Google Cloud Resource Manager APIs.
* Create a Google Cloud Storage bucket to stage your Cloud Dataflow code. Make sure you note the bucket name as you will need it later.
* Create a BigQuery dataset called finance. Keep note of the fully qualified dataset name which is in the format projectName:finance
* Upload the transfers_july.csv to your AWS S3/Google Cloud Storage bucket
#### Reading from AWS S3 and writing to BigQuery
```
mvn compile exec:java \
-Dexec.mainClass=com.harland.example.batch.BigQueryImportPipeline \
-Dexec.args="--project=<GCP PROJECT ID> \
--bucketUrl=s3://<S3 BUCKET NAME> \
--awsRegion=eu-west-1 \
--bqTableName=<BIGQUERY TABLE e.g. project:finance.transactions> \
--awsAccessKey=<YOUR ACCESS KEY> \
--awsSecretKey=<YOUR SECRET KEY> \
--runner=DataflowRunner \
--region=europe-west1 \
--stagingLocation=gs://<DATAFLOW BUCKET>/stage/ \
--tempLocation=gs://<DATAFLOW BUCKET>/temp/"
```
#### Reading from Google Cloud Storage and writing to BigQuery
```
mvn compile exec:java \
-Dexec.mainClass=com.harland.example.batch.BigQueryImportPipeline \
-Dexec.args="--project=<GCP PROJECT ID> \
--bucketUrl=gs://<GCS BUCKET NAME> \
--bqTableName=<BIGQUERY TABLE e.g. project:finance.transactions> \
--runner=DataflowRunner \
--region=europe-west1 \
--stagingLocation=gs://<DATAFLOW BUCKET>/stage/ \
--tempLocation=gs://<DATAFLOW BUCKET>/temp/"
```
## Built with
* Java 8
* Maven 3
* Apache Beam 2.5.0
| 0 |
CodelyTV/java-oop-examples | Object-Oriented Programming recap with Java examples | java java8 oop oop-examples oop-principles | # Object-Oriented Programming concepts recap with Java examples
## Concept
* Software development paradigm
* We should represent our system concepts using classes
* Classes deals with common behaviour to all of its different instances (objects):

* Objects have their own memory
* Object communicate between them sending and receiving messages
## Visibility and inheritance
### `public`, `protected`, and `private` visibility keywords
* When do you use each one?
* Guilt presumption
* Simplify our classes API (exposed methods) => Easier to understand, easier to be SRP compliant, avoid having to maintain public methods because others are coupled to them
* Question:
* Which would be the output of the `Child#visibilityTest` method?
* Solution: `ChildShould`. Possible answers:
```
"Child#privateMethod Child#protectedMethod Child#publicMethod" // a
"Parent#privateMethod Child#protectedMethod Child#publicMethod" // b
"Parent#privateMethod Parent#protectedMethod Child#publicMethod" // c
"Parent#privateMethod Child#protectedMethod Parent#publicMethod" // d
"Parent#privateMethod Parent#protectedMethod Parent#publicMethod" // e
// It doesn't compile // f
```
### `static` keyword
* What is it for?
* Question:
* Which would be the output for the following `getTotal` calls?
* Solution: `CounterShould`. Possible answers:
```java
Counter counterA = new Counter();
Counter counterB = new Counter();
Counter counterC = new Counter();
counterA.increaseTotal();
counterA.increaseTotal();
counterA.increaseTotal();
counterB.increaseTotal();
counterB.increaseTotal();
counterC.increaseTotal();
// a:
counterA.getTotal(); // 0
counterB.getTotal(); // 0
counterC.getTotal(): // 0
// b:
counterA.getTotal(); // 6
counterB.getTotal(); // 6
counterC.getTotal(): // 6
// c:
counterA.getTotal(); // 3
counterB.getTotal(); // 5
counterC.getTotal(): // 6
// c:
counterA.getTotal(); // 6
counterB.getTotal(); // 3
counterC.getTotal(): // 1
```
### `final` keyword
* What does it do in attributes?
* Does not allow to redefine them
* What does it do in methods?
* Does not allow to override them
* What does it do in classes?
* Does not allow to inherit from them
* When we should use it?
* Same reasoning as with the visibility keywords: Guilt presumption.
* Why: Make the next developer think twice before extending from it.
* Key concept: [Composition over Inheritance](https://medium.com/humans-create-software/composition-over-inheritance-cb6f88070205).
### `abstract` classes vs `interface`s
* What's the difference?
* Interfaces:
* Doesn't allow to implement method bodies. It only allow us to declare method contracts/headers. <- True until Java8
* They're great because as they have fewer capabilities, they are easier to read and understand without letting us mess up adding behaviour.
* A class can implement different interfaces.
* Abstract classes:
* Allow to implement method bodies.
* A class can only extend from one abstract class.
* When we should use `abstract` classes?
* Opinion: Almost never. Just exceptional cases. We should have a very big reason to do so 🙂
* When we should use `interfaces`?
* Opinion: In order to decouple from infrastructure* stuff.
* *Infrastructure: behaviour related to a third party library or component (Postgres DB, AWS SDK, Slack SDK, MailChimp API…)
* Usage example:
```java
interface ProductRecommender
{
Recommendations findFor(ProductId productId);
}
final class BlueknowProductRecommender implements ProductRecommender
{
@Override
public Recommendations findFor(ProductId productId) {
// Call to the Blueknow service API
// Parse the JSON response into a `Recommendations` class instance
return recommendations;
}
}
```
Example:
* Context:
* We have a Builder system in order to build our applications
* We want to notify the development team once the build is ready to be deployed
* We're testing different messaging apps such as Slack and HipChat
* In order to do not miss our notifications, we want to be notified through the `#dev-notifications` Slack channel, and through the `dev-notifications@codely.tv` mailing list
* Questions:
* How would you model these different classes and their interactions?
| 0 |
ralscha/spring4ws-demos | WebSocket examples with Spring 4 | java spring spring-boot spring-framework spring-mvc websocket | Sample applications with the Spring Framework 5 Websocket/SockJS/STOMP support.
| 0 |
mythz/java-linq-examples | C#'s 101 LINQ Samples translated to Java | null | 101 C# LINQ Samples in Java
===========================
Port of the [C# 101 LINQ Samples](http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b) rewritten into Andriod-compatible [Java 1.7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html).
Compare Java to other LINQ examples written in:
- [Kotlin](https://github.com/mythz/kotlin-linq-examples)
- [Groovy](https://gitlab.com/svermeulen/groovy-linq-samples)
- [Swift](https://github.com/mythz/swift-linq-examples)
- [Clojure](https://github.com/mythz/clojure-linq-examples)
- [Dart](https://github.com/mythz/dart-linq-examples)
- [Elixir](https://github.com/omnibs/elixir-linq-examples)
- [Python](https://github.com/rogerwcpt/python-linq-samples)
- [#Script code](https://sharpscript.net/linq/restriction-operators?lang=code)
- [#Script lisp](https://sharpscript.net/linq/restriction-operators?lang=lisp)
## [Call .NET Web Services from Java](http://docs.servicestack.net/java-add-servicestack-reference)
If you're looking for an effortles typed API for consuming .NET Web Services in pure Java or Android Java Apps checkout ServiceStack's [Java Add ServiceStack Reference](https://github.com/ServiceStack/ServiceStack/wiki/Java-Add-ServiceStack-Reference).
### Running the examples
Each of the LINQ Examples can be run from the included Android App with its results logged to the screen:

Run the included [Android Studio project](https://github.com/mythz/java-linq-examples/tree/master/src) to execute all the examples. You can also choose to only run specific examples by commenting out any of the sections you're not interested in [MainActivity.java](https://github.com/mythz/java-linq-examples/blob/432dfeb0ea3c95ecdd8e007886a77d1508d6f312/src/app/src/main/java/servicestack/net/javalinqexamples/MainActivity.java#L54-L67).
A copy of the LINQ examples output is also available in [linq-log.txt](https://raw.githubusercontent.com/mythz/java-linq-examples/master/linq-log.txt).
### Contents
The samples below mirrors the C# LINQ samples layout with the names of the top-level Java methods matching their corresponding C# examples.
#### [LINQ - Restriction Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Restrictions.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Restriction-Operators-b15d29ca)
#### [LINQ - Projection Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Projections.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-to-DataSets-09787825)
#### [LINQ - Partitioning Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Partitioning.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Partitioning-Operators-c68aaccc)
#### [LINQ - Ordering Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Ordering.java) / [MSDN C#](http://code.msdn.microsoft.com/SQL-Ordering-Operators-050af19e)
#### [LINQ - Grouping Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Grouping.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-to-DataSets-Grouping-c62703ea)
#### [LINQ - Set Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/SetOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Set-Operators-374f34fe)
#### [LINQ - Conversion Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Conversion.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Conversion-Operators-e4e59714)
#### [LINQ - Element Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/ElementOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Element-Operators-0f3f12ce)
#### [LINQ - Generation Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/GenerationOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Generation-Operators-8a3fbff7)
#### [LINQ - Quantifiers](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/Quantifiers.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Quantifiers-f00e7e3e)
#### [LINQ - Aggregate Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/AggregateOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Aggregate-Operators-c51b3869)
#### [LINQ - Miscellaneous Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/MiscOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Miscellaneous-6b72bb2a)
#### [LINQ - Query Execution](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/QueryExecution.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Query-Execution-ce0d3b95)
#### [LINQ - Join Operators](https://github.com/mythz/java-linq-examples/blob/master/src/app/src/main/java/servicestack/net/javalinqexamples/JoinOperators.java) / [MSDN C#](http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9)
## Java Functional Utils
Unlike many modern languages supporting a functional-style, Java doesn't have any LINQ-like utils built-in by default. It's also not very extensible which combined with the lack of proper Type Inference, Type Erasure and Closures in Java 1.7 makes the equivalent Java source code particularly more verbose.
To improve the development experience in Java, we've added common functional utils to simplify programming in a functional style inside [ServiceStack's Java and Android Client Library](https://github.com/ServiceStack/ServiceStack/wiki/Java-Add-ServiceStack-Reference): **net.servicestack:android**.
### Install
To include it in your Android Studio project, add it to your **build.gradle** dependency, e.g:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'net.servicestack:android:1.0.24'
}
Pure Java projects should add the **net.servicestack:client** dependency instead:
dependencies {
compile 'net.servicestack:client:1.0.24'
}
Alternatively this library is also automatically added when Adding a Typed Remote Service Reference with ServiceStack IDE Plugins for [Intellij IDEA](https://github.com/ServiceStack/ServiceStack/wiki/Java-Add-ServiceStack-Reference#servicestack-idea-android-studio-plugin
) and [Eclipse Maven projects](https://github.com/ServiceStack/ServiceStack.Java/tree/master/src/ServiceStackEclipse#eclipse-integration-with-servicestack).
### Usage
Once the dependency is added you can add a static import to access [all the functional utils](https://github.com/ServiceStack/ServiceStack.Java/blob/master/src/AndroidClient/client/src/main/java/net/servicestack/func/Func.java) used in the LINQ examples below:
```java
import static net.servicestack.func.Func.*;
```
## Side-by-side - C# LINQ vs Java
For a side-by-side comparison, the original **C#** source code is displayed above the equivalent **Java** translation.
- The **Output** shows the logging output of running the **Java** Android App.
- Outputs ending with `...` illustrates only a partial response is displayed.
- The C# ObjectDumper util used is downloadable from MSDN - [ObjectDumper.zip](http://code.msdn.microsoft.com/Visual-Studio-2008-C-d295cdba/file/46086/1/ObjectDumper.zip)
The Java LINQ Examples are limited to Java 1.7 so they're available on Android.
LINQ - Restriction Operators
----------------------------
### linq1: Where - Simple 1
```csharp
//c#
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
}
```
```java
//java
public void linq1(){
int[] numbers = new int[]{ 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> lowNums = filter(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n < 5;
}
});
Log.d("Numbers < 5:");
for (int n : lowNums){
Log.d(n);
}
}
```
#### Output
Numbers < 5:
4
1
3
2
0
### linq2: Where - Simple 2
```csharp
//c#
public void Linq2()
{
List<Product> products = GetProductList();
var soldOutProducts =
from p in products
where p.UnitsInStock == 0
select p;
Console.WriteLine("Sold out products:");
foreach (var product in soldOutProducts)
{
Console.WriteLine("{0} is sold out!", product.ProductName);
}
}
```
```java
//java
public void linq2(){
List<Product> products = getProductList();
List<Product> soldOutProducts = filter(products, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitsInStock == 0;
}
});
Log.d("Sold out products:");
for (Product p : soldOutProducts) {
Log.d(p.productName + " is sold out!");
}
}
```
#### Output
Sold out products:
Chef Anton's Gumbo Mix is sold out!
Alice Mutton is sold out!
Thüringer Rostbratwurst is sold out!
Gorgonzola Telino is sold out!
Perth Pasties is sold out!
### linq3: Where - Simple 3
```csharp
//c#
public void Linq3()
{
List<Product> products = GetProductList();
var expensiveInStockProducts =
from p in products
where p.UnitsInStock > 0 && p.UnitPrice > 3.00M
select p;
Console.WriteLine("In-stock products that cost more than 3.00:");
foreach (var product in expensiveInStockProducts)
{
Console.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName);
}
}
```
```java
//java
public void linq3(){
List<Product> products = getProductList();
ArrayList<Product> expensiveInStockProducts = filter(products, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitsInStock > 0 && p.unitPrice > 3.00;
}
});
Log.d("In-stock products that cost more than 3.00:");
for (Product p : expensiveInStockProducts) {
Log.d(p.productName + " is in stock and costs more than 3.00.");
}
}
```
#### Output
In-stock products that cost more than 3.00:
Chai is in stock and costs more than 3.00.
Chang is in stock and costs more than 3.00.
Aniseed Syrup is in stock and costs more than 3.00.
...
### linq4: Where - Drilldown
```csharp
//c#
public void Linq4()
{
List<Customer> customers = GetCustomerList();
var waCustomers =
from c in customers
where c.Region == "WA"
select c;
Console.WriteLine("Customers from Washington and their orders:");
foreach (var customer in waCustomers)
{
Console.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName);
foreach (var order in customer.Orders)
{
Console.WriteLine(" Order {0}: {1}", order.OrderID, order.OrderDate);
}
}
}
```
```java
//java
public void linq4(){
List<Customer> customers = getCustomerList();
List<Customer> waCustomers = filter(customers, new Predicate<Customer>() {
@Override
public boolean apply(Customer c) {
return "WA".equals(c.region);
}
});
Log.d("Customers from Washington and their orders:");
for (Customer c : waCustomers){
Log.d("Customer " + c.customerId + " " + c.companyName);
for (Order o : c.orders){
Log.d(" Order " + o.orderId + ": " + dateFmt(o.orderDate));
}
}
}
```
#### Output
Customers from Washington and their orders:
Customer LAZYK Lazy K Kountry Store
Order 10482: 1997/03/21
Order 10545: 1997/05/22
Customer TRAIH Trail's Head Gourmet Provisioners
Order 10574: 1997/06/19
Order 10577: 1997/06/23
Order 10822: 1998/01/08
...
### linq5: Where - Indexed
```csharp
//c#
public void Linq5()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var shortDigits = digits.Where((digit, index) => digit.Length < index);
Console.WriteLine("Short digits:");
foreach (var d in shortDigits)
{
Console.WriteLine("The word {0} is shorter than its value.", d);
}
}
```
```java
//java
public void linq5(){
String[] digits = new String[]{ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<String> shortDigits = filteri(digits, new PredicateIndex<String>() {
@Override
public boolean apply(String s, int i) {
return s.length() < i;
}
});
Log.d("Short digits:");
for (String d : shortDigits){
Log.d("The word " + d + " is shorter than its value.");
}
}
```
#### Output
Short digits:
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.
LINQ - Projection Operators
---------------------------
### linq6: Select - Simple 1
```csharp
//c#
public void Linq6()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsPlusOne =
from n in numbers
select n + 1;
Console.WriteLine("Numbers + 1:");
foreach (var i in numsPlusOne)
{
Console.WriteLine(i);
}
}
```
```java
//java
public void linq06(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> numsPlusOne = map(toList(numbers), new Function<Integer, Integer>() {
@Override
public Integer apply(Integer i) {
return i + 1;
}
});
Log.d("Numbers + 1:");
for (Integer n : numsPlusOne){
Log.d(n);
}
}
```
#### Output
Numbers + 1:
6
5
2
4
10
9
7
8
3
1
### linq7: Select - Simple 2
```csharp
//c#
public void Linq7()
{
List<Product> products = GetProductList();
var productNames =
from p in products
select p.ProductName;
Console.WriteLine("Product Names:");
foreach (var productName in productNames)
{
Console.WriteLine(productName);
}
}
```
```java
//java
public void linq07(){
List<Product> products = getProductList();
List<String> productNames = map(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.productName;
}
});
Log.d("Product Names:");
for (String productName : productNames){
Log.d(productName);
}
}
```
#### Output
Product Names:
Chai
Chang
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
...
### linq8: Select - Transformation
```csharp
//c#
public void Linq8()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var textNums =
from n in numbers
select strings[n];
Console.WriteLine("Number strings:");
foreach (var s in textNums)
{
Console.WriteLine(s);
}
}
```
```java
//java
public void linq08(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
final String[] strings = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<String> textNums = map(toList(numbers), new Function<Integer, String>() {
@Override
public String apply(Integer n) {
return strings[n];
}
});
Log.d("Number strings:");
for (String s : textNums){
Log.d(s);
}
}
```
#### Output
Number strings:
five
four
one
three
nine
eight
six
seven
two
zero
### linq9: Select - Anonymous Types 1
```csharp
//c#
public void Linq9()
{
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
var upperLowerWords =
from w in words
select new { Upper = w.ToUpper(), Lower = w.ToLower() };
foreach (var ul in upperLowerWords)
{
Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
}
}
```
```java
//java
public void linq09(){
String[] words = new String[]{ "aPPLE", "BlUeBeRrY", "cHeRry" };
List<Tuple<String,String>> upperLowerWords = map(words, new Function<String, Tuple<String,String>>(){
@Override
public Tuple<String,String> apply(String w) {
return new Tuple<>(w.toUpperCase(), w.toLowerCase());
}
});
for (Tuple<String,String> ul : upperLowerWords){
Log.d("Uppercase: " + ul.A + ", Lowercase: " + ul.B);
}
}
```
#### Output
Uppercase: APPLE, Lowercase: apple
Uppercase: BLUEBERRY, Lowercase: blueberry
Uppercase: CHERRY, Lowercase: cherry
### linq10: Select - Anonymous Types 2
```csharp
//c#
public void Linq10()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var digitOddEvens =
from n in numbers
select new { Digit = strings[n], Even = (n % 2 == 0) };
foreach (var d in digitOddEvens)
{
Console.WriteLine("The digit {0} is {1}.", d.Digit, d.Even ? "even" : "odd");
}
}
```
```java
//java
public void linq10(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
final String[] strings = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<Tuple<String, Boolean>> digitOddEvens = map(toList(numbers), new Function<Integer, Tuple<String, Boolean>>() {
@Override
public Tuple<String, Boolean> apply(Integer n) {
return new Tuple<>(strings[n], n % 2 == 0);
}
});
for (Tuple<String,Boolean> d : digitOddEvens){
Log.d("The digit " + d.A + " is " + (d.B ? "even" : "odd") + ".");
}
}
```
#### Output
The digit five is odd.
The digit four is even.
The digit one is odd.
The digit three is odd.
The digit nine is odd.
The digit eight is even.
The digit six is even.
The digit seven is odd.
The digit two is even.
The digit zero is even.
### linq11: Select - Anonymous Types 3
```csharp
//c#
public void Linq11()
{
List<Product> products = GetProductList();
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
Console.WriteLine("Product Info:");
foreach (var productInfo in productInfos)
{
Console.WriteLine("{0} is in the category {1} and costs {2} per unit.", productInfo.ProductName, productInfo.Category, productInfo.Price);
}
}
```
```java
//java
public void linq11(){
List<Product> products = getProductList();
List<Tuple3<String,String,Double>> productInfos = map(products, new Function<Product, Tuple3<String, String, Double>>() {
@Override
public Tuple3<String, String, Double> apply(Product p) {
return new Tuple3<>(p.productName, p.category, p.unitPrice);
}
});
Log.d("Product Info:");
for (Tuple3<String,String,Double> productInfo : productInfos){
Log.d(productInfo.A + " is in the category " + productInfo.B + " and costs " + productInfo.C + " per unit.");
}
}
```
#### Output
Product Info:
Chai is in the category Beverages and costs 18.0 per unit.
Chang is in the category Beverages and costs 19.0 per unit.
Aniseed Syrup is in the category Condiments and costs 10.0 per unit.
...
### linq12: Select - Indexed
```csharp
//c#
public void Linq12()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numsInPlace = numbers.Select((num, index) => new { Num = num, InPlace = (num == index) });
Console.WriteLine("Number: In-place?");
foreach (var n in numsInPlace)
{
Console.WriteLine("{0}: {1}", n.Num, n.InPlace);
}
}
```
```java
//java
public void linq12(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Tuple<Integer,Boolean>> numsInPlace = mapi(toList(numbers), new FunctionIndex<Integer, Tuple<Integer, Boolean>>() {
@Override
public Tuple<Integer, Boolean> apply(Integer num, int index) {
return new Tuple<>(num, num == index);
}
});
Log.d("Number: In-place?");
for (Tuple<Integer,Boolean> n : numsInPlace){
Log.d(n.A + ": " + n.B);
}
}
```
#### Output
Number: In-place?
5: false
4: false
1: false
3: true
9: false
8: false
6: true
7: true
2: false
0: false
### linq13: Select - Filtered
```csharp
//c#
public void Linq13()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var lowNums =
from n in numbers
where n < 5
select digits[n];
Console.WriteLine("Numbers < 5:");
foreach (var num in lowNums)
{
Console.WriteLine(num);
}
}
```
```java
//java
public void linq13(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
final String[] digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<String> lowNums = map(
filter(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n < 5;
}
}),
new Function<Integer, String>() {
@Override
public String apply(Integer n){
return digits[n];
}
});
Log.d("Numbers < 5:");
for (String num : lowNums){
Log.d(num);
}
}
```
#### Output
Numbers < 5:
four
one
three
two
zero
### linq14: SelectMany - Compound from 1
```csharp
//c#
public void Linq14()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var pairs =
from a in numbersA
from b in numbersB
where a < b
select new { a, b };
Console.WriteLine("Pairs where a < b:");
foreach (var pair in pairs)
{
Console.WriteLine("{0} is less than {1}", pair.a, pair.b);
}
}
```
```java
//java
public void linq14(){
int[] numbersA = new int[] { 0, 2, 4, 5, 6, 8, 9 };
final int[] numbersB = new int[] { 1, 3, 5, 7, 8 };
List<Tuple<Integer,Integer>> pairs = expand(
map(toList(numbersA), new Function<Integer,List<Tuple<Integer,Integer>>>() {
@Override
public List<Tuple<Integer,Integer>> apply(final Integer a) {
return map(filter(toList(numbersB), new Predicate<Integer>() {
@Override
public boolean apply(Integer b) {
return a < b;
}
}), new Function<Integer, Tuple<Integer,Integer>>() {
@Override
public Tuple<Integer, Integer> apply(Integer b) {
return new Tuple<>(a,b);
}
});
}
})
);
Log.d("Pairs where a < b:");
for (Tuple<Integer,Integer> pair : pairs){
Log.d(pair.A + " is less than " + pair.B);
}
}
```
#### Output
Pairs where a < b:
0 is less than 1
0 is less than 3
0 is less than 5
0 is less than 7
0 is less than 8
2 is less than 3
2 is less than 5
2 is less than 7
2 is less than 8
4 is less than 5
4 is less than 7
4 is less than 8
5 is less than 7
5 is less than 8
6 is less than 7
6 is less than 8
### linq15: SelectMany - Compound from 2
```csharp
//c#
public void Linq15()
{
List<Customer> customers = GetCustomerList();
var orders =
from c in customers
from o in c.Orders
where o.Total < 500.00M
select new { c.CustomerID, o.OrderID, o.Total };
ObjectDumper.Write(orders);
}
```
```java
//java
public void linq15(){
List<Customer> customers = getCustomerList();
List<Tuple3<String, Integer, Double>> orders = expand(
map(customers, new Function<Customer, List<Tuple3<String, Integer, Double>>>() {
@Override
public List<Tuple3<String, Integer, Double>> apply(final Customer c) {
return map(filter(c.orders, new Predicate<Order>() {
@Override
public boolean apply(Order o) {
return o.total < 500;
}
}), new Function<Order, Tuple3<String, Integer, Double>>() {
@Override
public Tuple3<String, Integer, Double> apply(Order o) {
return new Tuple3<>(c.customerId, o.orderId, o.total);
}
});
}
})
);
for (Tuple3<?,?,?> o : orders){
Log.d(o);
}
}
```
#### Output
(ALFKI, 10702, 330.0)
(ALFKI, 10952, 471.2)
(ANATR, 10308, 88.8)
(ANATR, 10625, 479.75)
...
### linq16: SelectMany - Compound from 3
```csharp
//c#
public void Linq16()
{
List<Customer> customers = GetCustomerList();
var orders =
from c in customers
from o in c.Orders
where o.OrderDate >= new DateTime(1998, 1, 1)
select new { c.CustomerID, o.OrderID, o.OrderDate };
ObjectDumper.Write(orders);
}
```
```java
//java
public void linq16(){
List<Customer> customers = getCustomerList();
final Date date = new Date(98, 0, 1); //= 1998-01-01
List<Tuple3<String, Integer, Date>> orders = expand(
map(customers, new Function<Customer, List<Tuple3<String, Integer, Date>>>() {
@Override
public List<Tuple3<String, Integer, Date>> apply(final Customer c) {
return map(filter(c.orders, new Predicate<Order>() {
@Override
public boolean apply(Order o) {
return o.orderDate.after(date);
}
}), new Function<Order, Tuple3<String, Integer, Date>>() {
@Override
public Tuple3<String, Integer, Date> apply(Order o) {
return new Tuple3<>(c.customerId, o.orderId, o.orderDate);
}
});
}
})
);
for (Tuple3<?,?,?> o : orders){
Log.d(o);
}
}
```
#### Output
(ALFKI, 10835, Thu Jan 15 00:00:00 GMT+08:00 1998)
(ALFKI, 10952, Mon Mar 16 00:00:00 GMT+08:00 1998)
(ALFKI, 11011, Thu Apr 09 00:00:00 GMT+08:00 1998)
(ANATR, 10926, Wed Mar 04 00:00:00 GMT+08:00 1998)
(ANTON, 10856, Wed Jan 28 00:00:00 GMT+08:00 1998)
...
### linq17: SelectMany - from Assignment
```csharp
//c#
public void Linq17()
{
List<Customer> customers = GetCustomerList();
var orders =
from c in customers
from o in c.Orders
where o.Total >= 2000.0M
select new { c.CustomerID, o.OrderID, o.Total };
ObjectDumper.Write(orders);
}
```
```java
//java
public void linq17(){
List<Customer> customers = getCustomerList();
List<Tuple3<String, Integer, Double>> orders = expand(
map(customers, new Function<Customer, List<Tuple3<String, Integer, Double>>>() {
@Override
public List<Tuple3<String, Integer, Double>> apply(final Customer c) {
return map(filter(c.orders, new Predicate<Order>() {
@Override
public boolean apply(Order o) {
return o.total >= 2000;
}
}), new Function<Order, Tuple3<String, Integer, Double>>() {
@Override
public Tuple3<String, Integer, Double> apply(Order o) {
return new Tuple3<>(c.customerId, o.orderId, o.total);
}
});
}
})
);
for (Tuple3<?,?,?> o : orders){
Log.d(o);
}
}
```
#### Output
(ANTON, 10573, 2082.0)
(AROUT, 10558, 2142.9)
(AROUT, 10953, 4441.25)
(BERGS, 10384, 2222.4)
(BERGS, 10524, 3192.65)
...
### linq18: SelectMany - Multiple from
```csharp
//c#
public void Linq18()
{
List<Customer> customers = GetCustomerList();
DateTime cutoffDate = new DateTime(1997, 1, 1);
var orders =
from c in customers
where c.Region == "WA"
from o in c.Orders
where o.OrderDate >= cutoffDate
select new { c.CustomerID, o.OrderID };
ObjectDumper.Write(orders);
}
```
```java
//java
public void linq18(){
List<Customer> customers = getCustomerList();
final Date cutoffDate = new Date(97,0,1); //1997-01-01
List<Tuple<String, Integer>> orders = expand(
map(
filter(customers, new Predicate<Customer>() {
@Override
public boolean apply(Customer c) {
return "WA".equals(c.region);
}
})
, new Function<Customer, List<Tuple<String, Integer>>>() {
@Override
public List<Tuple<String, Integer>> apply(final Customer c) {
return map(filter(c.orders, new Predicate<Order>() {
@Override
public boolean apply(Order o) {
return o.orderDate.after(cutoffDate);
}
}), new Function<Order, Tuple<String, Integer>>() {
@Override
public Tuple<String, Integer> apply(Order o) {
return new Tuple<>(c.customerId, o.orderId);
}
});
}
})
);
for (Tuple<?,?> o : orders){
Log.d(o);
}
}
```
#### Output
(LAZYK, 10482)
(LAZYK, 10545)
(TRAIH, 10574)
(TRAIH, 10577)
(TRAIH, 10822)
(WHITC, 10469)
(WHITC, 10483)
(WHITC, 10504)
(WHITC, 10596)
(WHITC, 10693)
(WHITC, 10696)
(WHITC, 10723)
(WHITC, 10740)
(WHITC, 10861)
(WHITC, 10904)
(WHITC, 11032)
(WHITC, 11066)
### linq19: SelectMany - Indexed
```csharp
//c#
public void Linq19()
{
List<Customer> customers = GetCustomerList();
var customerOrders =
customers.SelectMany(
(cust, custIndex) =>
cust.Orders.Select(o => "Customer #" + (custIndex + 1) +
" has an order with OrderID " + o.OrderID));
ObjectDumper.Write(customerOrders);
}
```
```java
//java
public void linq19(){
List<Customer> customers = getCustomerList();
List<String> customerOrders = expand(
mapi(customers, new FunctionIndex<Customer, List<String>>() {
@Override
public List<String> apply(Customer cust, final int custIndex) {
return map(cust.orders, new Function<Order, String>() {
@Override
public String apply(Order o) {
return "Customer #" + (custIndex + 1) + " has an order with OrderID " + o.orderId;
}
});
}
})
);
for (String x : customerOrders){
Log.d(x);
}
}
```
#### Output
Customer #1 has an order with OrderID 10643
Customer #1 has an order with OrderID 10692
Customer #1 has an order with OrderID 10702
Customer #1 has an order with OrderID 10835
Customer #1 has an order with OrderID 10952
Customer #1 has an order with OrderID 11011
Customer #2 has an order with OrderID 10308
Customer #2 has an order with OrderID 10625
Customer #2 has an order with OrderID 10759
Customer #2 has an order with OrderID 10926
...
LINQ - Partitioning Operators
-----------------------------
### linq20: Take - Simple
```csharp
//c#
public void Linq20()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var first3Numbers = numbers.Take(3);
Console.WriteLine("First 3 numbers:");
foreach (var n in first3Numbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq20() {
int[] numbers = new int[]{5, 4, 1, 3, 9, 8, 6, 7, 2, 0};
List<Integer> first3Numbers = take(toList(numbers), 3);
Log.d("First 3 numbers:");
for (Integer n : first3Numbers) {
Log.d(n);
}
}
```
#### Output
First 3 numbers:
5
4
1
### linq21: Take - Nested
```csharp
//c#
public void Linq21()
{
List<Customer> customers = GetCustomerList();
var first3WAOrders = (
from c in customers
from o in c.Orders
where c.Region == "WA"
select new { c.CustomerID, o.OrderID, o.OrderDate })
.Take(3);
Console.WriteLine("First 3 orders in WA:");
foreach (var order in first3WAOrders)
{
ObjectDumper.Write(order);
}
}
```
```java
//java
public void linq21() {
List<Customer> customers = getCustomerList();
List<Tuple3<String, Integer, Date>> first3WAOrders =
take(
expand(
map(filter(customers, new Predicate<Customer>() {
@Override
public boolean apply(Customer c) {
return "WA".equals(c.region);
}
}),
new Function<Customer, List<Tuple3<String, Integer, Date>>>() {
@Override
public List<Tuple3<String, Integer, Date>> apply(final Customer c) {
return map(c.orders, new Function<Order, Tuple3<String, Integer, Date>>() {
@Override
public Tuple3<String, Integer, Date> apply(Order o) {
return new Tuple3<>(c.customerId, o.orderId, o.orderDate);
}
});
}
})
),
3);
Log.d("First 3 orders in WA:");
for (Tuple3<?, ?, ?> o : first3WAOrders) {
Log.d(o);
}
}
```
#### Output
First 3 orders in WA:
(LAZYK, 10482, Fri Mar 21 00:00:00 GMT+08:00 1997)
(LAZYK, 10545, Thu May 22 00:00:00 GMT+08:00 1997)
(TRAIH, 10574, Thu Jun 19 00:00:00 GMT+08:00 1997)
### linq22: Skip - Simple
```csharp
//c#
public void Linq22()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst4Numbers = numbers.Skip(4);
Console.WriteLine("All but first 4 numbers:");
foreach (var n in allButFirst4Numbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq22() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> allButFirst4Numbers = skip(toList(numbers), 4);
Log.d("All but first 4 numbers:");
for (Integer n : allButFirst4Numbers){
Log.d(n);
}
}
```
#### Output
All but first 4 numbers:
9
8
6
7
2
0
### linq23: Skip - Nested
```csharp
//c#
public void Linq23()
{
List<Customer> customers = GetCustomerList();
var waOrders =
from c in customers
from o in c.Orders
where c.Region == "WA"
select new { c.CustomerID, o.OrderID, o.OrderDate };
var allButFirst2Orders = waOrders.Skip(2);
Console.WriteLine("All but first 2 orders in WA:");
foreach (var order in allButFirst2Orders)
{
ObjectDumper.Write(order);
}
}
```
```java
//java
public void linq23() {
List<Customer> customers = getCustomerList();
List<Tuple3<String, Integer, Date>> allButFirst2Orders =
skip(
expand(
map(filter(customers, new Predicate<Customer>() {
@Override
public boolean apply(Customer c) {
return "WA".equals(c.region);
}
}),
new Function<Customer, List<Tuple3<String, Integer, Date>>>() {
@Override
public List<Tuple3<String, Integer, Date>> apply(final Customer c) {
return map(c.orders, new Function<Order, Tuple3<String, Integer, Date>>() {
@Override
public Tuple3<String, Integer, Date> apply(Order o) {
return new Tuple3<>(c.customerId, o.orderId, o.orderDate);
}
});
}
})
),
2);
Log.d("All but first 2 orders in WA:");
for (Tuple3<?, ?, ?> o : allButFirst2Orders) {
Log.d(o);
}
}
```
#### Output
All but first 2 orders in WA:
(TRAIH, 10574, Thu Jun 19 00:00:00 GMT+08:00 1997)
(TRAIH, 10577, Mon Jun 23 00:00:00 GMT+08:00 1997)
(TRAIH, 10822, Thu Jan 08 00:00:00 GMT+08:00 1998)
(WHITC, 10269, Wed Jul 31 00:00:00 GMT+08:00 1996)
(WHITC, 10344, Fri Nov 01 00:00:00 GMT+08:00 1996)
(WHITC, 10469, Mon Mar 10 00:00:00 GMT+08:00 1997)
(WHITC, 10483, Mon Mar 24 00:00:00 GMT+08:00 1997)
(WHITC, 10504, Fri Apr 11 00:00:00 GMT+08:00 1997)
(WHITC, 10596, Fri Jul 11 00:00:00 GMT+08:00 1997)
(WHITC, 10693, Mon Oct 06 00:00:00 GMT+08:00 1997)
(WHITC, 10696, Wed Oct 08 00:00:00 GMT+08:00 1997)
(WHITC, 10723, Thu Oct 30 00:00:00 GMT+08:00 1997)
(WHITC, 10740, Thu Nov 13 00:00:00 GMT+08:00 1997)
(WHITC, 10861, Fri Jan 30 00:00:00 GMT+08:00 1998)
(WHITC, 10904, Tue Feb 24 00:00:00 GMT+08:00 1998)
(WHITC, 11032, Fri Apr 17 00:00:00 GMT+08:00 1998)
(WHITC, 11066, Fri May 01 00:00:00 GMT+08:00 1998)
### linq24: TakeWhile - Simple
```csharp
//c#
public void Linq24()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);
Console.WriteLine("First numbers less than 6:");
foreach (var n in firstNumbersLessThan6)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq24() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> firstNumbersLessThan6 = takeWhile(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n < 6;
}
});
Log.d("First numbers less than 6:");
for (Integer n : firstNumbersLessThan6){
Log.d(n);
}
}
```
#### Output
First numbers less than 6:
5
4
1
3
### linq25: TakeWhile - Indexed
```csharp
//c#
public void Linq25()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var firstSmallNumbers = numbers.TakeWhile((n, index) => n >= index);
Console.WriteLine("First numbers not less than their position:");
foreach (var n in firstSmallNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq25() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> firstSmallNumbers = takeWhilei(toList(numbers), new PredicateIndex<Integer>() {
@Override
public boolean apply(Integer n, int index) {
return n >= index;
}
});
Log.d("First numbers not less than their position:");
for (Integer n : firstSmallNumbers){
Log.d(n);
}
}
```
#### Output
First numbers not less than their position:
5
4
### linq26: SkipWhile - Simple
```csharp
//c#
public void Linq26()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var allButFirst3Numbers = numbers.SkipWhile(n => n % 3 != 0);
Console.WriteLine("All elements starting from first element divisible by 3:");
foreach (var n in allButFirst3Numbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq26() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> allButFirst3Numbers = skipWhile(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n % 3 != 0;
}
});
Log.d("All elements starting from first element divisible by 3:");
for (Integer n : allButFirst3Numbers){
Log.d(n);
}
}
```
#### Output
All elements starting from first element divisible by 3:
3
9
8
6
7
2
0
### linq27: SkipWhile - Indexed
```csharp
//c#
public void Linq27()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var laterNumbers = numbers.SkipWhile((n, index) => n >= index);
Console.WriteLine("All elements starting from first element less than its position:");
foreach (var n in laterNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq27() {
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Integer> laterNumbers = skipWhilei(toList(numbers), new PredicateIndex<Integer>() {
@Override
public boolean apply(Integer n, int index) {
return n >= index;
}
});
Log.d("All elements starting from first element less than its position:");
for (Integer n : laterNumbers){
Log.d(n);
}
}
```
#### Output
All elements starting from first element less than its position:
1
3
9
8
6
7
2
0
LINQ - Ordering Operators
-------------------------
### linq28: OrderBy - Simple 1
```csharp
//c#
public void Linq28()
{
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w
select w;
Console.WriteLine("The sorted list of words:");
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
}
```
```java
//java
public void linq28(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
List<String> sortedWords = orderBy(words);
Log.d("The sorted list of words:");
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
The sorted list of words:
apple
blueberry
cherry
### linq29: OrderBy - Simple 2
```csharp
//c#
public void Linq29()
{
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w.Length
select w;
Console.WriteLine("The sorted list of words (by length):");
foreach (var w in sortedWords)
{
Console.WriteLine(w);
}
}
```
```java
//java
public void linq29(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
List<String> sortedWords = orderBy(words, new Function<String, Comparable>() {
@Override
public Comparable apply(String s) {
return s.length();
}
});
Log.d("The sorted list of words (by length):");
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
The sorted list of words (by length):
apple
cherry
blueberry
### linq30: OrderBy - Simple 3
```csharp
//c#
public void Linq30()
{
List<Product> products = GetProductList();
var sortedProducts =
from p in products
orderby p.ProductName
select p;
ObjectDumper.Write(sortedProducts);
}
```
```java
//java
public void linq30(){
List<Product> products = getProductList();
List<Product> sortedProducts = orderBy(products, new Function<Product, Comparable>() {
@Override
public Comparable apply(Product p) {
return p.productName;
}
});
for (Product p : sortedProducts){
Log.d(p);
}
}
```
#### Output
(Product id=17, name=Alice Mutton, cat=Meat/Poultry, price=39.0, inStock=0)
(Product id=3, name=Aniseed Syrup, cat=Condiments, price=10.0, inStock=13)
(Product id=40, name=Boston Crab Meat, cat=Seafood, price=18.4, inStock=123)
(Product id=60, name=Camembert Pierrot, cat=Dairy Products, price=34.0, inStock=19)
(Product id=18, name=Carnarvon Tigers, cat=Seafood, price=62.5, inStock=42)
...
### linq31: OrderBy - Comparer
```csharp
//c#
public void Linq31()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
```
```java
//java
public void linq31(){
String[] words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
List<String> sortedWords = orderBy(words, String.CASE_INSENSITIVE_ORDER);
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
AbAcUs
aPPLE
BlUeBeRrY
bRaNcH
cHeRry
ClOvEr
### linq32: OrderByDescending - Simple 1
```csharp
//c#
public void Linq32()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var sortedDoubles =
from d in doubles
orderby d descending
select d;
Console.WriteLine("The doubles from highest to lowest:");
foreach (var d in sortedDoubles)
{
Console.WriteLine(d);
}
}
```
```java
//java
public void linq32(){
double[] doubles = new double[] { 1.7, 2.3, 1.9, 4.1, 2.9 };
List<Double> sortedDoubles = orderByDesc(toList(doubles));
Log.d("The doubles from highest to lowest:");
for (Double d : sortedDoubles){
Log.d(d);
}
}
```
#### Output
The doubles from highest to lowest:
4.1
2.9
2.3
1.9
1.7
### linq33: OrderByDescending - Simple 2
```csharp
//c#
public void Linq33()
{
List<Product> products = GetProductList();
var sortedProducts =
from p in products
orderby p.UnitsInStock descending
select p;
ObjectDumper.Write(sortedProducts);
}
```
```java
//java
public void linq33(){
List<Product> products = getProductList();
List<Product> sortedProducts = orderByDesc(products, new Function<Product, Integer>(){
@Override
public Integer apply(Product p) {
return p.unitsInStock;
}
});
for (Product p : sortedProducts){
Log.d(p);
}
}
```
#### Output
(Product id=75, name=Rhönbräu Klosterbier, cat=Beverages, price=7.75, inStock=125)
(Product id=40, name=Boston Crab Meat, cat=Seafood, price=18.4, inStock=123)
(Product id=6, name=Grandma's Boysenberry Spread, cat=Condiments, price=25.0, inStock=120)
(Product id=55, name=Pâté chinois, cat=Meat/Poultry, price=24.0, inStock=115)
(Product id=61, name=Sirop d'érable, cat=Condiments, price=28.5, inStock=113)
...
### linq34: OrderByDescending - Comparer
```csharp
//c#
public void Linq34()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
```
```java
//java
public void linq34(){
String[] words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
List<String> sortedWords = orderByDesc(words, String.CASE_INSENSITIVE_ORDER);
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
ClOvEr
cHeRry
bRaNcH
BlUeBeRrY
aPPLE
AbAcUs
### linq35: ThenBy - Simple
```csharp
//c#
public void Linq35()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits =
from d in digits
orderby d.Length, d
select d;
Console.WriteLine("Sorted digits:");
foreach (var d in sortedDigits)
{
Console.WriteLine(d);
}
}
```
```java
//java
public void linq35(){
String[] digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<String> sortedDigits = orderBy(orderBy(digits), new Function<String, Comparable>() {
@Override
public Comparable apply(String s) {
return s.length();
}
});
Log.d("Sorted digits:");
for (String d : sortedDigits){
Log.d(d);
}
}
```
#### Output
Sorted digits:
one
six
two
five
four
nine
zero
eight
seven
three
### linq36: ThenBy - Comparer
```csharp
//c#
public void Linq36()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords =
words.OrderBy(a => a.Length)
.ThenBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
```
```java
//java
public void linq36(){
String[] words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
List<String> sortedWords = orderBy(orderBy(words, String.CASE_INSENSITIVE_ORDER), new Function<String, Comparable>() {
@Override
public Comparable apply(String s) {
return s.length();
}
});
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
aPPLE
AbAcUs
bRaNcH
cHeRry
ClOvEr
BlUeBeRrY
### linq37: ThenByDescending - Simple
```csharp
//c#
public void Linq37()
{
List<Product> products = GetProductList();
var sortedProducts =
from p in products
orderby p.Category, p.UnitPrice descending
select p;
ObjectDumper.Write(sortedProducts);
}
```
```java
//java
public void linq37(){
List<Product> products = getProductList();
List<Product> sortedProducts = orderByAll(products,
new Comparator<Product>() {
@Override
public int compare(Product a, Product b) {
return a.category.compareTo(b.category);
}
},
new Comparator<Product>() {
@Override
public int compare(Product a, Product b) {
return b.unitPrice.compareTo(a.unitPrice);
}
}
);
for (Product p : sortedProducts){
Log.d(p);
}
}
```
#### Output
(Product id=38, name=Côte de Blaye, cat=Beverages, price=263.5, inStock=17)
(Product id=43, name=Ipoh Coffee, cat=Beverages, price=46.0, inStock=17)
(Product id=2, name=Chang, cat=Beverages, price=19.0, inStock=17)
(Product id=1, name=Chai, cat=Beverages, price=18.0, inStock=39)
(Product id=35, name=Steeleye Stout, cat=Beverages, price=18.0, inStock=20)
(Product id=39, name=Chartreuse verte, cat=Beverages, price=18.0, inStock=69)
(Product id=76, name=Lakkalikööri, cat=Beverages, price=18.0, inStock=57)
(Product id=70, name=Outback Lager, cat=Beverages, price=15.0, inStock=15)
(Product id=34, name=Sasquatch Ale, cat=Beverages, price=14.0, inStock=111)
...
### linq38: ThenByDescending - Comparer
```csharp
//c#
public void Linq38()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords =
words.OrderBy(a => a.Length)
.ThenByDescending(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
```
```java
//java
public void linq38(){
String[] words = new String[] { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
List<String> sortedWords = orderByAll(words,
new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
},
new Comparator<String>() {
@Override
public int compare(String a, String b) {
return String.CASE_INSENSITIVE_ORDER.compare(b,a);
}
});
for (String w : sortedWords){
Log.d(w);
}
}
```
#### Output
aPPLE
ClOvEr
cHeRry
bRaNcH
AbAcUs
BlUeBeRrY
### linq39: Reverse
```csharp
//c#
public void Linq39()
{
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var reversedIDigits = (
from d in digits
where d[1] == 'i'
select d)
.Reverse();
Console.WriteLine("A backwards list of the digits with a second character of 'i':");
foreach (var d in reversedIDigits)
{
Console.WriteLine(d);
}
}
```
```java
//java
public void linq39(){
String[] digits = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
List<String> reversedIDigits = reverse(filter(digits, new Predicate<String>() {
@Override
public boolean apply(String d) {
return d.charAt(1) == 'i';
}
}));
Log.d("A backwards list of the digits with a second character of 'i':");
for (String d : reversedIDigits){
Log.d(d);
}
}
```
#### Output
A backwards list of the digits with a second character of 'i':
nine
eight
six
five
LINQ - Grouping Operators
-------------------------
### linq40: GroupBy - Simple 1
```csharp
//c#
public void Linq40()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups =
from n in numbers
group n by n % 5 into g
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:", g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n);
}
}
}
```
```java
//java
public void linq40(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
List<Tuple<Integer, Group<Integer,Integer>>> numberGroups = map(
groupBy(toList(numbers), new Function<Integer, Integer>() {
@Override
public Integer apply(Integer n){
return n % 5;
}
}),
new Function<Group<Integer, Integer>, Tuple<Integer, Group<Integer,Integer>>>() {
@Override
public Tuple<Integer, Group<Integer,Integer>> apply(Group<Integer, Integer> g){
return new Tuple<>(g.key, g);
}
});
for (Tuple<Integer, Group<Integer,Integer>> g : numberGroups){
Log.d("Numbers with a remainder of " + g.A + " when divided by 5:");
for (Integer n : g.B){
Log.d(n);
}
}
}
```
#### Output
Numbers with a remainder of 4 when divided by 5:
4
9
Numbers with a remainder of 1 when divided by 5:
1
6
Numbers with a remainder of 0 when divided by 5:
5
0
Numbers with a remainder of 2 when divided by 5:
7
2
Numbers with a remainder of 3 when divided by 5:
3
8
### linq41: GroupBy - Simple 2
```csharp
//c#
public void Linq41()
{
string[] words = { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
var wordGroups =
from w in words
group w by w[0] into g
select new { FirstLetter = g.Key, Words = g };
foreach (var g in wordGroups)
{
Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter);
foreach (var w in g.Words)
{
Console.WriteLine(w);
}
}
}
```
```java
//java
public void linq41(){
String[] words = new String[] { "blueberry", "chimpanzee", "abacus", "banana", "apple", "cheese" };
List<Tuple<Character, Group<Character,String>>> wordGroups = map(
groupBy(toList(words), new Function<String, Character>() {
@Override
public Character apply(String s){
return s.charAt(0);
}
}),
new Function<Group<Character, String>, Tuple<Character, Group<Character,String>>>() {
@Override
public Tuple<Character, Group<Character,String>> apply(Group<Character,String> g){
return new Tuple<>(g.key, g);
}
});
for (Tuple<Character, Group<Character,String>> g : wordGroups){
Log.d("Words that start with the letter '" + g.A + "':");
for (String w : g.B){
Log.d(w);
}
}
}
```
#### Output
Words that start with the letter 'a':
abacus
apple
Words that start with the letter 'b':
blueberry
banana
Words that start with the letter 'c':
chimpanzee
cheese
### linq42: GroupBy - Simple 3
```csharp
//c#
public void Linq42()
{
List<Product> products = GetProductList();
var orderGroups =
from p in products
group p by p.Category into g
select new { Category = g.Key, Products = g };
ObjectDumper.Write(orderGroups, 1);
}
```
```java
//java
public void linq42(){
List<Product> products = getProductList();
List<Tuple<String,Group<String,Product>>> orderGroups = map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p){
return p.category;
}
}),
new Function<Group<String,Product>, Tuple<String, Group<String,Product>>>() {
@Override
public Tuple<String, Group<String,Product>> apply(Group<String,Product> g){
return new Tuple<>(g.key, g);
}
});
for (Tuple<String,Group<String,Product>> x : orderGroups){
Log.d(x.B);
}
}
```
#### Output
Confections:
(Product id=16, name=Pavlova, cat=Confections, price=17.45, inStock=29)
(Product id=19, name=Teatime Chocolate Biscuits, cat=Confections, price=9.2, inStock=25)
(Product id=20, name=Sir Rodney's Marmalade, cat=Confections, price=81.0, inStock=40)
(Product id=21, name=Sir Rodney's Scones, cat=Confections, price=10.0, inStock=3)
(Product id=25, name=NuNuCa Nuß-Nougat-Creme, cat=Confections, price=14.0, inStock=76)
(Product id=26, name=Gumbär Gummibärchen, cat=Confections, price=31.23, inStock=15)
(Product id=27, name=Schoggi Schokolade, cat=Confections, price=43.9, inStock=49)
(Product id=47, name=Zaanse koeken, cat=Confections, price=9.5, inStock=36)
(Product id=48, name=Chocolade, cat=Confections, price=12.75, inStock=15)
(Product id=49, name=Maxilaku, cat=Confections, price=20.0, inStock=10)
(Product id=50, name=Valkoinen suklaa, cat=Confections, price=16.25, inStock=65)
(Product id=62, name=Tarte au sucre, cat=Confections, price=49.3, inStock=17)
(Product id=68, name=Scottish Longbreads, cat=Confections, price=12.5, inStock=6)
Seafood:
(Product id=10, name=Ikura, cat=Seafood, price=31.0, inStock=31)
(Product id=13, name=Konbu, cat=Seafood, price=6.0, inStock=24)
### linq43: GroupBy - Nested
```csharp
//c#
public void Linq43()
{
List<Customer> customers = GetCustomerList();
var customerOrderGroups =
from c in customers
select
new
{
c.CompanyName,
YearGroups =
from o in c.Orders
group o by o.OrderDate.Year into yg
select
new
{
Year = yg.Key,
MonthGroups =
from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
}
};
ObjectDumper.Write(customerOrderGroups, 3);
}
```
```java
//java
public void linq43(){
List<Customer> customers = getCustomerList();
List<Tuple<String, ArrayList<Tuple<Integer, ArrayList<Group<Integer, Order>>>>>> customerOrderGroups =
map(customers, new Function<Customer, Tuple<String, ArrayList<Tuple<Integer, ArrayList<Group<Integer, Order>>>>>>() {
@Override
public Tuple<String, ArrayList<Tuple<Integer, ArrayList<Group<Integer, Order>>>>> apply(Customer c) {
return new Tuple<>( //Yay Type Inference!
c.companyName,
map(groupBy(c.orders, new Function<Order, Integer>() {
@Override
public Integer apply(Order o) {
return o.orderDate.getYear() + 1900;
}
}),
new Function<Group<Integer, Order>, Tuple<Integer, ArrayList<Group<Integer, Order>>>>() {
@Override
public Tuple<Integer, ArrayList<Group<Integer, Order>>> apply(Group<Integer, Order> yg) {
return new Tuple<>( //Yay Type Inference!
yg.key,
groupBy(yg.items, new Function<Order, Integer>() {
@Override
public Integer apply(Order o) {
return o.orderDate.getMonth() + 1;
}
})
);
}
}
)
);
}
});
for (Tuple<String, ArrayList<Tuple<Integer, ArrayList<Group<Integer, Order>>>>> g : customerOrderGroups){
Log.d("\n# " + g.A);
for (Tuple<Integer, ArrayList<Group<Integer, Order>>> yg : g.B){
Log.d(yg.A + ": ");
for (Group<Integer, Order> mg : yg.B){
Log.d(" " + mg.key + ": ");
for (Order o : mg){
Log.d(" " + o);
}
}
}
}
}
```
#### Output
# Alfreds Futterkiste
1997:
8:
(Order id=10643, total=814.5)
10:
(Order id=10692, total=878.0)
(Order id=10702, total=330.0)
1998:
4:
(Order id=11011, total=933.5)
1:
(Order id=10835, total=845.8)
3:
(Order id=10952, total=471.2)
### linq44: GroupBy - Comparer
```csharp
//c#
public void Linq44()
{
string[] anagrams = { "from ", " salt", " earn ", " last ", " near ", " form " };
var orderGroups = anagrams.GroupBy(w => w.Trim(), new AnagramEqualityComparer());
ObjectDumper.Write(orderGroups, 1);
}
```
```java
//java
public void linq44(){
String[] anagrams = new String[] { "from ", " salt", " earn ", " last ", " near ", " form " };
List<Group<String, String>> orderGroups = groupBy(toList(anagrams),
new Function<String, String>() {
@Override
public String apply(String w) {
return w.trim();
}
},
new Predicate2<String, String>() {
@Override
public boolean apply(String a, String b) {
char[] aChars = a.toCharArray();
char[] bChars = b.toCharArray();
Arrays.sort(aChars);
Arrays.sort(bChars);
return Arrays.equals(aChars, bChars);
}
});
for (Group<String, String> g : orderGroups){
StringBuilder sb = new StringBuilder();
for (String w : g){
if (sb.length() > 0)
sb.append(", ");
sb.append("'").append(w).append("'");
}
Log.d("[ " + sb + " ]");
}
}
```
#### Output
[ ' earn ', ' near ' ]
[ ' salt', ' last ' ]
[ 'from ', ' form ' ]
### linq45: GroupBy - Comparer, Mapped
```csharp
//c#
public void Linq45()
{
string[] anagrams = { "from ", " salt", " earn ", " last ", " near ", " form " };
var orderGroups = anagrams.GroupBy(
w => w.Trim(),
a => a.ToUpper(),
new AnagramEqualityComparer()
);
ObjectDumper.Write(orderGroups, 1);
}
```
```java
//java
public void linq45(){
String[] anagrams = new String[] { "from ", " salt", " earn ", " last ", " near ", " form " };
List<Group<String, String>> orderGroups = groupBy(toList(anagrams),
new Function<String, String>() {
@Override
public String apply(String w) {
return w.trim();
}
},
new Predicate2<String, String>() {
@Override
public boolean apply(String a, String b) {
char[] aChars = a.toCharArray();
char[] bChars = b.toCharArray();
Arrays.sort(aChars);
Arrays.sort(bChars);
return Arrays.equals(aChars, bChars);
}
},
new Function<String, String>() {
@Override
public String apply(String s) {
return s.toUpperCase();
}
});
for (Group<String, String> g : orderGroups){
StringBuilder sb = new StringBuilder();
for (String w : g){
if (sb.length() > 0)
sb.append(", ");
sb.append("'").append(w).append("'");
}
Log.d("[ " + sb + " ]");
}
}
```
#### Output
[ ' EARN ', ' NEAR ' ]
[ ' SALT', ' LAST ' ]
[ 'FROM ', ' FORM ' ]
LINQ - Set Operators
--------------------
### linq46: Distinct - 1
```csharp
//c#
public void Linq46()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
var uniqueFactors = factorsOf300.Distinct();
Console.WriteLine("Prime factors of 300:");
foreach (var f in uniqueFactors)
{
Console.WriteLine(f);
}
}
```
```java
//java
public void linq46(){
int[] factorsOf300 = new int[] { 2, 2, 3, 5, 5 };
List<Integer> uniqueFactors = distinct(toList(factorsOf300));
Log.d("Prime factors of 300:");
for (Integer f : uniqueFactors){
Log.d(f);
}
}
```
#### Output
Prime factors of 300:
5
3
2
### linq47: Distinct - 2
```csharp
//c#
public void Linq47()
{
List<Product> products = GetProductList();
var categoryNames = (
from p in products
select p.Category)
.Distinct();
Console.WriteLine("Category names:");
foreach (var n in categoryNames)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq47(){
List<Product> products = getProductList();
List<String> categoryNames = distinct(
map(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}));
Log.d("Category names:");
for (String n : categoryNames){
Log.d(n);
}
}
```
#### Output
Category names:
Confections
Seafood
Grains/Cereals
Meat/Poultry
Beverages
Condiments
Dairy Products
Produce
### linq48: Union - 1
```csharp
//c#
public void Linq48()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var uniqueNumbers = numbersA.Union(numbersB);
Console.WriteLine("Unique numbers from both arrays:");
foreach (var n in uniqueNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq48(){
int[] numbersA = new int[] { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = new int[] { 1, 3, 5, 7, 8 };
List<Integer> uniqueNumbers = union(toList(numbersA), toList(numbersB));
Log.d("Unique numbers from both arrays:");
for (Integer n : uniqueNumbers){
Log.d(n);
}
}
```
#### Output
Unique numbers from both arrays:
0
2
4
5
6
8
9
1
3
7
### linq49: Union - 2
```csharp
//c#
public void Linq49()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList();
var productFirstChars =
from p in products
select p.ProductName[0];
var customerFirstChars =
from c in customers
select c.CompanyName[0];
var uniqueFirstChars = productFirstChars.Union(customerFirstChars);
Console.WriteLine("Unique first letters from Product names and Customer names:");
foreach (var ch in uniqueFirstChars)
{
Console.WriteLine(ch);
}
}
```
```java
//java
public void linq49(){
List<Product> products = getProductList();
List<Customer> customers = getCustomerList();
List<Character> productFirstChars = map(products, new Function<Product, Character>() {
@Override
public Character apply(Product p) {
return p.productName.charAt(0);
}
});
List<Character> customerFirstChars = map(customers, new Function<Customer, Character>() {
@Override
public Character apply(Customer c) {
return c.companyName.charAt(0);
}
});
List<Character> uniqueFirstChars = union(productFirstChars, customerFirstChars);
Log.d("Unique first letters from Product names and Customer names:");
for (Character ch : uniqueFirstChars){
Log.d(ch);
}
}
```
#### Output
Unique first letters from Product names and Customer names:
C
A
G
U
N
M
I
Q
K
T
P
S
R
B
J
Z
V
F
E
W
L
O
D
H
### linq50: Intersect - 1
```csharp
//c#
public void Linq50()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var commonNumbers = numbersA.Intersect(numbersB);
Console.WriteLine("Common numbers shared by both arrays:");
foreach (var n in commonNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq50(){
int[] numbersA = new int[] { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = new int[] { 1, 3, 5, 7, 8 };
List<Integer> commonNumbers = intersect(toList(numbersA), toList(numbersB));
Log.d("Common numbers shared by both arrays:");
for (Integer n : commonNumbers){
Log.d(n);
}
}
```
#### Output
Common numbers shared by both arrays:
5
8
### linq51: Intersect - 2
```csharp
//c#
public void Linq51()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList();
var productFirstChars =
from p in products
select p.ProductName[0];
var customerFirstChars =
from c in customers
select c.CompanyName[0];
var commonFirstChars = productFirstChars.Intersect(customerFirstChars);
Console.WriteLine("Common first letters from Product names and Customer names:");
foreach (var ch in commonFirstChars)
{
Console.WriteLine(ch);
}
}
```
```java
//java
public void linq51(){
List<Product> products = getProductList();
List<Customer> customers = getCustomerList();
List<Character> productFirstChars = map(products, new Function<Product, Character>() {
@Override
public Character apply(Product p) {
return p.productName.charAt(0);
}
});
List<Character> customerFirstChars = map(customers, new Function<Customer, Character>() {
@Override
public Character apply(Customer c) {
return c.companyName.charAt(0);
}
});
List<Character> commonFirstChars = intersect(productFirstChars, customerFirstChars);
Log.d("Common first letters from Product names and Customer names:");
for (Character ch : commonFirstChars){
Log.d(ch);
}
}
```
#### Output
Common first letters from Product names and Customer names:
C
A
G
N
M
I
Q
K
T
P
S
R
B
V
F
E
W
L
O
### linq52: Except - 1
```csharp
//c#
public void Linq52()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq52(){
int[] numbersA = new int[] { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = new int[] { 1, 3, 5, 7, 8 };
List<Integer> aOnlyNumbers = difference(toList(numbersA), toList(numbersB));
Log.d("Numbers in first array but not second array:");
for(Integer n: aOnlyNumbers){
Log.d(n);
}
}
```
#### Output
Numbers in first array but not second array:
0
2
4
6
9
### linq53: Except - 2
```csharp
//c#
public void Linq53()
{
List<Product> products = GetProductList();
List<Customer> customers = GetCustomerList();
var productFirstChars =
from p in products
select p.ProductName[0];
var customerFirstChars =
from c in customers
select c.CompanyName[0];
var productOnlyFirstChars = productFirstChars.Except(customerFirstChars);
Console.WriteLine("First letters from Product names, but not from Customer names:");
foreach (var ch in productOnlyFirstChars)
{
Console.WriteLine(ch);
}
}
```
```java
//java
public void linq53(){
List<Product> products = getProductList();
List<Customer> customers = getCustomerList();
List<Character> productFirstChars = map(products, new Function<Product, Character>() {
@Override
public Character apply(Product p) {
return p.productName.charAt(0);
}
});
List<Character> customerFirstChars = map(customers, new Function<Customer, Character>() {
@Override
public Character apply(Customer c) {
return c.companyName.charAt(0);
}
});
List<Character> productOnlyFirstChars = difference(productFirstChars, customerFirstChars);
Log.d("First letters from Product names, but not from Customer names:");
for (Character ch : productOnlyFirstChars){
Log.d(ch);
}
}
```
#### Output
First letters from Product names, but not from Customer names:
U
J
Z
LINQ - Conversion Operators
---------------------------
### linq54: ToArray
```csharp
//c#
public void Linq54()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var sortedDoubles =
from d in doubles
orderby d descending
select d;
var doublesArray = sortedDoubles.ToArray();
Console.WriteLine("Every other double from highest to lowest:");
for (int d = 0; d < doublesArray.Length; d += 2)
{
Console.WriteLine(doublesArray[d]);
}
}
```
```java
//java
public void linq54(){
double[] doubles = new double[] { 1.7, 2.3, 1.9, 4.1, 2.9 };
List<Double> sortedDoubles = orderByDesc(toList(doubles));
Double[] doublesArray = toArray(sortedDoubles, Double.class);
Log.d("Every other double from highest to lowest:");
for (int d = 0; d < doublesArray.length; d += 2){
Log.d(doublesArray[d]);
}
}
```
#### Output
Every other double from highest to lowest:
4.1
2.3
1.7
### linq55: ToList
```csharp
//c#
public void Linq55()
{
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords =
from w in words
orderby w
select w;
var wordList = sortedWords.ToList();
Console.WriteLine("The sorted word list:");
foreach (var w in wordList)
{
Console.WriteLine(w);
}
}
```
```java
//java
public void linq55(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
List<String> sortedWords = orderBy(words);
List<String> wordList = toList(sortedWords);
Log.d("The sorted word list:");
for (String w : wordList){
Log.d(w);
}
}
```
#### Output
The sorted word list:
apple
blueberry
cherry
### linq56: ToDictionary
```csharp
//c#
public void Linq56()
{
var scoreRecords = new[] { new {Name = "Alice", Score = 50},
new {Name = "Bob" , Score = 40},
new {Name = "Cathy", Score = 45}
};
var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
}
```
```java
//java
public void linq56(){
List<Tuple<String,Integer>> scoreRecords = toList(
new Tuple<>("Alice", 50),
new Tuple<>("Bob", 40),
new Tuple<>("Cathy", 45)
);
Map<String,Tuple<String,Integer>> scoreRecordsDict = toDictionary(scoreRecords, new Function<Tuple<String, Integer>, String>() {
@Override
public String apply(Tuple<String, Integer> t) {
return t.A;
}
});
Log.d("Bob's score: " + scoreRecordsDict.get("Bob"));
}
```
#### Output
Bob's score: (Bob, 40)
### linq57: OfType
```csharp
//c#
public void Linq57()
{
object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 };
var doubles = numbers.OfType<double>();
Console.WriteLine("Numbers stored as doubles:");
foreach (var d in doubles)
{
Console.WriteLine(d);
}
}
```
```java
//java
public void linq57(){
Object[] numbers = new Object[] { null, 1.0, "two", 3, "four", 5, "six", 7.0 };
List<Double> doubles = ofType(toList(numbers), Double.class);
Log.d("Numbers stored as doubles:");
for (Double d : doubles){
Log.d(d);
}
}
```
#### Output
Numbers stored as doubles:
1.0
7.0
LINQ - Element Operators
------------------------
### linq58: First - Simple
```csharp
//c#
public void Linq58()
{
List<Product> products = GetProductList();
Product product12 = (
from p in products
where p.ProductID == 12
select p)
.First();
ObjectDumper.Write(product12);
}
```
```java
//java
public void linq58(){
List<Product> products = getProductList();
Product product12 = first(products, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.productId == 12;
}
});
Log.d(product12);
}
```
#### Output
(Product id=12, name=Queso Manchego La Pastora, cat=Dairy Products, price=38.0, inStock=86)
### linq59: First - Condition
```csharp
//c#
public void Linq59()
{
string[] strings = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string startsWithO = strings.First(s => s[0] == 'o');
Console.WriteLine("A string starting with 'o': {0}", startsWithO);
}
```
```java
//java
public void linq59(){
String[] strings = new String[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
String startsWithO = first(strings, new Predicate<String>() {
@Override
public boolean apply(String s) {
return s.charAt(0) == 'o';
}
});
Log.d("A string starting with 'o': " + startsWithO);
}
```
#### Output
A string starting with 'o': one
### linq61: FirstOrDefault - Simple
```csharp
//c#
public void Linq61()
{
int[] numbers = { };
int firstNumOrDefault = numbers.FirstOrDefault();
Console.WriteLine(firstNumOrDefault);
}
```
```java
//java
public void linq61(){
int[] numbers = { };
int firstNumOrDefault = first(toList(numbers), 0);
Log.d(firstNumOrDefault);
}
```
#### Output
0
### linq62: FirstOrDefault - Condition
```csharp
//c#
public void Linq62()
{
List<Product> products = GetProductList();
Product product789 = products.FirstOrDefault(p => p.ProductID == 789);
Console.WriteLine("Product 789 exists: {0}", product789 != null);
}
```
```java
//java
public void linq62(){
List<Product> products = getProductList();
Product product789 = first(products, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.productId == 789;
}
});
Log.d("Product 789 exists: " + (product789 != null));
}
```
#### Output
Product 789 exists: false
### linq64: ElementAt
```csharp
//c#
public void Linq64()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = (
from n in numbers
where n > 5
select n)
.ElementAt(1); // second number is index 1 because sequences use 0-based indexing
Console.WriteLine("Second number > 5: {0}", fourthLowNum);
}
```
```java
//java
public void linq64(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
Integer fourthLowNum = filter(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n > 5;
}
})
.get(1); // second number is index 1 because sequences use 0-based indexing
Log.d("Second number > 5: " + fourthLowNum);
}
```
#### Output
Second number > 5: 8
LINQ - Generation Operators
---------------------------
### linq65: Range
```csharp
//c#
public void Linq65()
{
var numbers =
from n in Enumerable.Range(100, 50)
select new { Number = n, OddEven = n % 2 == 1 ? "odd" : "even" };
foreach (var n in numbers)
{
Console.WriteLine("The number {0} is {1}.", n.Number, n.OddEven);
}
}
```
```java
//java
public void linq65(){
List<Tuple<Integer, String>> numbers = map(toList(range(100, 150)), new Function<Integer, Tuple<Integer, String>>() {
@Override
public Tuple<Integer, String> apply(Integer n) {
return new Tuple<>(n, n % 2 == 1 ? "odd" : "even");
}
});
for (Tuple<Integer,String> n : numbers){
Log.d("The number " + n.A + " is " + n.B);
}
}
```
#### Output
The number 100 is even
The number 101 is odd
The number 102 is even
The number 103 is odd
The number 104 is even
The number 105 is odd
The number 106 is even
The number 107 is odd
The number 108 is even
The number 109 is odd
The number 110 is even
...
### linq66: Repeat
```csharp
//c#
public void Linq66()
{
var numbers = Enumerable.Repeat(7, 10);
foreach (var n in numbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq66(){
int[] numbers = repeat(7, 10);
for (int n : numbers){
Log.d(n);
}
}
```
#### Output
7
7
7
7
7
7
7
7
7
7
LINQ - Quantifiers
------------------
### linq67: Any - Simple
```csharp
//c#
public void Linq67()
{
string[] words = { "believe", "relief", "receipt", "field" };
bool iAfterE = words.Any(w => w.Contains("ei"));
Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE);
}
```
```java
//java
public void linq67(){
String[] words = new String[] { "believe", "relief", "receipt", "field" };
boolean iAfterE = any(words, new Predicate<String>() {
@Override
public boolean apply(String w) {
return w.contains("ei");
}
});
Log.d("There is a word that contains in the list that contains 'ei': " + iAfterE);
}
```
#### Output
There is a word that contains in the list that contains 'ei': true
### linq69: Any - Grouped
```csharp
//c#
public void Linq69()
{
List<Product> products = GetProductList();
var productGroups =
from p in products
group p by p.Category into g
where g.Any(p => p.UnitsInStock == 0)
select new { Category = g.Key, Products = g };
ObjectDumper.Write(productGroups, 1);
}
```
```java
//java
public void linq69(){
List<Product> products = getProductList();
List<Tuple<String, Group<String,Product>>> productGroups =
map(
filter(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Predicate<Group<String, Product>>() {
@Override
public boolean apply(Group<String, Product> g) {
return any(g, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitsInStock == 0;
}
});
}
})
, new Function<Group<String, Product>, Tuple<String, Group<String, Product>>>() {
@Override
public Tuple<String, Group<String, Product>> apply(Group<String, Product> g) {
return new Tuple<>(g.key, g);
}
}
);
for (Tuple<String, Group<String,Product>> t : productGroups){
Log.d(t.B);
}
}
```
#### Output
Meat/Poultry:
(Product id=9, name=Mishi Kobe Niku, cat=Meat/Poultry, price=97.0, inStock=29)
(Product id=17, name=Alice Mutton, cat=Meat/Poultry, price=39.0, inStock=0)
(Product id=29, name=Thüringer Rostbratwurst, cat=Meat/Poultry, price=123.79, inStock=0)
(Product id=53, name=Perth Pasties, cat=Meat/Poultry, price=32.8, inStock=0)
(Product id=54, name=Tourtière, cat=Meat/Poultry, price=7.45, inStock=21)
(Product id=55, name=Pâté chinois, cat=Meat/Poultry, price=24.0, inStock=115)
Condiments:
(Product id=3, name=Aniseed Syrup, cat=Condiments, price=10.0, inStock=13)
(Product id=4, name=Chef Anton's Cajun Seasoning, cat=Condiments, price=22.0, inStock=53)
...
### linq70: All - Simple
```csharp
//c#
public void Linq70()
{
int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
bool onlyOdd = numbers.All(n => n % 2 == 1);
Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd);
}
```
```java
//java
public void linq70(){
int[] numbers = new int[] { 1, 11, 3, 19, 41, 65, 19 };
boolean onlyOdd = all(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n % 2 == 1;
}
});
Log.d("The list contains only odd numbers: " + onlyOdd);
}
```
#### Output
The list contains only odd numbers: true
### linq72: All - Grouped
```csharp
//c#
public void Linq72()
{
List<Product> products = GetProductList();
var productGroups =
from p in products
group p by p.Category into g
where g.All(p => p.UnitsInStock > 0)
select new { Category = g.Key, Products = g };
ObjectDumper.Write(productGroups, 1);
}
```
```java
//java
public void linq72(){
List<Product> products = getProductList();
List<Tuple<String, Group<String,Product>>> productGroups =
map(
filter(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Predicate<Group<String, Product>>() {
@Override
public boolean apply(Group<String, Product> g) {
return all(g, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitsInStock > 0;
}
});
}
})
, new Function<Group<String, Product>, Tuple<String, Group<String, Product>>>() {
@Override
public Tuple<String, Group<String, Product>> apply(Group<String, Product> g) {
return new Tuple<>(g.key, g);
}
}
);
for (Tuple<String, Group<String,Product>> t : productGroups){
Log.d(t.B);
}
}
```
#### Output
Confections:
(Product id=16, name=Pavlova, cat=Confections, price=17.45, inStock=29)
(Product id=19, name=Teatime Chocolate Biscuits, cat=Confections, price=9.2, inStock=25)
(Product id=20, name=Sir Rodney's Marmalade, cat=Confections, price=81.0, inStock=40)
(Product id=21, name=Sir Rodney's Scones, cat=Confections, price=10.0, inStock=3)
(Product id=25, name=NuNuCa Nuß-Nougat-Creme, cat=Confections, price=14.0, inStock=76)
(Product id=26, name=Gumbär Gummibärchen, cat=Confections, price=31.23, inStock=15)
(Product id=27, name=Schoggi Schokolade, cat=Confections, price=43.9, inStock=49)
(Product id=47, name=Zaanse koeken, cat=Confections, price=9.5, inStock=36)
(Product id=48, name=Chocolade, cat=Confections, price=12.75, inStock=15)
(Product id=49, name=Maxilaku, cat=Confections, price=20.0, inStock=10)
(Product id=50, name=Valkoinen suklaa, cat=Confections, price=16.25, inStock=65)
(Product id=62, name=Tarte au sucre, cat=Confections, price=49.3, inStock=17)
(Product id=68, name=Scottish Longbreads, cat=Confections, price=12.5, inStock=6)
...
LINQ - Aggregate Operators
--------------------------
### linq73: Count - Simple
```csharp
//c#
public void Linq73()
{
int[] factorsOf300 = { 2, 2, 3, 5, 5 };
int uniqueFactors = factorsOf300.Distinct().Count();
Console.WriteLine("There are {0} unique factors of 300.", uniqueFactors);
}
```
```java
//java
public void linq73(){
int[] factorsOf300 = new int[] { 2, 2, 3, 5, 5 };
int uniqueFactors = distinct(toList(factorsOf300)).size();
Log.d("There are " + uniqueFactors + " unique factors of 300.");
}
```
#### Output
There are 3 unique factors of 300.
### linq74: Count - Conditional
```csharp
//c#
public void Linq74()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = numbers.Count(n => n % 2 == 1);
Console.WriteLine("There are {0} odd numbers in the list.", oddNumbers);
}
```
```java
//java
public void linq74(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int oddNumbers = count(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n % 2 == 1;
}
});
Log.d("There are " + oddNumbers + " odd numbers in the list.");
}
```
#### Output
There are 5 odd numbers in the list.
### linq76: Count - Nested
```csharp
//c#
public void Linq76()
{
List<Customer> customers = GetCustomerList();
var orderCounts =
from c in customers
select new { c.CustomerID, OrderCount = c.Orders.Count() };
ObjectDumper.Write(orderCounts);
}
```
```java
//java
public void linq76(){
List<Customer> customers = getCustomerList();
List<Tuple<String, Integer>> orderCounts =
map(customers, new Function<Customer, Tuple<String, Integer>>() {
@Override
public Tuple<String, Integer> apply(Customer c) {
return new Tuple<>(c.customerId, c.orders.size());
}
});
for (Tuple<?,?> t : orderCounts){
Log.d(t);
}
}
```
#### Output
(ALFKI, 6)
(ANATR, 4)
(ANTON, 7)
(AROUT, 13)
(BERGS, 18)
(BLAUS, 7)
(BLONP, 11)
...
### linq77: Count - Grouped
```csharp
//c#
public void Linq77()
{
List<Product> products = GetProductList();
var categoryCounts =
from p in products
group p by p.Category into g
select new { Category = g.Key, ProductCount = g.Count() };
ObjectDumper.Write(categoryCounts
}
```
```java
//java
public void linq77(){
List<Product> products = getProductList();
List<Tuple<String,Integer>> categoryCounts =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String,Integer>>() {
@Override
public Tuple<String, Integer> apply(Group<String, Product> g) {
return new Tuple<>(g.key, g.items.size());
}
}
);
for (Tuple<?,?> t : categoryCounts){
Log.d(t);
}
}
```
#### Output
(Confections, 13)
(Seafood, 12)
(Grains/Cereals, 7)
(Meat/Poultry, 6)
(Beverages, 12)
(Condiments, 12)
(Dairy Products, 10)
(Produce, 5)
### linq78: Sum - Simple
```csharp
//c#
public void Linq78()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double numSum = numbers.Sum();
Console.WriteLine("The sum of the numbers is {0}.", numSum);
}
```
```java
//java
public void linq78(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double numSum = sum(numbers);
Log.d("The sum of the numbers is " + numSum);
}
```
#### Output
The sum of the numbers is 45.0
### linq79: Sum - Projection
```csharp
//c#
public void Linq79()
{
string[] words = { "cherry", "apple", "blueberry" };
double totalChars = words.Sum(w => w.Length);
Console.WriteLine("There are a total of {0} characters in these words.", totalChars);
}
```
```java
//java
public void linq79(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
Integer totalChars = sum(toList(words), new Function<String, Integer>() {
@Override
public Integer apply(String w) {
return w.length();
}
});
Log.d("There are a total of " + totalChars + " characters in these words.");
}
```
#### Output
There are a total of 20 characters in these words.
### linq80: Sum - Grouped
```csharp
//c#
public void Linq80()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
select new { Category = g.Key, TotalUnitsInStock = g.Sum(p => p.UnitsInStock) };
ObjectDumper.Write(categories);
}
```
```java
//java
public void linq80(){
List<Product> products = getProductList();
List<Tuple<String, Integer>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
})
, new Function<Group<String,Product>, Tuple<String, Integer>>() {
@Override
public Tuple<String, Integer> apply(Group<String, Product> g) {
return new Tuple<>(g.key, sum(g, new Function<Product, Integer>() {
@Override
public Integer apply(Product p) {
return p.unitsInStock;
}
}));
}
}
);
for (Tuple<?,?> t : categories){
Log.d(t);
}
}
```
#### Output
(Confections, 386)
(Seafood, 701)
(Grains/Cereals, 308)
(Meat/Poultry, 165)
(Beverages, 559)
(Condiments, 507)
(Dairy Products, 393)
(Produce, 100)
### linq81: Min - Simple
```csharp
//c#
public void Linq81()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int minNum = numbers.Min();
Console.WriteLine("The minimum number is {0}.", minNum);
}
```
```java
//java
public void linq81(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int minNum = min(numbers);
Log.d("The minimum number is " + minNum);
}
```
#### Output
The minimum number is 0
### linq82: Min - Projection
```csharp
//c#
public void Linq82()
{
string[] words = { "cherry", "apple", "blueberry" };
int shortestWord = words.Min(w => w.Length);
Console.WriteLine("The shortest word is {0} characters long.", shortestWord);
}
```
```java
//java
public void linq82(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
int shortestWord = min(words, new Function<String, Integer>() {
@Override
public Integer apply(String w) {
return w.length();
}
});
Log.d("The shortest word is " + shortestWord + " characters long.");
}
```
#### Output
The shortest word is 5 characters long.
### linq83: Min - Grouped
```csharp
//c#
public void Linq83()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
select new { Category = g.Key, CheapestPrice = g.Min(p => p.UnitPrice) };
ObjectDumper.Write(categories);
}
```
```java
//java
public void linq83(){
List<Product> products = getProductList();
List<Tuple<String,Double>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String, Double>>() {
@Override
public Tuple<String, Double> apply(Group<String, Product> g) {
return new Tuple<>(g.key, minDouble(g, new Function<Product, Double>() {
@Override
public Double apply(Product p) {
return p.unitPrice;
}
}));
}
}
);
for (Tuple<?,?> t : categories){
Log.d(t);
}
}
```
#### Output
(Confections, 9.2)
(Seafood, 6.0)
(Grains/Cereals, 7.0)
(Meat/Poultry, 7.45)
(Beverages, 4.5)
(Condiments, 10.0)
(Dairy Products, 2.5)
(Produce, 10.0)
### linq84: Min - Elements
```csharp
//c#
public void Linq84()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
let minPrice = g.Min(p => p.UnitPrice)
select new { Category = g.Key, CheapestProducts = g.Where(p => p.UnitPrice == minPrice) };
ObjectDumper.Write(categories, 1);
}
```
```java
//java
public void linq84(){
List<Product> products = getProductList();
List<Tuple<String,ArrayList<Product>>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String, ArrayList<Product>>>() {
@Override
public Tuple<String, ArrayList<Product>> apply(Group<String, Product> g) {
final double minPrice = minDouble(g, new Function<Product, Double>() {
@Override
public Double apply(Product p) {
return p.unitPrice;
}
});
return new Tuple<>(
g.key,
filter(g.items, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitPrice == minPrice;
}
})
);
}
}
);
for (Tuple<String,ArrayList<Product>> t : categories){
Log.d(t.A + ": ");
Log.d(t.B);
}
}
```
#### Output
Confections:
[(Product id=19, name=Teatime Chocolate Biscuits, cat=Confections, price=9.2, inStock=25)]
Seafood:
[(Product id=13, name=Konbu, cat=Seafood, price=6.0, inStock=24)]
Grains/Cereals:
[(Product id=52, name=Filo Mix, cat=Grains/Cereals, price=7.0, inStock=38)]
Meat/Poultry:
[(Product id=54, name=Tourtière, cat=Meat/Poultry, price=7.45, inStock=21)]
Beverages:
[(Product id=24, name=Guaraná Fantástica, cat=Beverages, price=4.5, inStock=20)]
Condiments:
[(Product id=3, name=Aniseed Syrup, cat=Condiments, price=10.0, inStock=13)]
Dairy Products:
[(Product id=33, name=Geitost, cat=Dairy Products, price=2.5, inStock=112)]
Produce:
[(Product id=74, name=Longlife Tofu, cat=Produce, price=10.0, inStock=4)]
### linq85: Max - Simple
```csharp
//c#
public void Linq85()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int maxNum = numbers.Max();
Console.WriteLine("The maximum number is {0}.", maxNum);
}
```
```java
//java
public void linq85(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int maxNum = max(numbers);
Log.d("The maximum number is " + maxNum);
}
```
#### Output
The maximum number is 9
### linq86: Max - Projection
```csharp
//c#
public void Linq86()
{
string[] words = { "cherry", "apple", "blueberry" };
int longestLength = words.Max(w => w.Length);
Console.WriteLine("The longest word is {0} characters long.", longestLength);
}
```
```java
//java
public void linq86(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
int longestLength = max(words, new Function<String, Integer>() {
@Override
public Integer apply(String w) {
return w.length();
}
});
Log.d("The longest word is " + longestLength + " characters long.");
}
```
#### Output
The longest word is 9 characters long.
### linq87: Max - Grouped
```csharp
//c#
public void Linq87()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
select new { Category = g.Key, MostExpensivePrice = g.Max(p => p.UnitPrice) };
ObjectDumper.Write(categories);
}
```
```java
//java
public void linq87(){
List<Product> products = getProductList();
ArrayList<Tuple<String, Double>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String, Double>>() {
@Override
public Tuple<String, Double> apply(Group<String, Product> g) {
return new Tuple<>(
g.key,
maxDouble(g, new Function<Product, Double>() {
@Override
public Double apply(Product p) {
return p.unitPrice;
}
})
);
}
}
);
for (Tuple<?,?> t : categories){
Log.d(t);
}
}
```
#### Output
(Confections, 81.0)
(Seafood, 62.5)
(Grains/Cereals, 38.0)
(Meat/Poultry, 123.79)
(Beverages, 263.5)
(Condiments, 43.9)
(Dairy Products, 55.0)
(Produce, 53.0)
### linq88: Max - Elements
```csharp
//c#
public void Linq88()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
let maxPrice = g.Max(p => p.UnitPrice)
select new { Category = g.Key, MostExpensiveProducts = g.Where(p => p.UnitPrice == maxPrice) };
ObjectDumper.Write(categories, 1);
}
```
```java
//java
public void linq88(){
List<Product> products = getProductList();
List<Tuple<String,ArrayList<Product>>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String, ArrayList<Product>>>() {
@Override
public Tuple<String, ArrayList<Product>> apply(Group<String, Product> g) {
final double maxPrice = maxDouble(g, new Function<Product, Double>() {
@Override
public Double apply(Product p) {
return p.unitPrice;
}
});
return new Tuple<>(
g.key,
filter(g.items, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return p.unitPrice == maxPrice;
}
})
);
}
}
);
for (Tuple<String,ArrayList<Product>> t : categories){
Log.d(t.A + ": ");
Log.d(t.B);
}
}
```
#### Output
Confections:
[(Product id=20, name=Sir Rodney's Marmalade, cat=Confections, price=81.0, inStock=40)]
Seafood:
[(Product id=18, name=Carnarvon Tigers, cat=Seafood, price=62.5, inStock=42)]
Grains/Cereals:
[(Product id=56, name=Gnocchi di nonna Alice, cat=Grains/Cereals, price=38.0, inStock=21)]
Meat/Poultry:
[(Product id=29, name=Thüringer Rostbratwurst, cat=Meat/Poultry, price=123.79, inStock=0)]
Beverages:
[(Product id=38, name=Côte de Blaye, cat=Beverages, price=263.5, inStock=17)]
Condiments:
[(Product id=63, name=Vegie-spread, cat=Condiments, price=43.9, inStock=24)]
Dairy Products:
[(Product id=59, name=Raclette Courdavault, cat=Dairy Products, price=55.0, inStock=79)]
Produce:
[(Product id=51, name=Manjimup Dried Apples, cat=Produce, price=53.0, inStock=20)]
### linq89: Average - Simple
```csharp
//c#
public void Linq89()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double averageNum = numbers.Average();
Console.WriteLine("The average number is {0}.", averageNum);
}
```
```java
//java
public void linq89(){
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
double averageNum = avg(numbers);
Log.d("The average number is " + averageNum);
}
```
#### Output
The average number is 4.5
### linq90: Average - Projection
```csharp
//c#
public void Linq90()
{
string[] words = { "cherry", "apple", "blueberry" };
double averageLength = words.Average(w => w.Length);
Console.WriteLine("The average word length is {0} characters.", averageLength);
}
```
```java
//java
public void linq90(){
String[] words = new String[] { "cherry", "apple", "blueberry" };
double averageLength = avg(words, new Function<String, Integer>() {
@Override
public Integer apply(String w) {
return w.length();
}
});
Log.d("The average word length is " + averageLength + " characters.");
}
```
#### Output
The average word length is 6.666666666666667 characters.
### linq91: Average - Grouped
```csharp
//c#
public void Linq91()
{
List<Product> products = GetProductList();
var categories =
from p in products
group p by p.Category into g
select new { Category = g.Key, AveragePrice = g.Average(p => p.UnitPrice) };
ObjectDumper.Write(categories);
}
```
```java
//java
public void linq91(){
List<Product> products = getProductList();
ArrayList<Tuple<String, Double>> categories =
map(
groupBy(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.category;
}
}),
new Function<Group<String, Product>, Tuple<String, Double>>() {
@Override
public Tuple<String, Double> apply(Group<String, Product> g) {
return new Tuple<>(
g.key,
avgDouble(g, new Function<Product, Double>() {
@Override
public Double apply(Product p) {
return p.unitPrice;
}
})
);
}
}
);
for (Tuple<?,?> t : categories){
Log.d(t);
}
}
```
#### Output
(Confections, 25.16)
(Seafood, 20.6825)
(Grains/Cereals, 20.25)
(Meat/Poultry, 54.00666666666667)
(Beverages, 37.979166666666664)
(Condiments, 23.0625)
(Dairy Products, 28.73)
(Produce, 32.37)
### linq92: Aggregate - Simple
```csharp
//c#
public void Linq92()
{
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);
Console.WriteLine("Total product of all numbers: {0}", product);
}
```
```java
//java
public void linq92(){
double[] doubles = new double[] { 1.7, 2.3, 1.9, 4.1, 2.9 };
double product = reduce(toList(doubles), 1d, new Reducer<Double, Double>() {
@Override
public Double reduce(Double runningProduct, Double nextFactor) {
return runningProduct * nextFactor;
}
});
Log.d("Total product of all numbers: " + product);
}
```
#### Output
Total product of all numbers: 88.33080999999999
### linq93: Aggregate - Seed
```csharp
//c#
public void Linq93()
{
double startBalance = 100.0;
int[] attemptedWithdrawals = { 20, 10, 40, 50, 10, 70, 30 };
double endBalance =
attemptedWithdrawals.Aggregate(startBalance,
(balance, nextWithdrawal) =>
((nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance));
Console.WriteLine("Ending balance: {0}", endBalance);
}
```
```java
//java
public void linq93(){
double startBalance = 100.0;
int[] attemptedWithdrawals = new int[] { 20, 10, 40, 50, 10, 70, 30 };
double endBalance =
reduce(
toList(attemptedWithdrawals),
startBalance,
new Reducer<Integer, Double>() {
@Override
public Double reduce(Double balance, Integer nextWithdrawal) {
return (nextWithdrawal <= balance) ? (balance - nextWithdrawal) : balance;
}
}
);
Log.d("Ending balance: " + endBalance);
}
```
#### Output
Ending balance: 20.0
LINQ - Miscellaneous Operators
------------------------------
### linq94: Concat - 1
```csharp
//c#
public void Linq94()
{
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine("All numbers from both arrays:");
foreach (var n in allNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq94(){
int[] numbersA = new int[] { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = new int[] { 1, 3, 5, 7, 8 };
List<Integer> allNumbers = concat(toList(numbersA), toList(numbersB));
Log.d("All numbers from both arrays:");
for (Integer n : allNumbers){
Log.d(n);
}
}
```
#### Output
All numbers from both arrays:
0
2
4
5
6
8
9
1
3
5
7
8
### linq95: Concat - 2
```csharp
//c#
public void Linq95()
{
List<Customer> customers = GetCustomerList();
List<Product> products = GetProductList();
var customerNames =
from c in customers
select c.CompanyName;
var productNames =
from p in products
select p.ProductName;
var allNames = customerNames.Concat(productNames);
Console.WriteLine("Customer and product names:");
foreach (var n in allNames)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq95(){
List<Customer> customers = getCustomerList();
List<Product> products = getProductList();
List<String> customerNames = map(customers, new Function<Customer, String>() {
@Override
public String apply(Customer c) {
return c.companyName;
}
});
List<String> productNames = map(products, new Function<Product, String>() {
@Override
public String apply(Product p) {
return p.productName;
}
});
List<String> allNames = concat(customerNames, productNames);
Log.d("Customer and product names:");
for (String n : allNames){
Log.d(n);
}
}
```
#### Output
Customer and product names:
Alfreds Futterkiste
Ana Trujillo Emparedados y helados
Antonio Moreno Taquería
Around the Horn
Berglunds snabbköp
Blauer See Delikatessen
...
### linq96: EqualAll - 1
```csharp
//c#
public void Linq96()
{
var wordsA = new string[] { "cherry", "apple", "blueberry" };
var wordsB = new string[] { "cherry", "apple", "blueberry" };
bool match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);
}
```
```java
//java
public void linq96(){
String[] wordsA = new String[] { "cherry", "apple", "blueberry" };
String[] wordsB = new String[] { "cherry", "apple", "blueberry" };
boolean match = Arrays.equals(wordsA, wordsB);
Log.d("The sequences match: " + match);
}
```
#### Output
The sequences match: true
### linq97: EqualAll - 2
```csharp
//c#
public void Linq97()
{
var wordsA = new string[] { "cherry", "apple", "blueberry" };
var wordsB = new string[] { "apple", "blueberry", "cherry" };
bool match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);
}
```
```java
//java
public void linq97(){
String[] wordsA = new String[] { "cherry", "apple", "blueberry" };
String[] wordsB = new String[] { "cherry", "blueberry", "cherry" };
boolean match = Arrays.equals(wordsA, wordsB);
Log.d("The sequences match: " + match);
}
```
#### Output
The sequences match: false
LINQ - Query Execution
----------------------
### linq99: Deferred Execution
```csharp
//c#
public void Linq99()
{
// Sequence operators form first-class queries that
// are not executed until you enumerate over them.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q =
from n in numbers
select ++i;
// Note, the local variable 'i' is not incremented
// until each element is evaluated (as a side-effect):
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
}
```
```java
//java
public void linq099(){
final int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
final int[] i = {0};
List<FunctionResult<Integer>> q =
map(toList(numbers), new Function<Integer, FunctionResult<Integer>>() {
@Override
public FunctionResult<Integer> apply(Integer n) {
return new FunctionResult<Integer>() {
@Override
public Integer apply() {
return ++i[0];
}
};
}
});
for (FunctionResult<Integer> f : q){
Integer v = f.apply();
Log.d("v = " + v + ", i = " + i[0]);
}
}
```
#### Output
v = 1, i = 1
v = 2, i = 2
v = 3, i = 3
v = 4, i = 4
v = 5, i = 5
v = 6, i = 6
v = 7, i = 7
v = 8, i = 8
v = 9, i = 9
v = 10, i = 10
### linq100: Immediate Execution
```csharp
//c#
public void Linq100()
{
// Methods like ToList() cause the query to be
// executed immediately, caching the results.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int i = 0;
var q = (
from n in numbers
select ++i)
.ToList();
// The local variable i has already been fully
// incremented before we iterate the results:
foreach (var v in q)
{
Console.WriteLine("v = {0}, i = {1}", v, i);
}
}
```
```java
//java
public void linq100(){
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
final int[] i = {0};
List<Integer> q = map(toList(numbers), new Function<Integer, Integer>() {
@Override
public Integer apply(Integer n) {
return ++i[0];
}
});
for (Integer v : q){
Log.d("v = " + v + ", i = " + i[0]);
}
}
```
#### Output
v = 1, i = 10
v = 2, i = 10
v = 3, i = 10
v = 4, i = 10
v = 5, i = 10
v = 6, i = 10
v = 7, i = 10
v = 8, i = 10
v = 9, i = 10
v = 10, i = 10
### linq101: Query Reuse
```csharp
//c#
public void Linq101()
{
// Deferred execution lets us define a query once
// and then reuse it later after data changes.
int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNumbers =
from n in numbers
where n <= 3
select n;
Console.WriteLine("First run numbers <= 3:");
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
for (int i = 0; i < 10; i++)
{
numbers[i] = -numbers[i];
}
// During this second run, the same query object,
// lowNumbers, will be iterating over the new state
// of numbers[], producing different results:
Console.WriteLine("Second run numbers <= 3:");
foreach (int n in lowNumbers)
{
Console.WriteLine(n);
}
}
```
```java
//java
public void linq101(){
final int[] numbers = new int[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
FunctionResult<List<Integer>> lowNumbers =
new FunctionResult<List<Integer>>() {
@Override
public List<Integer> apply() {
return filter(toList(numbers), new Predicate<Integer>() {
@Override
public boolean apply(Integer n) {
return n <= 3;
}
});
}
};
Log.d("First run numbers <= 3:");
for (Integer n : lowNumbers.apply()){
Log.d(n);
}
for (int i = 0; i < 10; i++){
numbers[i] = -numbers[i];
}
Log.d("Second run numbers <= 3:");
for (Integer n : lowNumbers.apply()){
Log.d(n);
}
}
```
#### Output
First run numbers <= 3:
1
3
2
0
Second run numbers <= 3:
-5
-4
-1
-3
-9
-8
-6
-7
-2
0
LINQ - Join Operators
---------------------
### linq102: Cross Join
```csharp
//c#
public void Linq102()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}
```
```java
//java
public void linq102(){
String[] categories = new String[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = getProductList();
List<Tuple<String, String>> q =
map(
join(toList(categories), products, new Predicate2<String, Product>() {
@Override
public boolean apply(String c, Product p) {
return c.equals(p.category);
}
}),
new Function<Tuple<String, Product>, Tuple<String, String>>() {
@Override
public Tuple<String, String> apply(Tuple<String, Product> t) {
return new Tuple<>(t.A, t.B.productName);
}
}
);
for (Tuple<String,String> v : q){
Log.d(v.A + ": " + v.B);
}
}
```
#### Output
Beverages: Chai
Beverages: Chang
Beverages: Guaraná Fantástica
Beverages: Sasquatch Ale
Beverages: Steeleye Stout
Beverages: Côte de Blaye
Beverages: Chartreuse verte
Beverages: Ipoh Coffee
...
### linq103: Group Join
```csharp
//c#
public void Linq103()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category into ps
select new { Category = c, Products = ps };
foreach (var v in q)
{
Console.WriteLine(v.Category + ":");
foreach (var p in v.Products)
{
Console.WriteLine(" " + p.ProductName);
}
}
}
```
```java
//java
public void linq103(){
String[] categories = new String[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = getProductList();
List<Tuple<String,ArrayList<Product>>> q =
map(
joinGroup(toList(categories), products, new Predicate2<String, Product>() {
@Override
public boolean apply(String c, Product p) {
return c.equals(p.category);
}
}),
new Function<Group<String, Tuple<String, Product>>, Tuple<String, ArrayList<Product>>>() {
@Override
public Tuple<String, ArrayList<Product>> apply(Group<String, Tuple<String, Product>> g) {
return new Tuple<>(
g.key,
map(g.items, new Function<Tuple<String,Product>, Product>() {
@Override
public Product apply(Tuple<String, Product> t) {
return t.B;
}
})
);
}
}
);
for (Tuple<String,ArrayList<Product>> v : q){
Log.d(v.A + ":");
for (Product p : v.B){
Log.d(" " + p.productName);
}
}
}
```
#### Output
Beverages:
Chai
Chang
Guaraná Fantástica
Sasquatch Ale
Steeleye Stout
Côte de Blaye
Chartreuse verte
Ipoh Coffee
Laughing Lumberjack Lager
Outback Lager
Rhönbräu Klosterbier
Lakkalikööri
Seafood:
Ikura
Konbu
Carnarvon Tigers
Nord-Ost Matjeshering
Inlagd Sill
Gravad lax
Boston Crab Meat
Jack's New England Clam Chowder
Rogede sild
Spegesild
Escargots de Bourgogne
Röd Kaviar
...
### linq104: Cross Join with Group Join
```csharp
//c#
public void Linq104()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category into ps
from p in ps
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}
```
```java
//java
public void linq104(){
String[] categories = new String[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = getProductList();
List<Tuple<String,String>> q =
expand(
map(
joinGroup(toList(categories), products, new Predicate2<String, Product>() {
@Override
public boolean apply(String c, Product p) {
return c.equals(p.category);
}
}),
new Function<Group<String, Tuple<String, Product>>, List<Tuple<String, String>>>() {
@Override
public List<Tuple<String, String>> apply(Group<String, Tuple<String, Product>> g) {
return map(g.items, new Function<Tuple<String, Product>, Tuple<String, String>>() {
@Override
public Tuple<String, String> apply(Tuple<String, Product> t) {
return new Tuple<>(t.A, t.B.productName);
}
});
}
}
)
);
for (Tuple<String,String> v : q){
Log.d(v.B + ": " + v.A);
}
}
```
#### Output
Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Ikura: Seafood
Konbu: Seafood
Carnarvon Tigers: Seafood
...
### linq105: Left Outer Join
```csharp
//c#
public void Linq105()
{
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
List<Product> products = GetProductList();
var q =
from c in categories
join p in products on c equals p.Category into ps
from p in ps.DefaultIfEmpty()
select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
}
```
```java
//java
public void linq105(){
String[] categories = new String[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
final List<Product> products = getProductList();
List<Tuple<String,String>> q =
expand(
map(toList(categories), new Function<String, List<Tuple<String, String>>>() {
@Override
public List<Tuple<String, String>> apply(final String c) {
List<Product> catProducts = filter(products, new Predicate<Product>() {
@Override
public boolean apply(Product p) {
return c.equals(p.category);
}
});
return catProducts.isEmpty()
? toList(new Tuple<>(c, "(No products)"))
: map(catProducts, new Function<Product, Tuple<String, String>>() {
@Override
public Tuple<String, String> apply(Product p) {
return new Tuple<>(c, p.productName);
}
});
}
})
);
for (Tuple<String,String> v : q){
Log.d(v.B + ": " + v.A);
}
}
```
#### Output
Chai: Beverages
Chang: Beverages
Guaraná Fantástica: Beverages
Sasquatch Ale: Beverages
Steeleye Stout: Beverages
Côte de Blaye: Beverages
Chartreuse verte: Beverages
Ipoh Coffee: Beverages
Laughing Lumberjack Lager: Beverages
Outback Lager: Beverages
Rhönbräu Klosterbier: Beverages
Lakkalikööri: Beverages
Aniseed Syrup: Condiments
Chef Anton's Cajun Seasoning: Condiments
Chef Anton's Gumbo Mix: Condiments
Grandma's Boysenberry Spread: Condiments
Northwoods Cranberry Sauce: Condiments
Genen Shouyu: Condiments
Gula Malacca: Condiments
Sirop d'érable: Condiments
Vegie-spread: Condiments
Louisiana Fiery Hot Pepper Sauce: Condiments
Louisiana Hot Spiced Okra: Condiments
Original Frankfurter grüne Soße: Condiments
(No products): Vegetables
...
### Contributors
- [mythz](https://github.com/mythz) (Demis Bellot)
| 0 |
cdklabs/aws-cdk-testing-examples | null | null | ## AWS CDK Testing Examples
This repository contains code examples in Python, Java, and TypeScript for the
Testing CDK Applications in Any Language blog post. These examples use the new
`assertions` module to unit test various parts of a CDK application.
To try these examples out yourself, follow the instructions for your language
in the [Getting started with the AWS CDK developer
guide](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html), then
run the commands listed in the README.md of the appropriate subdirectory
(i.e. java/, python/, or typescript/).
For more information on the `assertions` module, refer to the [API
reference](https://docs.aws.amazon.com/cdk/api/latest/docs/assertions-readme.html).
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## License
This library is licensed under the MIT-0 License. See the LICENSE file.
| 0 |
grro/stability | code examples | null | null | 0 |
Jerady/fontawesomefx-examples | null | null | # FontAwesomeFX Examples and Demo Applications
[Get the code here](https://github.com/Jerady/fontawesomefx-demoapps)
## Basic Usage
```
FontAwesomeIconView fontAwesomeIconView =
new FontAwesomeIconView(FontAwesomeIcon.ANGELLIST);
```

```
MaterialDesignIconView materialDesignIconView =
new MaterialDesignIconView(MaterialDesignIcon.THUMB_UP);
materialDesignIconView.setSize("4em");
```
### Run BasicGlyphsApp demo
`./gradlew -PmainClass=de.jensd.fx.glyphs.demo.apps.BasicGlyphsApp execute`
## Basic Usage using Factories
```
Text fontAwesomeIcon =
FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.ANGELLIST);
root.getChildren().add(fontAwesomeIcon);
```
```
Text materialDesignIcon =
MaterialDesignIconFactory.get().createIcon(MaterialDesignIcon.CHECK_ALL, "4em");
root.getChildren().add(materialDesignIcon);
```
### Run BasicGlyphsFactoryApp demo
`./gradlew -PmainClass=de.jensd.fx.glyphs.demo.apps.BasicGlyphsApp execute`
## CSS Styled Glyphs
```
FontAwesomeIconView thumbsUpIcon = new FontAwesomeIconView();
thumbsUpIcon.setStyleClass("thumbs-up-icon");
root.getChildren().add(thumbsUpIcon);
```
```
FontAwesomeIconView thumbsDownIcon = new FontAwesomeIconView();
thumbsDownIcon.setStyleClass("thumbs-down-icon");
root.getChildren().add(thumbsDownIcon);
```
```
WeatherIconView blueskyIcon = new WeatherIconView();
blueskyIcon.setStyleClass("bluesky-icon");
root.getChildren().add(blueskyIcon);
```

####styles/glyphs.css
```
.root{
-icons-color: black;
}
.glyph-icon{
-fx-text-fill: -icons-color;
-fx-fill: -icons-color;
-glyph-size: 48px;
}
.glyph-icon:hover{
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.2), 4, 0, 0, 0);
}
.bluesky-icon{
-glyph-name: "CLOUD";
-icons-color: blue;
-fx-fill: linear-gradient(-icons-color 0%,
derive(-icons-color, 100%) 30%, derive(blueviolet, 30%) 85%);
}
.bluesky-icon:hover{
-glyph-name: "CLOUDY";
-icons-color: yellowgreen;
-fx-effect: dropshadow(three-pass-box,
rgba(156,115,241,0.6), 10, 0, 0, 0);
}
.bluesky-icon:pressed{
-glyph-name: "DAY_CLOUDY";
-icons-color: yellow;
-fx-effect: dropshadow(three-pass-box,
rgba(0,0,0,1.0), 10, 0, 0, 0);
}
.thumbs-up-icon{
-glyph-name: "THUMBS_UP";
-icons-color: yellowgreen;
}
.thumbs-up-icon:hover{
-fx-effect: dropshadow(three-pass-box, rgba(154,205,55,0.7), 10, 0, 0, 0);
}
.thumbs-up-icon:pressed{
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,1.0), 10, 0, 0, 0);
}
.thumbs-down-icon{
-glyph-name: "THUMBS_DOWN";
-icons-color: red;
}
.thumbs-down-icon:hover{
-fx-effect: dropshadow(three-pass-box, rgba(255,0,0,0.7), 10, 0, 0, 0);
}
.thumbs-down-icon:pressed{
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,1.0), 10, 0, 0, 0);
}
.android-icon{
-icons-color: yellowgreen;
-fx-fill: linear-gradient(-icons-color 0%, derive(yellowgreen, 30%) 85%);
-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,1.0), 10, 0, 0, 0);
}
```

### Run CssStyledGlyphsApp demo
`./gradlew -PmainClass=de.jensd.fx.glyphs.demo.apps.CssStyledGlyphsApp execute`
## CSS Styled Glyphs using Factories
```
Text thumbsUpIcon =
FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.THUMBS_UP, "4em");
thumbsUpIcon.getStyleClass().add("thumbs-up-icon");
root.getChildren().add(thumbsUpIcon);
```
```
Text thumbsDownIcon =
FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.THUMBS_DOWN, "4em");
thumbsDownIcon.getStyleClass().add("thumbs-down-icon");
root.getChildren().add(thumbsDownIcon);
```
```
Text blueskyIcon =
WeatherIconFactory.get().createIcon(WeatherIcon.CLOUDY, "4em");
blueskyIcon.getStyleClass().add("bluesky-icon");
root.getChildren().add(blueskyIcon);
```
### Run CssStylesBasicGlyphsFactoryApp demo
`./gradlew -PmainClass=de.jensd.fx.glyphs.demo.apps. CssStylesBasicGlyphsFactoryApp execute` | 0 |
lokeshgupta1981/Spring-Boot3-Demos | Spring Boot 3 Demo Projects and Examples | null | # Spring Boot3 Demos
Spring Boot 3 Demo Projects and Examples
| 0 |
vitaly-chibrikov/tp_java_2015_02 | Code examples for course Java Programming" in https://tech-mail.ru/" | null | # tp_java_2015_02
Code examples for course "Java Programming" in https://tech-mail.ru/
| 0 |
foo4u/keycloak-spring-demo | Examples demonstrating how to use the Keycloak Spring Security adapter | null | # Keycloak Spring Security Examples
Demonstrates how to use the Keycloak Spring Security adapter, including:
* Login
* Distributed SSO
* Distributed Logout
* OAuth2 Bearer Tokens
## Requirements
The following examples are standalone Spring Boot applications.
They require the Keycloak appliance 1.2.0, running locally on port 8080 (the default for the
standalone appliance).
There are multiple Spring Boot projects. These will all run on independently on the localhost
listening on differnt ports.
* **customer-app** A Spring Boot application that does remote login using OAuth2 browser redirects with the auth server
* **product-app** A Spring Boot application that does remote login using OAuth2 browser redirects with the auth server
* **database-service** A Spring Boot RESTful application service authenticated by bearer tokens only. The customer and product app invoke it to get data.
### Step 1: Make sure you've set up the Keycloak Server
The Keycloak Appliance Distribution comes with a preconfigured Keycloak server (based on Wildfly). You must use it this server to run the Spring Security demos.
### Step 2: Boot Keycloak Server
Where you go to start up the Keycloak Server depends on which distro you installed.
From appliance:
```
$ cd keycloak/bin
$ ./standalone.sh
```
### Step 3: Import the Test Realm
Import the test realm for the demo. Clicking on the below link will bring you to the
create realm page in the Admin UI. The username/password is admin/admin to login in. Keycloak will ask you to create a new admin password before you can go to the create
realm page.
http://localhost:8080/auth/admin/master/console/#/create/realm
Import the spring-demo-realm.json file that is in this project's root directory.
### Step 4: Build and deploy
Launch each application (use a new terminal for each application):
```
$ ./gradlew database-service:bootRun
$ ./gradlew customer-app:bootRun
$ ./gradlew product-app:bootRun
```
### Step 5: Login and Observe Apps
Try going to the customer app and view customer data:
http://localhost:9092/customer-portal/
This should take you to the auth-server login screen. Enter username: srossillo and password: password.
If you click on the products link, you'll be taken to the products app and show a product listing. The redirects
are still happening, but the auth-server knows you are already logged in so the login is bypassed.
If you click on the logout link of either of the product or customer app, you'll be logged out of all the applications.
## Admin Console
http://localhost:8080/auth/admin/index.html
| 0 |
ddd-by-examples/factory | The missing, complete example of Domain-Driven Design enterprise application backed by Spring stack | aggregate cqrs crud domain-driven-design domain-events domain-knowledge domain-model enterprise-applications event-storming hexagon invariants ports-and-adapters | # The missing, complete example of Domain-Driven Design enterprise application
[](https://opensource.org/licenses/MIT)
[](https://travis-ci.org/ddd-by-examples/factory)
[](https://codecov.io/gh/ddd-by-examples/factory)
## Command Query CRUD Responsibility Segregation
Not every piece of software is equally important...
Not every piece will decide about company / product success or can cause not reversible
negative business consequences like materialise brand risk or money loses.
On the other hand scalability or non functional requirements are different for different activities in software.
To accommodate to those differences, separate architectural patterns are applied:

**Simple Create Read Update Delete functionality** are exposed with leverage of CRUD framework.
Goals of that approach:
- fast initial development,
- fast respond to typical changes (ex. „please add another 2 fields on UI”),
- exposure of high quality API.
Examples in code:
- CRUD-able document [ProductDescription](product-management-adapters/src/main/java/io/dddbyexamples/factory/product/management/ProductDescription.java)
- persistence of document [ProductDescriptionEntity](product-management-adapters/src/main/java/io/dddbyexamples/factory/product/management/ProductDescriptionEntity.java)
- CRUD exposed as DAO and REST endpoint [ProductDescriptionDao](product-management-adapters/src/main/java/io/dddbyexamples/factory/product/management/ProductDescriptionDao.java)
**Complex Commands (business processing)** expressed in Domain Model which is embedded in hexagonal architecture.
Goals of that approach:
- enable approach with implementing the Domain Model in the first place, by adding infrastructure adapters later,
- keeping the Domain Model as simple as possible by protecting it from accidental complexity
caused by technological choices or transport models from external services / contexts,
- make the core business of application technology agnostic, enabling continues technology
migration and keeping long living projects up to date with fast evolving frameworks and libraries.
Examples of Domain Model in code:
- aggregate [ProductDemand](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/ProductDemand.java)
- entity [DailyDemand](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/DailyDemand.java)
- value object [Adjustment](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/Adjustment.java)
- policy [ReviewPolicy](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/ReviewPolicy.java)
- domain event [DemandedLevelsChanged](shared-kernel-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/DemandedLevelsChanged.java)
Examples of Ports in code:
- application service (primary port) [DemandService](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/DemandService.java)
- repository (secondary port) [ProductDemandRepository](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/ProductDemandRepository.java)
- domain events handling (secondary port) [DemandEvents](demand-forecasting-model/src/main/java/io/dddbyexamples/factory/demand/forecasting/DemandEvents.java)
Examples of Adapters in code:
- REST endpoint for complex command (driving adapter)
- command resource [DemandAdjustmentDao](demand-forecasting-adapters/src/main/java/io/dddbyexamples/factory/demand/forecasting/command/DemandAdjustmentDao.java)
- command handler [CommandsHandler](demand-forecasting-adapters/src/main/java/io/dddbyexamples/factory/demand/forecasting/command/CommandsHandler.java)
- repository implementation (driven adapter) [ProductDemandORMRepository](demand-forecasting-adapters/src/main/java/io/dddbyexamples/factory/demand/forecasting/ProductDemandORMRepository.java)
- events propagation (driven adapter) [DemandEventsPropagation](app-monolith/src/main/java/io/dddbyexamples/factory/demand/forecasting/DemandEventsPropagation.java)
**Complex Query** implemented as direct and simple as possible by:
- fetching persistent read model expected by consumer, the read model is a projection of past domain event,
- read model composed at query execution time build directly from persistent form of Domain Model,
- mix of above: read model composed at query execution time build from pre-calculated persistent projections of domain event.
Additional complex calculations or projections can be partially delegated to the Domain Model if desired.
Goals of that approach:
- encapsulation of the Domain Model complexity by providing (simpler) consumer driven or published language API,
- freeing the Domain Model from exposing data for reads making the Domain Model simpler,
- improves reads performance and enable horizontal scalability.
Examples in code:
- projection of domain events to persistent read model [DeliveryForecastProjection](demand-forecasting-adapters/src/main/java/io/dddbyexamples/factory/delivery/planning/projection/DeliveryForecastProjection.java)
- REST endpoint for persistent read model [DeliveryForecastDao](demand-forecasting-adapters/src/main/java/io/dddbyexamples/factory/delivery/planning/projection/DeliveryForecastDao.java)
- read model composed at query execution time [StockForecastQuery](app-monolith/src/main/java/io/dddbyexamples/factory/stock/forecast/StockForecastQuery.java)
- REST resource processor for NOT persistent read model [StockForecastResourceProcessor](app-monolith/src/main/java/io/dddbyexamples/factory/stock/forecast/ressource/StockForecastResourceProcessor.java)
## Hexagonal Architecture
Only the most valuable part of that enterprise software is embedded in hexagonal architecture -
complex business processing modeled in form of the Domain Model.

**Application Services** - providing entry point to Domain Model functionality,
Application Services are ports for Primary / Driving Adapters like RESTfull endpoints.
**Domain Model** - Object Oriented (in that case) piece of software modeling business rules, invariants,
calculations and processing variants.
Thanks to hexagon can be as clean and simple as possible - separating essential complexity of pure business
from accidental complexity of technical choices, free of technical and convention constraints.
**Ports** - contract defined by Domain Model expressing expectations from external resources (services, database or other models).
Declared interfaces alongside with IN-OUT parameters are Ports for Secondary / Driven Adapters like repository implementation.
**Adapters** - integration of the technology (REST, database, external services, etc.) with the Domain Model.
Making useful application from the Domain Model and the technology.
## Implementing Domain Model in the first place
In most projects the biggest risk is lack of domain knowledge among developers. We all known Java,
databases and bunch of handy frameworks, but what about: Investment Banking, Automotive Manufacturing or even e-Commerce.
Let's face the risk at first, maintain and explore domain knowledge
with **Model Exploration Whirlpool** and build **Ubiquitous Language** with your executable **Domain Model**,
**Domain Stories** and **Specification by Examples** from day one.
Adding infrastructure and technology later is easy thanks to Hexagonal Architecture.
Simply starting from ZERO business knowledge through initial domain and opportunity exploration with **Big Picture Event Storming**:

after cleaning and trimming initial model to most valuable and needed areas:

Deep dive in **Demand Forecasting** sub-domain with **Design Level Event Storming**:

is excellent canvas to cooperative exploration of:
- impacted and required actors,
- initial / desired system boundaries,
- actors interactions with system under design.
With use of **Domain Stories** and **Specification by Examples** it is easy to find:
- business rules and invariants,
- acceptance criteria,
- estimation of Domain Model depth,
- CRUD-suspected activities,
- missing parts.
| 1 |
sunrenjie/jpwh-2e-examples | Sample code from the book Java Persistence with Hibernate, Second Edition | null | null | 1 |
shoothzj/pulsar-client-examples | null | null | # pulsar-client-examples
描述了一些Pulsar客户端编码相关的最佳实践,并提供了可商用的样例代码,供大家研发的时候参考,提升大家接入Pulsar的效率。在生产环境上,Pulsar的地址信息往往都通过配置中心或者是k8s域名发现的方式获得,这块不是这篇文章描述的重点,以`PulsarConstant.SERVICE_HTTP_URL`代替。本文中的例子均已上传到[github](https://github.com/Shoothzj/pulsar-client-examples)
## Client初始化和配置
### 初始化Client--demo级别
```java
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClient;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarClientInit {
private static final PulsarClientInit INSTANCE = new PulsarClientInit();
private PulsarClient pulsarClient;
public static PulsarClientInit getInstance() {
return INSTANCE;
}
public void init() throws Exception {
pulsarClient = PulsarClient.builder()
.serviceUrl(PulsarConstant.SERVICE_HTTP_URL)
.build();
}
public PulsarClient getPulsarClient() {
return pulsarClient;
}
}
```
demo级别的Pulsar client初始化的时候没有配置任何自定义参数,并且初始化的时候没有考虑异常,`init`的时候会直接抛出异常。
### 初始化Client--可上线级别
```java
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClient;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarClientInitRetry {
private static final PulsarClientInitRetry INSTANCE = new PulsarClientInitRetry();
private volatile PulsarClient pulsarClient;
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new DefaultThreadFactory("pulsar-cli-init"));
public static PulsarClientInitRetry getInstance() {
return INSTANCE;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
try {
pulsarClient = PulsarClient.builder()
.serviceUrl(PulsarConstant.SERVICE_HTTP_URL)
.build();
log.info("pulsar client init success");
this.executorService.shutdown();
} catch (Exception e) {
log.error("init pulsar error, exception is ", e);
}
}
public PulsarClient getPulsarClient() {
return pulsarClient;
}
}
```
在实际的环境中,我们往往要做到`pulsar client`初始化失败后不影响微服务的启动,即待微服务启动后,再一直重试创建`pulsar client`。<br/>
上面的代码示例通过`volatile`加不断循环重建实现了这一目标,并且在客户端成功创建后,销毁了定时器线程。
### 初始化Client--商用级别
```java
import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.SizeUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarClientInitUltimate {
private static final PulsarClientInitUltimate INSTANCE = new PulsarClientInitUltimate();
private volatile PulsarClient pulsarClient;
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, new DefaultThreadFactory("pulsar-cli-init"));
public static PulsarClientInitUltimate getInstance() {
return INSTANCE;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
try {
pulsarClient = PulsarClient.builder()
.serviceUrl(PulsarConstant.SERVICE_HTTP_URL)
.ioThreads(4)
.listenerThreads(10)
.memoryLimit(64, SizeUnit.MEGA_BYTES)
.operationTimeout(5, TimeUnit.SECONDS)
.connectionTimeout(15, TimeUnit.SECONDS)
.build();
log.info("pulsar client init success");
this.executorService.shutdown();
} catch (Exception e) {
log.error("init pulsar error, exception is ", e);
}
}
public PulsarClient getPulsarClient() {
return pulsarClient;
}
}
```
商用级别的`Pulsar Client`新增了5个配置参数:
- **ioThreads** netty的ioThreads负责网络IO操作,如果业务流量较大,可以调高`ioThreads`个数;
- **listenersThreads** 负责调用以`listener`模式启动的消费者的回调函数,建议配置大于该client负责的`partition`数目;
- **memoryLimit** 当前用于限制`pulsar`生产者可用的最大内存,可以很好地防止网络中断、pulsar故障等场景下,消息积压在`producer`侧,导致java程序OOM;
- **operationTimeout** 一些元数据操作的超时时间,Pulsar默认为30s,有些保守,可以根据自己的网络情况、处理性能来适当调低;
- **connectionTimeout** 连接Pulsar的超时时间,配置原则同上。
### 客户端进阶参数(内存分配相关)
我们还可以通过传递java的property来控制Pulsar客户端内存分配的参数,这里列举几个重要参数
- **pulsar.allocator.pooled** 为true则使用堆外内存池,false则使用堆内存分配,不走内存池。默认使用高效的堆外内存池
- **pulsar.allocator.exit_on_oom** 如果内存溢出,是否关闭**jvm**,默认为false
- **pulsar.allocator.out_of_memory_policy** 在https://github.com/apache/pulsar/pull/12200 引入,用于配置当堆外内存不够使用时的行为,可选项为`FallbackToHeap`和`ThrowException`,默认为`FallbackToHeap`,如果你不希望消息序列化的内存影响到堆内存分配,则可以配置成`ThrowException`
## 生产者
### 初始化producer重要参数
#### maxPendingMessages
生产者消息发送队列,根据实际topic的量级合理配置,避免在网络中断、Pulsar故障场景下的OOM。建议和client侧的配置`memoryLimit`之间挑一个进行配置。
### messageRoutingMode
消息路由模式。默认为`RoundRobinPartition`。根据业务需求选择,如果需要保序,通常的做法是在向`Pulsar`发送消息时传递`key`值,这时就会根据`key`来选择要发送到的`partition`。如果有更复杂的保序场景,也可以自定义分发partition的策略。
#### autoUpdatePartition
自动更新partition信息。如`topic`中`partition`信息不变则不需要配置,降低集群的消耗。
#### batch相关参数
因为批量发送模式底层由定时任务实现,如果该topic上消息数较小,则不建议开启`batch`。尤其是大量的低时间间隔的定时任务会导致netty线程CPU飙高。
- **enableBatching** 是否启用批量发送
- **batchingMaxMessages** 批量发送最大消息条数
- **batchingMaxPublishDelay** 批量发送定时任务间隔
### 静态producer初始化
静态producer,指不会随着业务的变化进行producer的启动或关闭。那么就在微服务启动完成、client初始化完成之后,初始化producer,样例如下:
#### 一个生产者一个线程,适用于生产者数目较少的场景
```java
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.Producer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarStaticProducerInit {
private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-producer-init").build();
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, threadFactory);
private final String topic;
private volatile Producer<byte[]> producer;
public PulsarStaticProducerInit(String topic) {
this.topic = topic;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
try {
final PulsarClientInit instance = PulsarClientInit.getInstance();
producer = instance.getPulsarClient().newProducer().topic(topic).create();
executorService.shutdown();
} catch (Exception e) {
log.error("init pulsar producer error, exception is ", e);
}
}
public Producer<byte[]> getProducer() {
return producer;
}
}
```
#### 多个生产者一个线程,适用于生产者数目较多的场景
```java
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.Producer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarStaticProducersInit {
private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-producers-init").build();
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, threadFactory);
private final Map<String, Producer<byte[]>> producerMap = new ConcurrentHashMap<>();
private int initIndex = 0;
private final List<String> topics;
public PulsarStaticProducersInit(List<String> topics) {
this.topics = topics;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
if (initIndex == topics.size()) {
executorService.shutdown();
return;
}
for (; initIndex < topics.size(); initIndex++) {
try {
final PulsarClientInit instance = PulsarClientInit.getInstance();
final Producer<byte[]> producer = instance.getPulsarClient().newProducer().topic(topics.get(initIndex)).create();
producerMap.put(topics.get(initIndex), producer);
} catch (Exception e) {
log.error("init pulsar producer error, exception is ", e);
break;
}
}
}
public Producer<byte[]> getProducers(String topic) {
return producerMap.get(topic);
}
}
```
### 动态生成销毁的producer示例
还有一些业务,我们的producer可能会根据业务来进行动态的启动或销毁,如接收道路上车辆的数据,并发送给指定的topic。我们不会让内存里面驻留所有的producer,这会导致占用大量的内存,我们可以采用类似于LRU Cache的方式来管理producer的生命周期。
```java
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarDynamicProducerFactory {
/**
* topic -- producer
*/
private AsyncLoadingCache<String, Producer<byte[]>> producerCache;
public PulsarDynamicProducerFactory() {
this.producerCache = Caffeine.newBuilder()
.expireAfterAccess(600, TimeUnit.SECONDS)
.maximumSize(3000)
.removalListener((RemovalListener<String, Producer<byte[]>>) (topic, value, cause) -> {
log.info("topic {} cache removed, because of {}", topic, cause);
try {
value.close();
} catch (Exception e) {
log.error("close failed, ", e);
}
})
.buildAsync(new AsyncCacheLoader<>() {
@Override
public CompletableFuture<Producer<byte[]>> asyncLoad(String topic, Executor executor) {
return acquireFuture(topic);
}
@Override
public CompletableFuture<Producer<byte[]>> asyncReload(String topic, Producer<byte[]> oldValue,
Executor executor) {
return acquireFuture(topic);
}
});
}
private CompletableFuture<Producer<byte[]>> acquireFuture(String topic) {
CompletableFuture<Producer<byte[]>> future = new CompletableFuture<>();
try {
ProducerBuilder<byte[]> builder = DemoPulsarClientInit.getInstance().getPulsarClient().newProducer().enableBatching(true);
final Producer<byte[]> producer = builder.topic(topic).create();
future.complete(producer);
} catch (Exception e) {
log.error("create producer exception ", e);
future.completeExceptionally(e);
}
return future;
}
}
```
这个模式下,可以根据返回的`CompletableFuture<Producer<byte[]>>`来优雅地进行流式处理。
### 可以接受消息丢失的发送
```java
public void sendMsg(String topic, byte[] msg) {
final CompletableFuture<Producer<byte[]>> cacheFuture = producerCache.get(topic);
cacheFuture.whenComplete((producer, e) -> {
if (e != null) {
log.error("create pulsar client exception ", e);
return;
}
try {
producer.sendAsync(msg).whenComplete(((messageId, throwable) -> {
if (throwable == null) {
log.info("topic {} send success, msg id is {}", topic, messageId);
return;
}
log.error("send producer msg error ", throwable);
}));
} catch (Exception ex) {
log.error("send async failed ", ex);
}
});
}
```
以上为正确处理`Client`创建失败和发送失败的回调函数。但是由于在生产环境下,pulsar并不是一直保持可用的,会因为虚拟机故障、pulsar服务升级等导致发送失败。这个时候如果要保证消息发送成功,就需要对消息发送进行重试。
### 可以容忍极端场景下的发送丢失
```java
private final Timer timer = new HashedWheelTimer();
public void sendMsgWithRetry(String topic, byte[] msg, int retryTimes, int maxRetryTimes) {
final CompletableFuture<Producer<byte[]>> cacheFuture = producerCache.get(topic);
cacheFuture.whenComplete((producer, e) -> {
if (e != null) {
log.error("create pulsar client exception ", e);
return;
}
try {
producer.sendAsync(msg).whenComplete(((messageId, throwable) -> {
if (throwable == null) {
log.info("topic {} send success, msg id is {}", topic, messageId);
return;
}
if (retryTimes < maxRetryTimes) {
log.warn("topic {} send failed, begin to retry {} times exception is ", topic, retryTimes, throwable);
timer.newTimeout(timeout -> PulsarDynamicProducerFactory.this.sendMsgWithRetry(topic, msg, retryTimes + 1, maxRetryTimes), 1L << retryTimes, TimeUnit.SECONDS);
}
log.error("send producer msg error ", throwable);
}));
} catch (Exception ex) {
log.error("send async failed ", ex);
}
});
}
```
这里在发送失败后,做了退避重试,可以容忍`pulsar`服务端故障一段时间。比如退避7次、初次间隔为1s,那么就可以容忍`1+2+4+8+16+32+64=127s`的故障。这已经足够满足大部分生产环境的要求了。<br/>
因为理论上存在超过127s的故障,所以还是要在极端场景下,向上游返回失败。
### 生产者Partition级别严格保序
生产者严格保序的要点:一次只发送一条消息,确认发送成功后再发送下一条消息。实现上可以使用同步异步两种模式:
- 同步模式的要点就是循环发送,直到上一条消息发送成功后,再启动下一条消息发送
- 异步模式的要点是观测上一条消息发送的future,如果失败也一直重试,成功则启动下一条消息发送
值得一提的是,这个模式下,partition间是可以并行的,可以使用`OrderedExecutor`或`per partition per thread`
同步模式举例:
```java
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.client.api.Producer;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarProducerSyncStrictlyOrdered {
Producer<byte[]> producer;
public void sendMsg(byte[] msg) {
while (true) {
try {
final MessageId messageId = producer.send(msg);
log.info("topic {} send success, msg id is {}", producer.getTopic(), messageId);
break;
} catch (Exception e) {
log.error("exception is ", e);
}
}
}
}
```
## 消费者
### 初始化消费者重要参数
#### receiverQueueSize
注意:处理不过来时,消费缓冲队列会积压在内存中,合理配置防止OOM。如果服务的CPU比较健康,但是性能上不来,同时`receiverQueueSize`配置地也相对较小(如小于2*TPS),那么就可以考虑增大`receiverQueueSize`。
#### autoUpdatePartition
自动更新partition信息。如`topic`中`partition`信息不变则不需要配置,降低集群的消耗。
#### subscriptionType
订阅类型,根据业务需求决定。
#### subscriptionInitialPosition
订阅开始的位置,根据业务需求决定放到最前或者最后。
#### messageListener
使用listener模式消费,只需要提供回调函数,不需要主动执行`receive()`拉取。一般没有特殊诉求,建议采用listener模式。
#### ackTimeout
当服务端推送消息,但消费者未及时回复ack,经过ackTimeout后,会重新推送给消费者处理,即`redeliver`机制。<br/>
注意在利用`redeliver`机制的时候,一定要注意仅仅使用重试机制来重试可恢复的错误。举个例子,如果代码里面对消息进行解码,解码失败就不适合利用`redeliver`机制。这会导致客户端一直处于重试之中。
如果拿捏不准,还可以通过下面的`deadLetterPolicy`配置死信队列,防止消息一直重试。
#### negativeAckRedeliveryDelay
当客户端调用`negativeAcknowledge`时,触发`redeliver`机制的时间。`redeliver`机制的注意点同`ackTimeout`。
需要注意的是, `ackTimeout`和`negativeAckRedeliveryDelay`建议不要同时使用,一般建议使用`negativeAck`,用户可以有更灵活的控制权。一旦`ackTimeout`配置的不合理,在消费时间不确定的情况下可能会导致消息不必要的重试。
#### deadLetterPolicy
配置`redeliver`的最大次数和死信topic。
### 初始化消费者原则
消费者只有创建成功才能工作,不像生产者可以向上游返回失败,所以消费者要一直重试创建。示例代码如下:
注意:消费者和topic可以是一对多的关系,消费者可以订阅多个topic。
#### 一个消费者一个线程,适用于消费者数目较少的场景
```java
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.Consumer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarConsumerInit {
private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-consumer-init").build();
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, threadFactory);
private final String topic;
private volatile Consumer<byte[]> consumer;
public PulsarConsumerInit(String topic) {
this.topic = topic;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
try {
final PulsarClientInit instance = PulsarClientInit.getInstance();
consumer = instance.getPulsarClient().newConsumer().topic(topic).messageListener(new DummyMessageListener<>()).subscribe();
executorService.shutdown();
} catch (Exception e) {
log.error("init pulsar producer error, exception is ", e);
}
}
public Consumer<byte[]> getConsumer() {
return consumer;
}
}
```
#### 多个消费者一个线程,适用于消费者数目较多的场景
```java
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.client.api.Consumer;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* @author hezhangjian
*/
@Slf4j
public class PulsarConsumersInit {
private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("pulsar-consumers-init").build();
private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1, threadFactory);
private final Map<String, Consumer<byte[]>> consumerMap = new ConcurrentHashMap<>();
private int initIndex = 0;
private final List<String> topics;
public PulsarConsumersInit(List<String> topics) {
this.topics = topics;
}
public void init() {
executorService.scheduleWithFixedDelay(this::initWithRetry, 0, 10, TimeUnit.SECONDS);
}
private void initWithRetry() {
if (initIndex == topics.size()) {
executorService.shutdown();
return;
}
for (; initIndex < topics.size(); initIndex++) {
try {
final PulsarClientInit instance = PulsarClientInit.getInstance();
final Consumer<byte[]> consumer = instance.getPulsarClient().newConsumer().topic(topics.get(initIndex)).messageListener(new DummyMessageListener<>()).subscribe();
consumerMap.put(topics.get(initIndex), consumer);
} catch (Exception e) {
log.error("init pulsar producer error, exception is ", e);
break;
}
}
}
public Consumer<byte[]> getConsumer(String topic) {
return consumerMap.get(topic);
}
}
```
### 消费者达到至少一次语义
使用手动回复ack模式,确保处理成功后再ack。如果处理失败可以自己重试或通过`negativeAck`机制进行重试
#### 同步模式举例
这里需要注意,如果处理消息时长差距比较大,同步处理的方式可能会让本来可以很快处理的消息得不到处理的机会。
```java
/**
* @author hezhangjian
*/
@Slf4j
public class MessageListenerSyncAtLeastOnce<T> implements MessageListener<T> {
@Override
public void received(Consumer<T> consumer, Message<T> msg) {
try {
final boolean result = syncPayload(msg.getData());
if (result) {
consumer.acknowledgeAsync(msg);
} else {
consumer.negativeAcknowledge(msg);
}
} catch (Exception e) {
// 业务方法可能会抛出异常
log.error("exception is ", e);
consumer.negativeAcknowledge(msg);
}
}
/**
* 模拟同步执行的业务方法
* @param msg 消息体内容
* @return
*/
private boolean syncPayload(byte[] msg) {
return System.currentTimeMillis() % 2 == 0;
}
}
```
#### 异步模式举例
异步的话需要考虑内存的限制,因为异步的方式可以很快地从`broker`消费,不会被业务操作阻塞,这样 **inflight** 的消息可能会非常多。如果是`Shared`或`KeyShared`模式,可以通过`maxUnAckedMessage`进行限制。如果是`Failover`模式,可以通过下面的`消费者繁忙时阻塞拉取消息,不再进行业务处理`通过判断**inflight**消息数来阻塞处理。
```java
/**
* @author hezhangjian
*/
@Slf4j
public class MessageListenerAsyncAtLeastOnce<T> implements MessageListener<T> {
@Override
public void received(Consumer<T> consumer, Message<T> msg) {
try {
asyncPayload(msg.getData(), new DemoSendCallback() {
@Override
public void callback(Exception e) {
if (e == null) {
consumer.acknowledgeAsync(msg);
} else {
log.error("exception is ", e);
consumer.negativeAcknowledge(msg);
}
}
});
} catch (Exception e) {
// 业务方法可能会抛出异常
consumer.negativeAcknowledge(msg);
}
}
/**
* 模拟异步执行的业务方法
* @param msg 消息体
* @param sendCallback 异步函数的callback
*/
private void asyncPayload(byte[] msg, DemoSendCallback sendCallback) {
if (System.currentTimeMillis() % 2 == 0) {
sendCallback.callback(null);
} else {
sendCallback.callback(new Exception("exception"));
}
}
}
```
### 消费者繁忙时阻塞拉取消息,不再进行业务处理
当消费者处理不过来时,通过阻塞`listener`方法,不再进行业务处理。避免在微服务积累太多消息导致OOM,可以通过RateLimiter或者Semaphore控制处理。
```java
/**
* @author hezhangjian
*/
@Slf4j
public class MessageListenerBlockListener<T> implements MessageListener<T> {
/**
* Semaphore保证最多同时处理500条消息
*/
private final Semaphore semaphore = new Semaphore(500);
@Override
public void received(Consumer<T> consumer, Message<T> msg) {
try {
semaphore.acquire();
asyncPayload(msg.getData(), new DemoSendCallback() {
@Override
public void callback(Exception e) {
semaphore.release();
if (e == null) {
consumer.acknowledgeAsync(msg);
} else {
log.error("exception is ", e);
consumer.negativeAcknowledge(msg);
}
}
});
} catch (Exception e) {
semaphore.release();
// 业务方法可能会抛出异常
consumer.negativeAcknowledge(msg);
}
}
/**
* 模拟异步执行的业务方法
* @param msg 消息体
* @param sendCallback 异步函数的callback
*/
private void asyncPayload(byte[] msg, DemoSendCallback sendCallback) {
if (System.currentTimeMillis() % 2 == 0) {
sendCallback.callback(null);
} else {
sendCallback.callback(new Exception("exception"));
}
}
}
```
### 消费者严格按partition保序
为了实现`partition`级别消费者的严格保序,需要对单`partition`的消息,一旦处理失败,在这条消息重试成功之前不能处理该`partition`的其他消息。示例如下:
```java
/**
* @author hezhangjian
*/
@Slf4j
public class MessageListenerSyncAtLeastOnceStrictlyOrdered<T> implements MessageListener<T> {
@Override
public void received(Consumer<T> consumer, Message<T> msg) {
retryUntilSuccess(msg.getData());
consumer.acknowledgeAsync(msg);
}
private void retryUntilSuccess(byte[] msg) {
while (true) {
try {
final boolean result = syncPayload(msg);
if (result) {
break;
}
} catch (Exception e) {
log.error("exception is ", e);
}
}
}
/**
* 模拟同步执行的业务方法
*
* @param msg 消息体内容
* @return
*/
private boolean syncPayload(byte[] msg) {
return System.currentTimeMillis() % 2 == 0;
}
}
```
## FAQ
### 消费者的性能上不去,微服务的CPU也比较低
如果服务的CPU比较健康,但是性能上不来,同时`receiverQueueSize`配置地也相对较小(如小于2*TPS),那么就可以考虑增大`receiverQueueSize`。
## 致谢
感谢 [鹏辉哥](https://github.com/codelipenghui)和 [罗天](https://github.com/fu-turer)的审稿。
## 作者简介
贺张俭,西安电子科技大学毕业,华为云物联网高级工程师
简书博客地址: https://www.jianshu.com/u/9e21abacd418
| 0 |
eliasnogueira/restassured-complete-basic-example | A complete API Test Architecture example using Java and RestAssured providing a real-world example and continuous delivery ready. | apitesting java restassured testautomation | # Rest-Assured Complete Basic Example
[](https://github.com/eliasnogueira/restassured-complete-basic-example/actions)
Don't forget to give this project a ⭐
* [Required Software](#required-software)
* [How to execute the tests](#how-to-execute-the-tests)
* [Running the backend API](#running-the-backend-api)
* [Running the test suites](#running-the-test-suites)
* [Generating the test report](#generating-the-test-report)
* [About the Project Structure](#about-the-project-structure)
* [Libraries](#libraries)
* [Patterns applied](#patterns-applied)
* [Pipeline](#pipeline)
* [Do you want to help?](#do-you-want-to-help)
This project was created to start the initial steps with test automation for a REST API using Rest-Assured.
It tests the API: [combined-credit-api](https://github.com/eliasnogueira/combined-credit-api)
> :warning: **Disclaimer**
>
> This project has an educational objective and does not have the best practices that could be applied
>
> Some practices will help you to improve your test architecture, but the central point of this repository and
> demonstrate an example of running tests for API in a pipeline
> some practices will help you to improve your test architecture,
> but the central point of this repository and demonstrate an example of running tests for API in a pipeline
## Required software
* Java JDK 22+
* Maven installed and in your classpath
* Clone/download the backend API [combined-credit-api](https://github.com/eliasnogueira/combined-credit-api)
> :notebook: **Note**
>
> You can use Java 17 if you want
## How to execute the tests
You can open each test class on `src\test\java` and execute all of them, but I recommend you run it by the
command line. It enables us to run in different test execution strategies and, also in a pipeline, that is the repo purpose.
### Running the backend API
Please, before executing any tests, run the backend API.
After cloning this project:
1. Navigate to the project folder using the Terminal / Command prompt
2. Execute the following: `mvn spring-boot:run`
3. Wait until you see something like this: _Application has started! Happy tests!_
4. The API is ready and listen to all requests on `http://localhost:8088`
### Running the test suites
The test suites can be run directly by your IDE or by command line.
If you run `mvn test` all the tests will execute because it's the regular Maven lifecycle to run all the tests.
To run different suites based on the groups defined for each test you must inform the property `-Dgroups` and the group names.
The example below shows how to run the test for each pipeline stage:
| pipeline stage | command |
|--------------------|----------------------------------|
| health check tests | `mvn test -Dgroups="health"` |
| contract tests | `mvn test -Dgroups="contract"` |
| functional tests | `mvn test -Dgroups="functional"` |
| e2e tests | `mvn test -Dgroups="e2e"` |
### Generating the test report
This project uses Allure Report to automatically generate the test report.
There are some configuration to make it happen:
* aspectj configuration on `pom.xml` file
* `allure.properties` file on `src/test/resources`
You can use the command line to generate it in two ways:
* `mvn allure:serve`: will open the HTML report into the browser
* `mvn allure:report`: will generate the HTML port at `target/site/allure-maven-plugin` folder
## About the Project Structure
### src/main/java
#### test
Base Test that sets the initial aspects to make the requests using RestAssured.
It also has the configuration to deal with `BigDecimal` returns and SSL configuration.
#### client
Classes that do some actions in their endpoints. It's used my the `FullSimulationE2ETest` to demonstrate and e2e
scenario.
#### commons
It contains a class where will format the URL expected when we create a new resource in the `simulation` endpoint.
You can add any class that can be used in the project.
#### config
The class `Configuration` is the connections between the property file `api.properties` located in `src/test/resources/`.
The `@Config.Sources` load the properties file and match the attributes with the `@Key`, so you automatically have the value.
You can see two sources.
The first one will get the property values from the system (as environment variables or from the command line) in the case you want to change it, for example, in a pipeline.
The second will load the `api.properties` file from the classpath.
```java
@Config.Sources({
"system:properties",
"classpath:api.properties"})
```
The environment variable is read on the `ConfiguratorManager`.
This class reduces the amount of code necessary to get any information on the properties file.
This strategy uses [Owner](https://matteobaccan.github.io/owner/) library
#### data
##### factory
Test Data Factory classes using [java-faker](https://github.com/DiUS/java-faker) to generate fake data and [Lombok] to
create the objects using the Builder pattern.
In a few cases, there are custom data like:
* the list of existent restrictions and simulations in the database
* cpf generation
* data generation returned by the API use
##### provider
JUnit 5 Arguments to reduce the amount of code and maintenance for the functional tests on `SimulationsFunctionalTest`
##### suite
It contains a class having the data related to the test groups.
##### support
Custom CPF (social security number) generator.
#### model
Model and Builder class to
[mapping objects thought serialization and deserialization](https://github.com/rest-assured/rest-assured/wiki/Usage#object-mapping)
in use with Rest-Assured.
#### specs
Request and Response specifications used by the clients and e2e tests.
The class `InitialStepsSpec` set the basePath, baseURI, and port for the custom specs.
The classes `RestrictionsSpecs` and `SimulationsSpecs` contains the implementation of request and response specifications.
### src/test/java
#### e2e
End-to-End test using both endpoints to simulate the user journey thought the API.
#### general
Health check test to assure the endpoint is available.
#### restrictions
Contract and Functional tests to the Restriction endpoint.
#### simulations
Contract and Functional tests to the Simulations endpoint
### src/test/resources
It has a `schemas` folder with the JSON Schemas to enable Contract Testing using Rest-Assured. Also, the properties file to easily configure the API URI.
## Libraries
* [RestAssured](http://rest-assured.io/) library to test REST APIs
* [JUnit 5](https://junit.org/junit5/) to support the test creation
* [Owner](https://matteobaccan.github.io/owner/) to manage the property files
* [java-faker](https://github.com/DiUS/java-faker) to generate fake data
* [Log4J2](https://logging.apache.org/log4j/2.x/) as the logging strategy
* [Allure Report](https://docs.qameta.io/allure/) as the testing report strategy
## Patterns applied
* Test Data Factory
* Data Provider
* Builder
* Request and Response Specification
* Base Test
## Pipeline
This project uses [GitHub Actions](https://github.com/features/actions) to run the all the tests in a pipeline.
You can find it at https://github.com/eliasnogueira/restassured-complete-basic-example/blob/master/.github/workflows/test-execution.yml
We have the following pipeline steps:
```
build -> health check -> contract -> e2d -> funcional
```
Except the build, that is the traditional Maven build, the other stages has some parameters to determine the test type and the SUT (System Under Test).
The parameters are:
* `-Dgroups`: specify which test type will be executed
* `-Dapi.base.uri`: specify a new base URI
* `-Dapi.base.path`: specify a new base path
* `-Dapi.port`: specify a new port
* `-Dapi.health.context`: specify a new health context
All the parameters, except the `-Dgroups` are pointing to Heroku because we can't run it locally.
It's a great example about how can you set different attribute values to run your tests.
## Do you want to help?
Please read the [Contribution guide](CONTRIBUTING.md)
| 1 |
mkyong/spring4-mvc-gradle-xml-hello-world | Gradle + Spring 4 MVC hello world example (XML) | null | Gradle - Spring 4 MVC Hello World
===============================
Template for Spring 4 MVC + JSP view + XML configuration, using Gradle build tool.
###1. Technologies used
* Gradle 2.0
* Spring 4.1.6.RELEASE
* JSTL 1.2
* Logback 1.1.3
* Boostrap 3
###2. To Run this project locally
```shell
$ git clone https://github.com/mkyong/spring4-mvc-gradle-xml-hello-world
$ gradle jettyRun
```
Access ```http://localhost:8080/spring4```
###3. To import this project into Eclipse IDE
1. ```$ gradle eclipse```
2. Import into Eclipse via **existing projects into workspace** option.
3. Done.
###4. Project Demo
Please refer to this article [Gradle - Spring 4 MVC Hello World ](http://www.mkyong.com/spring-mvc/gradle-spring-mvc-web-project-example/)
| 1 |
alanfgates/programmingpig | Data and example code for Programming Pig, by Alan F. Gates | null | null | 1 |
iansrobinson/graph-databases-use-cases | Example use cases from the O'Reilly Graph Databases book | null | Graph Databases Use Cases
=========================
Example use case implementations from the O'Reilly book [Graph Databases](http://graphdatabases.com/) by [@iansrobinson](http://twitter.com/iansrobinson), [@jimwebber](http://twitter.com/jimwebber) and [@emileifrem](http://twitter.com/emileifrem).
Setup
-----
This repository contains a submodule, _neode_, which is used to build the performance datasets. After cloning the repository, you will need to initialize the submodule:
git submodule init
and then:
git submodule update
To run the use case queries:
mvn clean install
Overview
--------
Queries are developed in a test-driven fashion against small, well-known representative graphs (as described pp.83-87 of the book). The queries can then be run against a much larger, randomly-generated graph (typically, 1-2 million nodes and several million relationships), to test their relative performance. (Note: these performance tests do not test production-like scenarios; rather, they act as a sanity check, ensuring that queries that run fast against a very small graph are still reasonably performant when run against a larger graph.)
The project contains 3 modules (in addition to the _neode_ submodule):
* _queries_
Contains the use case queries and the unit tests used to develop the queries.
* _dataset_builders_
Builds larger, randomly-generated sample datasets.
* _performance_tests_
Runs the queries against the large sample datasets.
Running the Performance Tests
-----------------------------
First, build the project as described in Setup.
Before you run the performance tests you will need to generate sample datasets. To create a sample dataset run:
mvn test -pl data-generation -DargLine="-Xms2g -Xmx2g" -Dtest=AccessControl|Logistics|SocialNetwork
For example, to generate a sample dataset for the Logistics queries, run:
mvn test -pl data-generation -DargLine="-Xms2g -Xmx2g" -Dtest=Logistics
*WARNING:* Building the sample datasets takes a long time (several tens of minutes in some cases).
To execute the performance tests against a sample dataset, run:
mvn test -pl performance-testing -DargLine="-Xms2g -Xmx2g" -Dtest=AccessControl|Logistics|SocialNetwork
| 1 |
hifly81/kafka-examples | Practical examples with Apache Kafka® | avro avro-schema avroserializer confluent confluent-kafka flink kafka kafka-client kafka-consumer kafka-consumers kafka-events kafka-installation kafka-manager kafka-producer kafka-producers kafka-streams kafka-topic ksql ktable microprofile | null | 0 |
georgeberar/medium | Public repository containing examples for my Medium posts | null | Public repository containing examples for my Medium posts.
## Posts
| # | Post | Folder |
| ------------- | ------------- | ------------- |
| 1 | [SpringBoot: Fall In Love with Enum Mapping](https://medium.com/@georgeberar.contact/springboot-fall-in-love-with-enum-mapping-aa212c5e2056) | `dynamic-enum-mapping` |
| 2 | [SpringBoot: Standardized API Error Handling](https://medium.com/@georgeberar.contact/springboot-standardized-api-exception-handling-f31510861350) | `error-handling` |
| 3 | [SpringBoot: Fuzzy Match With Postgres](https://medium.com/@georgeberar.contact/springboot-fuzzy-match-with-postgres-8eb6bfd17b58) | `fuzzy-match-postgresql` |
| 4 | [SpringBoot: API Authentication Using OAuth2 With Google](https://medium.com/@georgeberar.contact/springboot-api-authentication-using-oauth2-with-google-655b8759f0ac) | `resource-server-oauth2-google` |
| 5 | [SpringBoot: Rule Engine For Classifying Celestial Objects](https://medium.com/@georgeberar.contact/springboot-rule-engine-for-classifying-celestial-objects-6af6d4f824a6) | `rule-engine` |
| 6 | [SpringBoot: Extract Text From PDF](https://medium.com/@georgeberar/springboot-extract-text-from-pdf-1d8d41b5adac) | `pdf-content-extractor` |
| 7 | [SpringBoot: Generate OpenAPI Document During Test Phase](https://medium.com/@georgeberar/springboot-generate-openapi-document-during-test-phase-a3a793a50dfe) | `openapi` |
| 8 | [Speed Up Backend Development With WireMock And Docker](https://medium.com/@georgeberar/speed-up-backend-development-with-wiremock-and-docker-5dc2eaadd9d9) | `wiremock-docker` | | 0 |
BroncBotz3481/YAGSL-Example | Yet Another General Swerve Library Example Project | frc java swerve swerve-drive yagsl | # Yet Another Generic Swerve Library (YAGSL) Example project
YAGSL is intended to be an easy implementation of a generic swerve drive that should work for most
square swerve drives. The project is documented
on [here](https://github.com/BroncBotz3481/YAGSL/wiki). The JSON documentation can also be
found [here](docs/START.md)
This example is intended to be a starting place on how to use YAGSL. By no means is this intended to
be the base of your robot project. YAGSL provides an easy way to generate a SwerveDrive which can be
used in both TimedRobot and Command-Based Robot templates.
# Overview
### Installation
Vendor URL:
```
https://broncbotz3481.github.io/YAGSL-Lib/yagsl/yagsl.json
```
[Javadocs here](https://broncbotz3481.github.io/YAGSL/)
[Library here](https://github.com/BroncBotz3481/YAGSL/)
[Code here](https://github.com/BroncBotz3481/YAGSL/tree/main/swervelib)
[WIKI](https://github.com/BroncBotz3481/YAGSL/wiki)
[Config Generation](https://broncbotz3481.github.io/YAGSL-Example/)
# Create an issue if there is any errors you find!
We will be actively montoring this and fix any issues when we can!
## Development
* Development happens here on `YAGSL-Example`. `YAGSL` and `YAGSL-Lib` are updated on a nightly
basis.
# Support our developers!
<a href='https://ko-fi.com/yagsl' target='_blank'><img height='35' style='border:0px;height:46px;' src='https://az743702.vo.msecnd.net/cdn/kofi3.png?v=0' border='0' alt='Buy Me a Robot at ko-fi.com'></a>
### TL;DR Generate and download your configuration [here](https://broncbotz3481.github.io/YAGSL-Example/) and unzip it so that it follows structure below:
```text
deploy
└── swerve
├── controllerproperties.json
├── modules
│ ├── backleft.json
│ ├── backright.json
│ ├── frontleft.json
│ ├── frontright.json
│ ├── physicalproperties.json
│ └── pidfproperties.json
└── swervedrive.json
```
### Then create your SwerveDrive object like this.
```java
import java.io.File;
import edu.wpi.first.wpilibj.Filesystem;
import swervelib.parser.SwerveParser;
import swervelib.SwerveDrive;
import edu.wpi.first.math.util.Units;
SwerveDrive swerveDrive=new SwerveParser(new File(Filesystem.getDeployDirectory(),"swerve")).createSwerveDrive(Units.feetToMeters(14.5));
```
# Migrating Old Configuration Files
1. Delete `wheelDiamter`, `gearRatio`, `encoderPulsePerRotation` from `physicalproperties.json`
2. Add `optimalVoltage` to `physicalproperties.json`
3. Delete `maxSpeed` and `optimalVoltage` from `swervedrive.json`
4. **IF** a swerve module doesn't have the same drive motor or steering motor as the rest of the
swerve drive you **MUST** specify a `conversionFactor` for BOTH the drive and steering motor in
the modules configuration JSON file. IF one of the motors is the same as the rest of the swerve
drive and you want to use that `conversionFactor`, set the `conversionFactor` in the module JSON
configuration to 0.
5. You MUST specify the maximum speed when creating a `SwerveDrive`
through `new SwerveParser(directory).createSwerveDrive(maximumSpeed);`
6. IF you do not want to set `conversionFactor` in `swervedrive.json`. You can pass it into the
constructor as a parameter like this
```java
double DriveConversionFactor = SwerveMath.calculateMetersPerRotation(Units.inchesToMeters(WHEEL_DIAMETER), GEAR_RATIO, ENCODER_RESOLUTION);
double SteeringConversionFactor = SwerveMath.calculateDegreesPerSteeringRotation(GEAR_RATIO, ENCODER_RESOLUTION);
SwerveDrive swerveDrive = new SwerveParser(directory).createSwerveDrive(maximumSpeed, SteeringConversionFactor, DriveConversionFactor);
```
### Falcon Support would not have been possible without support from Team 1466 Webb Robotics!
# Configuration Tips
### My Robot Spins around uncontrollably during autonomous or when attempting to set the heading!
* Invert the gyro scope.
* Invert the drive motors for every module. (If front and back become reversed when turning)
### Angle motors are erratic.
* Invert the angle motor.
### My robot is heavy.
* Implement momentum velocity limitations in SwerveMath.
### Ensure the IMU is centered on the robot
# Maintainers
- @thenetworkgrinch
- @Technologyman00
# Special Thanks to Team 7900! Trial N' Terror
Without the debugging and aid of Team 7900 the project could never be as stable or active as it is.
| 1 |
adamjshook/mapreducepatterns | Repository for MapReduce Design Patterns (O'Reilly 2012) example source code | null | mapreducepatterns
=================
Repository for MapReduce Design Patterns (O'Reilly 2012) example source code | 1 |
flixel-gdx/flixel-gdx-examples | A collection of demos and examples for the flixel-gdx framework. | null | What is flixel-gdx?
-----------------------
flixel-gdx is a port of the AS3 game framework [flixel](http://flixel.org) to Java and Android. It’s built on top of the well-known libgdx framework which allows apps to be deployed to both Android and Desktop. With libgdx the nasty OpenGL ES stuff is all hidden. Like the original flixel, its primary function is to provide some useful base classes that you can easily extend to make your own basic game objects.
Get Started
-----------
https://github.com/flixel-gdx/flixel-gdx/wiki/Project-Setup
Forums
------
flixel-gdx doesn’t have its own message board, but you can use the forums of flixel and libgdx. Both have an active community. If you have any questions or feedback that are related to flixel please put it in the flixel community. They are more likely to help you out more quickly than at the libgdx. Questions about Android, OpenGL ES, rendering, etc. goes to libgdx.
[flixel forums](http://forums.flixel.org) | [libgdx forums](http://www.badlogicgames.com/forum)
[](https://bitdeli.com/free "Bitdeli Badge")
| 0 |
hbaseinaction/twitbase | TwitBase is a running example used throughout HBase In Action | null | # HBase In Action: TwitBase
[http://www.manning.com/dimidukkhurana][0]
## Compiling the project
Code is managed by maven. Be sure to install maven on your platform
before running these commands. Also be aware that HBase is not yet
supported on the OpenJDK platform, the default JVM installed on most
modern Linux distributions. You'll want to install the Oracle (Sun)
Java 6 runtime and make sure it's configured on your `$PATH` before
you continue. Again, on Ubuntu, you may find the [`oab-java6`][1]
utility to be of use.
To build a self-contained jar:
$ mvn package
The jar created using this by default will allow you to interact with
HBase running in standalone mode on your local machine. If you want
to interact with a remote (possibly fully distributed) HBase
deployment, you can put your `hbase-site.xml` file in the
`src/main/resources` directory before compiling the jar.
## Using TwitBase
We have provided a launcher script to run TwitBase and the utilities
that the HBaseIA project comes with.
$ bin/launcher
Just run the launcher without any arguments and it'll print out the
usage information.
TwitBase applications can also be run using java directly:
$ java -cp target/twitbase-1.0.0.jar <app> [options...]
Utilities for interacting with TwitBase include:
- `HBaseIA.TwitBase.InitTables` : create TwitBase tables
- `HBaseIA.TwitBase.TwitsTool` : tool for managing Twits
- `HBaseIA.TwitBase.UsersTool` : tool for managing Users
- `HBaseIA.TwitBase.LoadUsers` : tool for loading random Users
- `HBaseIA.TwitBase.LoadTwits` : tool for loading random Twits
The following MapReduce jobs can be launched the same way:
- `HBaseIA.TwitBase.mapreduce.TimeSpent` : run TimeSpent log
processing MR job
- `HBaseIA.TwitBase.mapreduce.CountShakespeare` : run
Shakespearean counter MR job
- `HBaseIA.TwitBase.mapreduce.HamletTagger` : run
hamlet-tagging MR job
## Other utilities and scripts
The following utilities are available for you to play with:
- `utils.TablePreSplitter` : create pre-split table
## License
Copyright (C) 2012 Nick Dimiduk, Amandeep Khurana
Distributed under the [Apache License, version 2.0][2], the same as HBase.
[0]: http://www.manning.com/dimidukkhurana
[1]: https://github.com/flexiondotorg/oab-java6
[2]: http://www.apache.org/licenses/LICENSE-2.0.html
| 1 |
osmandapp/osmand-api-demo | Example of usage OsmAnd API | null | # osmand-api-demo
Examples of usage for OsmAnd API & SDK
- see https://osmand.net/docs/technical/osmand-api-sdk/ for instructions and differences
- you can use GitHub Actions to build projects in your fork (if you don't have Android build environment yourself)
| 1 |
alienrobotwizard/sounder | A grouping of Apache Pig examples. | null | null | 0 |
adamldavis/hellojava8 | Code examples for java 8 talk and book | null | hellojava8
==========
Code examples for java 8 talk
| 0 |
oktadev/auth0-java-microservices-examples | Java Microservice Examples | java microservices spring-boot spring-cloud spring-cloud-gateway | # Auth0 Java Microservice Examples
- [Reactive Java Microservices with Spring Boot and JHipster](reactive-jhipster#readme)
- [Java Microservices with Spring Boot and Spring Cloud - Gateway WebFlux](spring-boot-gateway-webflux#readme)
- [Java Microservices with Spring Boot and Spring Cloud - Gateway MVC](spring-boot-gateway-mvc#readme)
You can watch a demo of the WebFlux example in the screencast below.
[](https://youtu.be/m-lhymNdPBc)
| 0 |
alexjlockwood/adp-path-morph-submission-status | Submission status path morphing example | null | # material-submission-status-icon-demo
<img alt="Material exclamation mark to check mark animation" src="http://i.imgur.com/zVkc5lg.gif" width="336px" height="600px" />
| 1 |
piomin/sample-spring-kafka-microservices | Example microservices showing how to use Kafka and Kafka Streams with Spring Boot on the example of distributed transactions implementations with the SAGA pattern | kafka kafka-streams spring-boot spring-kafka | null | 1 |
effective-software-testing/code | The code examples of the Effective Software Testing: A Developer's Guide" book" | null | # Effective software testing

This repository contains the code examples of the _Software Testing: A Developer's Guide_ book, by [Maurício Aniche](https://www.mauricioaniche.com).
Each folder contains the code examples of their respective chapter:
* Chapter 1: Effective and systematic software testing
* Chapter 2: Specification-based testing
* Chapter 3: Structural testing and code coverage
* Chapter 4: Design by Contracts
* Chapter 5: Property-based testing
* Chapter 6: Test doubles and mocks
* Chapter 7: Designing for testability
* Chapter 8: Test-Driven Development
* Chapter 9: Larger tests
* Chapter 10: Test code quality
Each folder is an independent maven project. You should be able to import the project directly in your favorite IDE (e.g., InteliiJ, Eclipse). You can also run all the tests via `mvn test`.
To run code coverage in chapter 3, go to the ch3 folder and type `mvn clean test jacoco:report`. Then, open the `target/site/jacoco/index.html` file to see the report. If you want to run the mutation coverage, type `mvn clean compile test-compile pitest:mutationCoverage`. The report will be generated in the `target/pit-reports/**/index.html`, where `**` is a string that represents the date time that you ran the report. For Linux or Mac users, I provide bash scripts `coverage.sh` and `mutation.sh` that run the commands above for you.
To run the web tests of chapter 9, you first should run the [Spring PetClinic](https://github.com/spring-projects/spring-petclinic) application. For convenience, we provide a compiled jar here. To run the web app, just go to the ch9 folder and type `java -jar *.jar`.
## Contributing to PRs
Maybe you found a test I missed or a better way to implement the code. You are most welcome to submit your PRs!
If you do so, I ask you to create another file, with the same name as the original plus some suffix, and add a comment explaining what you did there. I do not want to touch the original files as they match with the code snippets in the book; we do not want readers to get lost.
## License and reuse
You are free to reuse and modify the code provided in this repository, for personal or business purposes, as long as the book is always explicitly mentioned as reference. For example, if you are providing training or workshops, you are required to have a dedicated slide with the picture of the book in each of the slide decks that make use of examples from here.
| 0 |
mahyoussef/ultimate-design-patterns | Mastering classical design patterns with practical examples in the ultimate design patterns bundle. | null | # ultimate-design-patterns
Mastering classical design patterns with practical examples in the ultimate design patterns bundle.
<p>
<a href="https://www.udemy.com/course/ultimate-design-patterns/?referralCode=C4486750B8FA2ABC3F46"><img src="images/ultimate-design-patterns.png" /> </a>
</p>
## How to Contribute
Feel free to contriubte by applying theses patterns in different programming languages as well as we are open for any enhancements through pull requests.
## Contributors
Thanks to all the people who already contributed!
| Name | Contribution | GitHub Avatar |
|----------------|------------------|---------------------------------------------------|
| Hatem Hosny | Typescript | <img src="https://github.com/hatemhosny.png" alt="Hatem Hosny" width="100" height="100"> |
| Mohamed Lotfy | Typescript | <img src="https://github.com/mohamedlotfe.png" alt="Mohamed Lotfy" width="100" height="100">|
| Menna | Typescript | <img src="https://github.com/mennah4.png" alt="Menna" width="100" height="100">|
| Amir Elsagan | C# | <img src="https://github.com/amirosagan.png" alt="Amir Elsagan" width="100" height="100">|
| Moamen Ashraf | C# | <img src="https://github.com/moamen189.png" alt="Moamen Ashraf" width="100" height="100">|
| Youssef Wael | C# | <img src="https://github.com/YoussefWaelMohamedLotfy.png" alt="Youssef Wael" width="100" height="100">|
| Mohamed Zidan | C# | <img src="https://github.com/mazidan77.png" alt="Mohamed Zidan" width="100" height="100">|
| Ahmed Mahdy | Dart | <img src="https://github.com/elnaddar.png" alt="Ahmed Mahdy" width="100" height="100">|
| Rodina Moamen | Kotlin | <img src="https://github.com/rodinamomen.png" alt="Rodina Moamen" width="100" height="100">|
| Abdelrahman Kosba | Java | <img src="https://github.com/abdelrahamn-kosba.png" alt="Abeldrahman Kosba" width="100" height="100">|
## License
This project is licensed under the terms of the MIT license.
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.