full_name
stringlengths 7
104
| description
stringlengths 4
725
⌀ | topics
stringlengths 3
468
⌀ | readme
stringlengths 13
565k
⌀ | label
int64 0
1
|
---|---|---|---|---|
microsoft/todo-app-java-on-azure | Sample TODO app using Java on Azure | null | # Todo App Java On Azure
This TodoList app is an Azure Java application. It provides end-to-end CRUD operation to todo list item from front-end AngularJS code. Behind the scene, todo list item data store is [Azure CosmosDB DocumentDB](https://docs.microsoft.com/en-us/azure/cosmos-db/documentdb-introduction). This application uses [Azure CosmosDB] (https://github.com/Azure/azure-cosmosdb-java), [Azure DocumentDB] (https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-introduction) [Spring Boot Starter](https://github.com/Microsoft/azure-spring-boot), and AngularJS to interact with Azure. This sample application provides several deployment options to deploy to Azure, pls see deployment section below. With Azure support in Spring Starters, maven plugins and Eclipse/IntelliJ plugins, Azure Java application development and deployment is effortless now.
## TOC
* [Requirements](#requirements)
* [Create Azure Cosmos DB documentDB](#create-azure-cosmos-db-documentdb)
* [Configuration](#configuration)
* [Run it](#run-it)
* [Contribution](#contributing)
* Add new features
* [Add AAD](https://github.com/Microsoft/todo-app-java-on-azure/tree/aad-start)
* [Add KeyVault](https://github.com/Microsoft/todo-app-java-on-azure/tree/keyvault-secrets)
* Deployment
* [Deploy to Azure Web App for Containers using IntelliJ plugin](./doc/deployment/deploy-to-azure-web-app-using-intelliJ-plugin.md)
* [Deploy to Azure Web App for Containers using Eclipse plugin](./doc/deployment/deploy-to-azure-web-app-using-eclipse-plugin.md)
* [Deploy to Azure Container Service Kubernetes cluster using Maven plugin](./doc/deployment/deploy-to-azure-container-service-using-maven-plugin.md)
* [Deploy to Azure Web App for Containers using Maven plugin](./doc/deployment/deploy-to-azure-web-app-using-maven-plugin.md)
* [Deploy to Azure Web App for Container using Jenkins](./doc/deployment/deploy-to-azure-web-app-using-jenkins.md)
* [Deploy to Azure Web App for Java SE applications using Jenkins](./doc/deployment/deploy-to-azure-web-app-javase-using-jenkins.md)
* [Deploy to Azure Web App for Tomcat using Jenkins](./doc/deployment/deploy-to-azure-web-app-tomcat-using-jenkins.md)
* [Deploy to Azure Container Service using Jenkins](./doc/deployment/deploy-to-azure-container-service-using-jenkins.md)
* [Deploy to AKS using Jenkins and Blue/Green Deployment](./doc/deployment/deploy-to-AKS-blueegreen-using-jenkins.md)
* [Build Docker image from git repo in Azure Container Registry then deploy to Azure Kubernetes Service using Jenkins](./doc/deployment/deploy-to-aks-with-acr-build-git-using-jenkins.md)
* [Build Docker image from local directory in Azure Container Registry then deploy to Azure Kubernetes Service using Jenkins](./doc/deployment/deploy-to-aks-with-acr-build-local-using-jenkins.md)
* [Useful link](#useful-link)
## Requirements
* [JDK](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) 1.8 and above
* [Maven](https://maven.apache.org/) 3.0 and above
## Create Azure Cosmos DB documentDB
You can follow our steps using [Azure CLI 2.0](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) to deploy an Azure Cosmos DB documentDB,
or follow [this article](https://docs.microsoft.com/en-us/azure/cosmos-db/create-documentdb-java) to create it from Azure portal.
1. login your Azure CLI, and set your subscription id
```bash
az login
az account set -s <your-subscription-id>
```
1. create an Azure Resource Group, and note your group name
```bash
az group create -n <your-azure-group-name> -l <your-resource-group-region>
```
1. create Azure Cosmos DB with DocumentDB kind. Note the `documentEndpoint` field in the response.
```bash
az cosmosdb create --kind GlobalDocumentDB -g <your-azure-group-name> -n <your-azure-documentDB-name>
```
**Note** name of cosmos db must be in lowercase.
1. get your Azure Cosmos DB key, get the `primaryMasterKey` of the DocumentDB you just created.
```bash
az cosmosdb list-keys -g <your-azure-group-name> -n <your-azure-documentDB-name>
```
## Configuration
* Note your DocumentDB uri and key from last step, specify a database name but no need to create it.
Then modify `src/main/resources/application.properties` file and save it.
``` txt
azure.documentdb.uri=put-your-documentdb-uri-here
azure.documentdb.key=put-your-documentdb-key-here
azure.documentdb.database=put-your-documentdb-databasename-here
```
* If you don't want to modify configuration in the source code manually, you can put variables in this file and
set their values in system environment variables: `DOCUMENTDB_URI`, `DOCUMENTDB_KEY` and `DOCUMENTDB_DBNAME`.
Then maven will substitute them during the build phase.
``` txt
azure.documentdb.uri=@env.DOCUMENTDB_URI@
azure.documentdb.key=@env.DOCUMENTDB_KEY@
azure.documentdb.database=@env.DOCUMENTDB_DBNAME@
```
## Run it
1. package the project using `mvn package`
1. Run the project using `java -jar target/todo-app-java-on-azure-1.0-SNAPSHOT.jar`
1. Open `http://localhost:8080` you can see the web pages to show the todo list app
## Clean up
Delete the Azure resources you created by running the following command:
```bash
az group delete -y --no-wait -n <your-resource-group-name>
```
## Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
## Useful link
- [Azure Spring Boot Starters](https://github.com/Microsoft/azure-spring-boot)
- [Azure Maven plugins](https://github.com/Microsoft/azure-maven-plugins)
| 1 |
ITHit/WebDAVServerSamplesJava | WebDAV server examples in Java based on IT Hit WebDAV Server Library for Java | amazon-s3 java kotlin ms-ofba oracle samples server spring spring-boot springboot sql webdav |
<h1>WebDAV Server Examples, Java</h1>
<div class="description"><p style="line-height: 22px; font-size: 15px; font-weight: normal;">IT Hit WebDAV Server Library for Java is provided with several examples that demonstrate how to build a WebDAV server with SQL back-end or with file system storage. You can adapt these samples to utilize almost any back-end storage including storing data in CMS/DMS/CRM, Azure or Amazon storage.</p>
<p style="line-height: 22px; font-size: 15px; font-weight: normal;">A sample HTML page included with samples demonstrates how to use <a title="IT Hit WebDAV Ajax Libray" href="https://www.webdavsystem.com/ajax/" target="_blank">IT Hit WebDAV Ajax Libray</a> to open documents from a web page for editing, list documents and navigate folder structure as well as build search capabilities.</p>
<h2>Online Demo Server</h2>
<p style="line-height: 22px; font-size: 15px; font-weight: normal;"><a title="https://www.WebDAVServer.com" href="https://www.WebDAVServer.com" target="_blank">https://www.WebDAVServer.com</a></p>
<h2> Requirements</h2>
<p style="line-height: 22px; font-size: 15px; font-weight: normal;">The samples are tested with <strong><span>Java 1.8</span></strong> in the following environments:</p>
<ul>
<li style="margin-bottom: 16px;">Tomcat 7 or later</li>
<li style="margin-bottom: 16px;">Glassfish 4.1.1 or later</li>
<li style="margin-bottom: 16px;">JBoss Wildfly 9 or later or respective EAP</li>
<li style="margin-bottom: 16px;">WebLogic 12c or later</li>
<li style="margin-bottom: 16px;">WebSphere 8.5.5.11 or later</li>
<li style="margin-bottom: 16px;">Jetty 9.3.13 or later</li>
</ul>
<h2>Full-text Search and indexing</h2>
<p style="line-height: 22px; font-size: 15px; font-weight: normal;">The samples are provided with full-text search and indexing based on use Apache Lucene as indexing engine and Apache Tika as content analysis toolkit.</p>
<p style="line-height: 22px; font-size: 15px; font-weight: normal;">The server implementation searches both file names and file content including content of Microsoft Office documents as well as any other documents which format is supported by Apache Tika, such as LibreOffice, OpenOffice, PDF, etc.</p></div>
<ul class="list">
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/springboot3fsstorage">
<h2>Spring Boot WebDAV Server Example with File System Back-end, Java</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/springboot3fsstorage">
<p>
This sample provides a WebDAV server running on the Spring Boot framework with files being stored in the file system. The WebDAV requests are processed in a dedicated context, while the rest of the website processes regular HTTP requests, serving web <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/springbootoraclestorage">
<h2>Spring Boot WebDAV Server Example with Oracle Back-end, Java</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/springbootoraclestorage">
<p>
This sample provides a WebDAV server running on the Spring Boot framework. All data including file content, document structure, and custom attributes are stored in the Oracle database. The IT Hit WebDAV Ajax Library is used to display and browse serv <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/springboots3storage">
<h2>Spring Boot WebDAV Server Example with Amazon S3 Back-end, Java</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/springboots3storage">
<p>
This sample is a fully functional Class 2 WebDAV server that runs on the Spring Boot framework and stores all data in the Amazon S3 bucket. The WebDAV requests are processed on a /DAV/ context, while the rest of the website processes regular HTTP req <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/oraclestorage">
<h2>WebDAV Server Example with Oracle Back-end, Java</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/oraclestorage">
<p>
The sample provides Class 2 WebDAV server implementation that can be hosted in Apache Tomcat, GlassFish, JBoss, WebLogic, WebSphere or other compliant application server. All data including file content, documents structure and custom attributes is s <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/filesystemstorage">
<h2>WebDAV Server Example with File System Back-end, Java and Kotlin</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/filesystemstorage">
<p>
This sample is a fully functional Class 2 WebDAV server that stores all data in the file system. It utilizes file system Extended Attributes (in case of Linux and macOS) or Alternate Data Streams (in case of Windows/NTFS) to store locks and custom pr <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/collectionsync">
<h2>WebDAV Server Example with Collection Synchronization Support</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/jakarta/collectionsync">
<p>
This sample is a fully functional Class 2 WebDAV server with collection synchronization support (RFC 6578) that stores all data in the file system. This sample is similar to what is provided by the Java demo WebDAV server at: https://webdavserver.com <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/android/androidfsstorage">
<h2>Java WebDAV Server Example for Android</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/android/androidfsstorage">
<p>
This sample is a Class 2 WebDAV server that runs on Android. It uses modified NanoHTTPD as an application server and publishes files from a mobile application folder or from media folder. Locks and properties in SQLite database.
To see the documents <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/deltav">
<h2>WebDAV Server Example with Versioning, Java</h2>
</a>
<a href="https://github.com/ITHit/WebDAVServerSamplesJava/tree/master/Java/javax/deltav">
<p>
The sample provides DeltaV WebDAV server implementation that can be hosted in Apache Tomcat, GlassFish, JBoss, WebLogic or WebSphere. The data is stored in Oracle database. The IT Hit WebDAV Ajax Library is used to display and browse server content o <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://www.webdavsystem.com/javaserver/server_examples/running_webdav_samples/">
<h2>Running the WebDAV Samples</h2>
</a>
<a href="https://www.webdavsystem.com/javaserver/server_examples/running_webdav_samples/">
<p>
Once your sample is configured and running you will see the following web page (note that the port that the sample is using may be different from the one on the screenshots):
This web page is a MyCustomHandlerPage.html included in each sample and <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://www.webdavsystem.com/javaserver/server_examples/search/">
<h2>Configuring Full-Text Search for Files Stored in File System or in Oracle Database</h2>
</a>
<a href="https://www.webdavsystem.com/javaserver/server_examples/search/">
<p>
The samples provided with SDK use Apache Lucene as indexing engine and Apache Tika as content analysis toolkit.
The server implementation searches both file names and file content including content of Microsoft Office documents as well as any other <span>...</span>
</p>
</a>
</li>
<li>
<a class="link-header" href="https://www.webdavsystem.com/javaserver/server_examples/troubleshooting/">
<h2>WebDAV Server Samples Problems and Troubleshooting</h2>
</a>
<a href="https://www.webdavsystem.com/javaserver/server_examples/troubleshooting/">
<p>
Examining Logs
If things are not going as planned and you run into issues the first place to look would be the log file &lt;Your Tomcat location&gt;\Tomcat x.x\logs\localhost.xxxx-xx-xx.log . The logs will reflect as to what is going on and it will <span>...</span>
</p>
</a>
</li>
</ul>
| 0 |
IBM-Cloud/todo-apps | Sample ToDo application (various languages) running on IBM Cloud | bluemix cloud-foundry cloudant couchdb java mongodb nodejs php python rails swift | about
================================================================================
The ToDo sample apps are meant to be simple demos of how you can take advantage
of Bluemix and a database service. In addition it shows how to take advantage
of both the [built-in](https://www.ng.bluemix.net/docs/starters/rt_landing.html) and [community buildpacks](https://github.com/cloudfoundry-community/cf-docs-contrib/wiki/Buildpacks)
to deploy your app using whatever runtime you choose.
The ToDo app is pretty simple, it allows you to add an persist ToDos that you
need to get done. As you complete different ToDos you can mark them done and
eventually delete them from the list. The ToDos are stored in a database.
All implementations support two different database backends,
[Mongo DB](https://www.mongodb.org/) and [Couch DB](http://couchdb.apache.org/)
via [Cloudant](https://cloudant.com/). If you want to use Cloudant see the
section of this README titled "Couch DB and Cloudant".
background
================================================================================
The front-end UI for the ToDo app uses a slightly modified version of the
Backbone sample from [TodoMVC.com](http://todomvc.com/architecture-examples/backbone/). The main change was
to change the `collections/todo.js` file to not use `localStorage`,
but to instead set the `url` to `apis/todos`,
so that the ToDos are retrieved from the server instead of from localStorage.
The original `collections/todo.js` file is
[here](https://github.com/tastejs/todomvc/blob/gh-pages/architecture-examples/backbone/js/collections/todos.js).
There are various implementation for the back-end of the ToDo app.
We have implemented the back-end currently in
Java, Node.js, Sinatra, Python, and PHP. If you want to contribute a backend
in another language we enchourage you to do. See the "adding new implementations"
section.
All of the implementations are similar; they serve up the files in the
`frontend` directory as static web resources - html, css, js files. And they
also expose an api at the uri `api/todos` to query and modify the ToDos.
Note that this isn't really a realistic ToDo app, at present, since it maintains
a global list of Todos that the entire world shares. The intent is just to
show using an existing simple front-end application with a simple database
back-end. A real example would probably include user authentication, storing
ToDo's on a per-user basis, etc.
getting the code
================================================================================
To get the code you can just clone the repo.
git clone git@github.com:IBM-Bluemix/todo-apps.git
The repository contains a directory for each implementation, and the
`frontend` directory contains the web resources that are used by each
implementation.
running the samples
================================================================================
To run the samples on Bluemix you must have signed up for Bluemix and have
installed the Cloud Foundry command line tool. To sign up for Bluemix head to
[bluemix.net](https://console.ng.bluemix.net/?cm_mmc=Display-GitHubReadMe-_-BluemixSampleApp-Todo-_-Node-Compose-_-BM-DevAd) and register.
You can download the Cloud Foundry command line tool by following the steps in the [README file](https://github.com/cloudfoundry/cli).
After you have installed the Cloud Foundry command line tool you need to point it
at Bluemix so it knows where to deploy the applications. You can do this by running
cf login -a https://api.ng.bluemix.net
This will prompt you to login with your Bluemix user ID and password which is the
same as your IBM ID and password. You should only need to do this once, the command
line tool will remember this information.
Most of the projects use build technologies that are specific to the runtime the ToDo
app is written in to deploy the app to Bluemix (Maven, Rake, Paver, etc). The assumption
is that these are tools developers who are using these runtimes are familiar with.
Under the covers they are using the Cloud Foundry command line to deploy the apps.
The benefit is that you don't need to remember verbose commands (in most cases) and
continue to use tools you are comfortable with. See the individual runtime folders
(java, node, php, python, sinatra) for more details on how to deploy the various
versions.
adding new implementations
================================================================================
Feel free to expand upon this project by adding new implementations in your
favorite runtime or framework. Below is a simple specification you should keep
in mind when adding new implementations.
### REST Endpoints
* The server implementation should support GET, POST, PUT, and DELETE.
#### GET Request - Gets all ToDos
GET /api/todos
GET Response
The response should be a JSON array of all ToDos.
[{"completed":false,"id":"001fbbe7bd708a34624b47526cd6ac89","order":1,"title":"test"},{"completed":false,"id":"4d6153cf4bc3bdaf9c6c7eebf42d67a6","order":2,"title":"1"},{"completed":false,"id":"be3855e004dd5d74c802992c09ea8d28","order":3,"title":"2"},{"completed":false,"id":"e7cb7149098961e5dc182715f1cb0e9d","order":4,"title":"3"},{"completed":false,"id":"9368ccc4629a1c8dfd99a9e741d01c44","order":5,"title":"4"},{"completed":false,"id":"e5752d462b83f13da3d8dced1c15eb43","order":6,"title":"5"}]
#### POST Request - Creates a new ToDo
POST /api/todos/
POST Body
{"title":"another","order":7,"completed":false}
POST Response
The response should be a JSON representation of a ToDo with the id field
populated.
{"completed":false,"id":"f76424cc41f1ee8c2682a37069098794","order":7,"title":"another"}
#### PUT Request - Updates a ToDo
PUT /api/todos/[id]
PUT Body
{"completed":true,"id":"4d6153cf4bc3bdaf9c6c7eebf42d67a6","order":2,"title":"1"}
PUT Response
The response should be a JSON representation of the updated ToDo.
{"completed":true,"id":"4d6153cf4bc3bdaf9c6c7eebf42d67a6","order":2,"title":"1"}
#### DELETE Request - Deletes a ToDo
DELETE /api/todos/[id]
DELETE Response
The response should be a 204.
### Mongo
* The Mongo implementation should use a collection called "todos".
* You should create a Mongo DB service with the name "todo-mongo-db" or "todo-compose-mongo-db", depending on which Mongo provider you choose.
#### Setting Up a Mongo DB server Locally
It will most likely be useful to have a local Mongo DB server for testing
when adding new implementations.
See the Mongo DB [install instructions](http://docs.mongodb.org/manual/installation/)
for your platform to install a local Mongo DB server.
### Couch DB / Cloudant
* You should create a Cloudant service with the name "todo-couch-db".
* The name of the Couch DB / Cloudant database to use is "bluemix-todo".
<b>View</b>
The application code should create a view document, if one doesn't already exist,
in the bluemix-todo database with the following JSON.
{
views: {
allTodos: {
reduce: "_count",
map: "function(doc){if(doc.title && doc.completed != null){emit(doc.order,{title: doc.title,completed: doc.completed})}}"
}
}
}
#### Setting Up CouchDB Server Locally
It will most likely be useful to have a local Couch DB server for testing
when adding new implementations.
Relax, this is very easy!
Head over to the official home of CouchDB - <http://couchdb.apache.org/> - and
click the red "DOWNLOAD" link. Follow the instructions to download a verison
of CouchDB for your platform.
When running the Mac version of CouchDB, you'll have a menu bar tool-button you can
use to start and manage the database.
The implementations will run locally as long as the CouchDB server is running.
By default the Couch DB will be running at http://127.0.0.1:5984.
| 1 |
odrotbohm/spring-restbucks | Implementation of the sample from REST in Practice based on Spring projects | null | null | 1 |
Rukey7/TagLayout | TagView Sample | null | # TagLayout
[![Apache 2.0 License](https://img.shields.io/badge/license-Apache%202.0-blue.svg?style=flat)](http://www.apache.org/licenses/LICENSE-2.0.html) [![](https://jitpack.io/v/Rukey7/TagLayout.svg)](https://jitpack.io/#Rukey7/TagLayout)
### 多功能的标签流布局
## Screenshot
##### 不同标签形状:
![](https://raw.githubusercontent.com/Rukey7/ScreenShot/master/TagLayout/tag_shape.png)
##### 标签单选和多选模式:
![](https://raw.githubusercontent.com/Rukey7/ScreenShot/master/TagLayout/tag_choice.png)
##### 标签编辑模式:
![](https://raw.githubusercontent.com/Rukey7/ScreenShot/master/TagLayout/tag_edit.png)
##### 标签换一换模式:
![](https://raw.githubusercontent.com/Rukey7/ScreenShot/master/TagLayout/tag_change.gif)
##### 单个标签的其它用法:
![](https://raw.githubusercontent.com/Rukey7/ScreenShot/master/TagLayout/tag_view.gif)
## dependence
你需要在项目的根 `build.gradle` 加入如下JitPack仓库链接:
```gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
```
接着在你的需要依赖的Module的`build.gradle`加入依赖:
```gradle
compile 'com.github.Rukey7:TagLayout:{lastest-version}'
```
其中 `{lastest-version}` 为最新的版本,你可以查看上面显示的jitpack版本信息,也可以到[jitpack.io](https://jitpack.io/#Rukey7/IjkPlayerView)仓库查看。
## Usage
在布局中直接使用:
```xml
<!-- 标签布局 -->
<com.dl7.tag.TagLayout
android:id="@+id/tag_layout_1"
style="@style/TagLayout.RandomColor"
app:tag_layout_fit_num="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<!-- 单个标签独立使用 -->
<com.dl7.tag.TagView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="删除"
app:tag_border_color="@android:color/holo_red_light"
app:tag_icon="@mipmap/ic_delete"
app:tag_press_feedback="true"
app:tag_text_color="@android:color/holo_red_light"/>
```
### 属性设置
标签布局属性(有对应接口):
|name|format|description|
|:---:|:---:|:---:|
| tag_layout_mode | enum | {normal,edit,change,single_choice,multi_choice}, 分别为正常、编辑、换一换、单选和多选等模式
| tag_layout_shape | enum | {round_rect,arc,rect},标签形状分别为圆角矩形、圆弧形和直角矩形,默认round_rect
| tag_layout_random_color | boolean | 随机颜色
| tag_layout_press_feedback | boolean | 按压反馈效果
| tag_layout_fit_num | integer | 设置一行固定显示几个标签
| tag_layout_bg_color | color | 标签布局背景颜色
| tag_layout_border_color | color | 标签布局边框颜色
| tag_layout_border_radius | dimension | 标签布局边框圆角弧度
| tag_layout_border_width | dimension | 标签布局边框大小
| tag_layout_vertical_interval | dimension | 标签垂直间隔
| tag_layout_horizontal_interval | dimension | 标签水平间隔
| tag_view_bg_color | color | 标签背景颜色
| tag_view_border_color | color | 标签边框颜色
| tag_view_text_color | color | 标签字体颜色
| tag_view_bg_color_check | color | 标签选中背景颜色
| tag_view_border_color_check | color | 标签选中边框颜色
| tag_view_text_color_check | color | 标签选中字体颜色
| tag_view_border_width | dimension | 标签边框大小
| tag_view_border_radius | dimension | 标签边框圆角弧度
| tag_view_vertical_padding | dimension | 标签垂直填充
| tag_view_horizontal_padding | dimension | 标签水平填充
| tag_view_icon_padding | dimension | 标签icon和文字的间隔
| tag_view_text_size | dimension | 标签字体大小(1.0.5由float改为dimension)
| tag_layout_horizontal_reverse | boolean | 水平反向排列(RTL)
标签属性:
|name|format|description|
|:---:|:---:|:---:|
| tag_mode | enum | {normal,check,icon_check_invisible,icon_check_change}, 分别为正常、可选中、选中图标消失和选中换图标等模式
| tag_shape | enum | {round_rect,arc,rect},标签形状分别为圆角矩形、圆弧形和直角矩形,默认round_rect
| tag_auto_check | boolean | 使能自动点击选中操作
| tag_press_feedback | boolean | 按压反馈效果
| tag_checked | boolean | 初始选中状态
| tag_icon | reference | 标签图标
| tag_icon_change | reference | 标签选中时替换的图标(icon_check_change模式)
| tag_text_check | string | 标签选中时替换的字符
| tag_bg_color | color | 标签背景颜色
| tag_border_color | color | 标签边框颜色
| tag_text_color | color | 标签字体颜色
| tag_bg_color_check | color | 标签选中背景颜色
| tag_border_color_check | color | 标签选中边框颜色
| tag_text_color_check | color | 标签选中字体颜色
| tag_border_width | dimension | 标签边框大小
| tag_border_radius | dimension | 标签边框圆角弧度
| tag_vertical_padding | dimension | 标签垂直填充
| tag_horizontal_padding | dimension | 标签水平填充
| tag_text | dimension | 标签icon和文字的间隔
| tag_icon_padding | dimension | 标签icon和文字的间隔
| tag_text | string | 标签字符
| tag_text_size | dimension | 标签字体大小
| tag_gravity | enum | 图标放置位置,只支持left和right
### ChangeLog
##### 1.0.4 -> 1.0.5
1、重写TagView直接继承View,简化了代码逻辑,不再支持TextView的android:text和android:textSize属性,替换为自定义的tag_text和tag_text_size属性;
2、增加了tag_gravity属性来设置Drawable的放置位置,只支持left和right;
##### 1.0.5 -> 1.0.6
1、添加水平反向排列属性(tag_layout_horizontal_reverse);
License
-------
Copyright 2017 Rukey7
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| 1 |
binblee/springcloud-swarm | Spring Cloud Application Samples on Docker swarm-mode cluster | null | # Spring Cloud Demo on Docker
# Spring Cloud application
Demo application is a tiny Spring Cloud application which has three services. ```Web``` and ```BookService```will register itself to ```Eureka``` Service during boot. ```Web``` service depends on ```BookService```, when it is invoked, it will find available instances of ```BookService``` from ```Eureka``` Server. ```Web``` will call ```BookService``` REST API to fulfill its result.
![](images/springcloud-tiny.png)
## Build
Run this command to build all images, it will rebuild all images even if no code change.
```
./build-all.sh
```
## Run application in local environment
Run demo application in local environment is wasy, there is an all-in-one compose file which allows you to run all the services.
```
cd compose
docker-compose -f all-in-one.yml up -d
```
Find which port mapping for each services.
```
$ docker-compose -f all-in-one.yaml ps
Name Command State Ports
----------------------------------------------------------------------------------------
compose_bookservice_1 java -Djava.security.egd=f ... Up
compose_eureka_1 java -Djava.security.egd=f ... Up 0.0.0.0:8761->8761/tcp
compose_web_1 java -Djava.security.egd=f ... Up 0.0.0.0:32771->8080/tcp
```
You will see eureka maps to port 8761 of localhost while web maps to 32771 in this case.
## Access Eureka Server
Access Eureka server through port 8761. You will see this Eureka server has one replica and two services registered.
```
http://localhost:8761
```
![](images/eureka-screenshot.png)
## Access the demo application
Docker allocated an random port for ```web``` service, you can get the port number using ```docker-compose ps``` command, or you can assign a port number in ```all-in-one.yml```.
Run this command or access it using a web browser.
```
curl http://localhost:<port>
```
![](images/web-screenshot.png)
## Deploy to docker swarm using compose V3 template
Let's take a look at [compose/all-in-one.yml](compose/all-in-one.yml). There are no version 3 specific compose syntax, you can deploy the application by using docker-compose in local environment, or deploy it to a Docker swarm cluster directly.
```yaml
version: '3'
services:
eureka:
image: binblee/demo-eurekaserver
ports:
- "8761:8761"
...
web:
image: binblee/demo-web
environment:
- EUREKA_SERVER_ADDRESS=eureka
ports:
- "8080"
...
bookservice:
image: binblee/demo-bookservice
environment:
- EUREKA_SERVER_ADDRESS=eureka
...
```
You can deploy it to a docker swarm cluster like this:
```
docker stack deploy -f all-in-one.yml springcloud-demo
```
## Run in production environment
All in one is good, but you need to consider below factors when you want to run all the services in an production environment.
- deploy Eureka server and applications separately, as Eureka server as an infrasturcture level service will not be updated frequently, it is not proper to deploy it with applications every time the application changes.
- again, Eureka server as infrastructure level need some kind of HA (high availablity).
Let's break the deployment into two compose files. Using [eureka.yml](compose/eureka.yml) you can deply a three-node-cluster of Euerka. All instances have same network alias ```eureka``` for which Eureka client will looking for.
[eureka.yml](compose/eureka.yml)
```yaml
version: '3'
services:
eureka1:
image: binblee/demo-eurekaserver
networks:
springcloud-overlay:
aliases:
- eureka
ports:
- "8761:8761"
environment:
- ADDITIONAL_EUREKA_SERVER_LIST=http://eureka2:8761/eureka/,http://eureka3:8761/eureka/
...
eureka2:
image: binblee/demo-eurekaserver
networks:
springcloud-overlay:
aliases:
- eureka
ports:
- "8762:8761"
environment:
- ADDITIONAL_EUREKA_SERVER_LIST=http://eureka1:8761/eureka/,http://eureka3:8761/eureka/
...
eureka3:
image: binblee/demo-eurekaserver
networks:
springcloud-overlay:
aliases:
- eureka
ports:
- "8763:8761"
environment:
- ADDITIONAL_EUREKA_SERVER_LIST=http://eureka1:8761/eureka/,http://eureka2:8761/eureka/
...
networks:
springcloud-overlay:
external:
name: springcloud-overlay
```
[demoweb.yml](compose/demoweb.yml) gets the content from original [all-in-one.yml](compose/all-in-one.yml), adding network properties. All services will connect to ```springcloud-overlay``` network.
```yaml
version: '3'
services:
web:
image: binblee/demo-web
networks:
- springcloud-overlay
environment:
- EUREKA_SERVER_ADDRESS=eureka
ports:
- "8080"
...
bookservice:
image: binblee/demo-bookservice
networks:
- springcloud-overlay
environment:
- EUREKA_SERVER_ADDRESS=eureka
...
networks:
springcloud-overlay:
external:
name: springcloud-overlay
```
Let's deploy it, noted that ```springcloud-overlay``` network needs to be created before ```eureka``` and ```demoweb``` are deployed.
```bash
docker network create -d overlay springcloud-overlay
cd compose/
docker stack deploy -c eureka.yml
docker stack deploy -c demoweb.yml
```
Access port 8761 of any node in swarm, you will see Eureka instance #1 has two replicas, and services are registered to it. Visit port 8762 and 8763, you will get other two Eureka server, have a try.
![](images/eureka-cluster.png)
## Recap
| 0 |
beast-dev/beast-mcmc | Bayesian Evolutionary Analysis Sampling Trees | bayesian-analysis beast evolution java mcmc phylogenetics | # BEAST
BEAST is a cross-platform program for Bayesian analysis of molecular sequences using MCMC. It is entirely orientated towards rooted, time-measured phylogenies inferred using strict or relaxed molecular clock models. It can be used as a method of reconstructing phylogenies but is also a framework for testing evolutionary hypotheses without conditioning on a single tree topology. BEAST uses MCMC to average over tree space, so that each tree is weighted proportional to its posterior probability. We include a simple to use user-interface program for setting up standard analyses and a suit of programs for analysing the results.
## Download BEAST
[Download BEAST v1.10.X binaries for Mac, Windows and UNIX/Linux](https://github.com/beast-dev/beast-mcmc/releases)
[Latest stable release ![Release Version](https://img.shields.io/github/release/beast-dev/beast-mcmc.svg?style=plastic) ![Release Date](https://img.shields.io/github/release-date/beast-dev/beast-mcmc.svg?style=plastic)](https://github.com/beast-dev/beast-mcmc/releases/latest/) ![Downloads](https://img.shields.io/github/downloads/beast-dev/beast-mcmc/v1.10.4/total.svg?style=plastic)
[Latest development release ![Development Version](https://img.shields.io/github/release/beast-dev/beast-mcmc/all.svg?style=plastic) ![Development Date](https://img.shields.io/github/release-date-pre/beast-dev/beast-mcmc.svg?style=plastic)](https://github.com/beast-dev/beast-mcmc/releases/latest/) ![Downloads](https://img.shields.io/github/downloads-pre/beast-dev/beast-mcmc/latest/total.svg?style=plastic)
[The previous major release of BEAST was v1.8.4 --- binaries for Mac, Windows and UNIX/Linux](https://github.com/beast-dev/beast-mcmc/releases/tag/v1.8.4) ![Downloads](https://img.shields.io/github/downloads/beast-dev/beast-mcmc/v1.8.4/total.svg?style=plastic)
[Older BEAST Downloads](https://code.google.com/p/beast-mcmc/downloads)
## Other Downloads
[BEASTGen v1.0.2 .tgz file](https://drive.google.com/file/d/0B37cqWL7UhTAVFVhQ2o1Y093b1k)
[BEASTGen v1.0.2 .ZIP file](https://drive.google.com/file/d/0B37cqWL7UhTAWm81VklIeUNtQVU)
# Documentation
[BEAST Documentation Website](http://beast.community)
# Development software
We use IntelliJ IDEA and java profiling via [JProfile](https://www.ej-technologies.com/products/jprofiler/overview.html) and YourKit
# Acknowledgements
- This work was supported in part by the European Union Seventh Framework Programme for research, technological development and demonstration under Grant Agreement no. 278433-PREDEMICS and no. 725422-ReservoirDOCS, the Wellcome Trust through collaborator award 206298/Z/17/Z, NSF grant DMS 1264153 and NIH grants R01 HG006139, R01 AI107034 and U19 AI135995.
---
| 0 |
stepanowon/OAuth_20 | OAuth 2.0 Provider & Client Java Samples | null | OAuth_20
========
Samples for OAuth 2.0 Provider & Client
OAuth2 Provider & Consumer Sample입니다.
https://tools.ietf.org/html/rfc6749 를 근거하여 작성하였습니다.
이 코드는 샘플 코드입니다. 상업적인 목적으로 사용하지 말아주세요. 스터디 용도로만 사용해주세요.
환경설정에 대한 질문, 코드 자체에 대한 질문은 받지 않겠습니다.
OAuth2.0에 대한 질문도 위의 RFC 문서를 직접 읽어보세요.
상업적인 목적이 아니라면 이용가능한 코드입니다.
상업적인 목적으로는 사용하지 말아주세요.
이 코드의 저작권은 stepanowon@hotmail.com 에게 있습니다.
A. environment
- Oracle 10g Express(H2 Database 사용가능)
- Java 1.6 + Spring 3.1 + Eclipse(indigo) + Maven + iBatis 2.0 + Tomcat 6.0(HTTP Port 8000)
B. project
- oauth2provider : 인증서버 & 리소스 서버
- oauth2client : web server flow 클라이언트
- oauth2client_agentflow : User Agent flow 클라이언트
C. configuration
- table 생성
- DB는 oracle 10g express에 oauth2/oauth2 계정을 생성하여야 함.
- oauth2provider의 src 디렉토리에 oauth2provider.sql 파일을 읽어 테이블 설치
사용자 계정은 t1000, gdhong, arnold 세개의 계정(암호 동일)
- 상수값 설정
- net.oauth.v2 패키지의 OAuth2Constant클래스에서 상수값변경
* USE_REFRESH_TOKEN : refresh token 기능을 사용할지 말지를 결정함.
* AES_ENCRYPTION_KEY : 내부에서 토큰 생성시 사용할 AES 암호화 키 값
* EXPIRES_IN_VALUE : refresh token 기능을 사용할 때 토큰의 유효기간(기본값:3600(초))
- net.oauth.v2 패키지의 OAuth2Scope 클래스에서 상수값 변경
* 조직에 따라 scope 상수값 설정(현재는 6개의 샘플 scope을 설정하였음)
* resource 엔드포인트 url 별로 권한 설정(scope 지정)
D. endpoint
- login & client app 등록
* com.multi.oauth2.provider.view.controller.LoginController 클래스 참조
* com.multi.oauth2.provider.view.controller.ClientController 클래스 참조
- authorization
* /oauth2provider/oauth2/auth
- response_type 파라미터가 code일 경우는 web server flow
- response_type 파라미터가 token일 경우는 user agent flow(Mobile App, Desktop포함)
- token
* /oauth2provider/oauth2/token
- grant_type 파라미터가 authorization_code 인 경우는 server flow로 access token 발급
- grant_type 파라미터가 refresh_token 인 경우는 access token을 갱신하게 됨.
- protected resource
* 이 샘플에서의 protected resource는 승인한 사용자의 계정 정보로 가정하였고,
endpoint는 /oauth2provider/resource/myinfo.do 이다.
* 여러 protected resource에 대한 권한을 부여하기 위해 end point별 권한은 net.oauth.v2.OAuth2Scope 클래스의
scopeUrlMap 필드에 Hashmap으로 작성한다
* access token 정보 검증, scope 검증은 Interceptor(com.multi.oauth2.provider.util.Oauth2Interceptor)를
이용해 Controller 실행 전에 처리한다.
* 예외 처리는 Controller 상에서 OAuth2Exception 을 발생시키면
ExceptionResolver가 error 페이지로 이동시켜 OAuth2.0 spec에 따른 에러 코드와 메시지를 응답한다.
* 클라이언트 앱이 user agent 타입으로 등록되었다면 Protected Resource 접근시 Cross Domain 문제를
해결해줄 수 있도록 CORS(Cross Origin Resource Sharing)기법을 지원하도록 하였다.
- 인증과정 또는 token 발급 과정에서 CSRF(Cross Site Request Forgery)공격에 대한 대응으로
OAuth2.0에서 recommended된 state 파라미터를 사용하였다.
E. 추가/개선할 사항..
- OAuth 2.0 에서는 에러 발생시 WWW-Authenticate 헤더를 통해 응답하도록 하고 있으나
Google, Facebook은 다른 방식을 사용하고 있다. 본 샘플은 facebook 스타일(?)로 작성하였다.
- OAuth2.0 의 처리과정 중 Web Server flow 와 user agent flow만 처리하였다.
* password credential과 client credential 방식은 작성하지 않았다. 대신
com.multi.oauth2.provider.view.controller.OAuth2Controller 클래스의 280번 라인에서
주석처리하여 향후 구현해야 함을 명시하였다.
* refresh token을 사용할 것인지는 OAuth2Constant의 상수값을 변경하면 됨.
* refresh token을 사용하지 않는 경우는 access token을 생성하지 않고 정해진 규칙에 따라
생성하도록 하였음. --> 랜덤값으로 토큰을 생성하여 DB에 저장하도록 변경가능
- 이 샘플에서는 redirect_uri 값을 비교하는 validation 과정을 거치므로 클라이언트 App을 등록할 때
반드시 접근가능한 URL을 입력해야 함( localhost 허용)
F. 알림사항
- 이 샘플은 잘 작동하지만 제대로된 설계없이 뚝딱거리면서 만들었음.
- 따라서 잘 정리된 코드는 아님. 주석도 개발새발임.
- 디버깅 목적으로 코드 사이사이에 콘솔 출력하는 코드가 많으니 알아서들 제거하고 테스트해야 함.
- oracle 10g 대신에 다른 DB 쓸거면 maven dependency, applicationContext.xml, oauth2.xml,
oauth2provider.sql 파일을 수정하여 쓰면 됨.
G. OAuth2.0 Client
- oauth2Client
* Web Server flow로 처리하도록 만든 client임.
* HTTP 통신을 위해 apache common의 HttpClent 클래스 사용
* client 각 요소는 jsp로 간단히 작성
* Settings.java 파일을 찾아 client_id, client_secret, 각각의 endpoint uri를 변경한 후 실행함.
- oauth2client_agentflow
* User Agent Flow 방식의 Client임.
* html 파일로 작성
* jQuery를 사용한 웹앱, webview를 통해 인증하고 access token을 획득하는 모바일앱. 이렇게 두가지의 경우
이 코드를 참조할 수 있음.
* index.html과 callback.html의 내부의 client_id, client_secret, 각각의 endpoint를 설정하고 실행함.
- 실행에 앞서 client app 을 인증서버(oauth2provider)에 등록해야 함.
| 0 |
AndroidAdvanceWithGeektime/Chapter02 | Sample for stop FinalizerWatchdogDaemon | null | # Chapter02
简介
======
该例子主要演示了如何通过关闭`FinalizerWatchdogDaemon`来减少`TimeoutException`的触发
需要注意的是,此种方法并不是去解决问题,而是为了避免上报异常采取的一种 hack 方案,并没有真正的解决引起 `finialize()` 超时的问题。
界面
======
![screen](screen.png)
操作步骤
======
1. 最好在模拟器下执行例子,因为各个手机设置的超时时长不同,不容易观看效果。
2. 点击`触发 Timeout`按钮,等待10多秒后,应用会触发 TimeOut Crash,产生如下日志
```
D/ghost: =============fire finalize=============FinalizerDaemon
I/.watchdogkille: Thread[3,tid=4369,WaitingInMainSignalCatcherLoop,Thread*=0x76e6ece16400,peer=0x149802d0,"Signal Catcher"]: reacting to signal 3
I/.watchdogkille: Wrote stack traces to '[tombstoned]'
E/AndroidRuntime: FATAL EXCEPTION: FinalizerWatchdogDaemon
Process: com.dodola.watchdogkiller, PID: 4363
java.util.concurrent.TimeoutException: com.dodola.watchdogkiller.GhostObject.finalize() timed out after 10 seconds
at java.lang.Thread.sleep(Native Method)
at java.lang.Thread.sleep(Thread.java:373)
at java.lang.Thread.sleep(Thread.java:314)
at com.dodola.watchdogkiller.GhostObject.finalize(GhostObject.java:13)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:250)
at java.lang.Daemons$FinalizerDaemon.runInternal(Daemons.java:237)
at java.lang.Daemons$Daemon.run(Daemons.java:103)
at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4363 SIG: 9
```
3. 点击`Kill WatchDog` 按钮可以关闭 Timeout watchdog,然后点击`触发 TimeOut` 按钮观察情况,正常情况下不会产生 crash
疑问点
===
如果直接调用Daemons$FinalizerWatchdogDaemon的stop方法,在Android 6.0之前的版本可能会有问题。
```
final Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");
final Field field = clazz.getDeclaredField("INSTANCE");
field.setAccessible(true);
final Object watchdog = field.get(null);
final Method method = clazz.getSuperclass().getDeclaredMethod("stop");
method.setAccessible(true);
method.invoke(watchdog);
```
这是为什么,你能告诉我们吗? | 1 |
SolaceSamples/solace-samples-mqtt | Getting Started Samples for using MQTT with Solace Message Routers. | mqtt solace solace-samples | [![Build Status](https://travis-ci.org/SolaceSamples/solace-samples-mqtt.svg?branch=master)](https://travis-ci.org/SolaceSamples/solace-samples-mqtt)
# Getting Started Examples
## MQ Telemetry Transport (MQTT)
MQTT is a standard lightweight protocol for sending and receiving messages. As such, in addition to information provided on the Solace [developer portal](http://dev.solace.com/tech/mqtt/), you may also look at some external sources for more details about MQTT. The following are good places to start
- http://mqtt.org/
- https://www.eclipse.org/paho/
The "Getting Started" tutorials will get you up to speed and sending messages with Solace technology as quickly as possible. There are three ways you can get started:
- Follow [these instructions](https://cloud.solace.com/learn/group_getting_started/ggs_signup.html) to quickly spin up a cloud-based Solace messaging service for your applications.
- Follow [these instructions](https://docs.solace.com/Solace-SW-Broker-Set-Up/Setting-Up-SW-Brokers.htm) to start the Solace VMR in leading Clouds, Container Platforms or Hypervisors. The tutorials outline where to download and how to install the Solace VMR.
- If your company has Solace message routers deployed, contact your middleware team to obtain the host name or IP address of a Solace message router to test against, a username and password to access it, and a VPN in which you can produce and consume messages.
## Contents
This repository contains code and matching tutorial walk throughs for different basic scenarios. It is best to view the associated [tutorials home page](https://dev.solace.com/samples/solace-samples-mqtt/).
## Prerequisites
There are no prerequisites.
## Build the Samples
./gradlew build
## Running the Samples
To try individual samples, build the project from source and then run samples like the following:
./build/staged/bin/topicPublisher tcp://<HOST>:<PORT> <client-username> <client-password>
See the individual tutorials linked from the [tutorials home page](https://dev.solace.com/samples/solace-samples-mqtt/) for full details which can walk you through the samples, what they do, and how to correctly run them to explore MQTT.
## Exploring the Samples
### Setting up your preferred IDE
Using a modern Java IDE provides cool productivity features like auto-completion, on-the-fly compilation, assisted refactoring and debugging which can be useful when you're exploring the samples and even modifying the samples. Follow the steps below for your preferred IDE.
#### Using Eclipse
To generate Eclipse metadata (.classpath and .project files), do the following:
./gradlew eclipse
Once complete, you may then import the projects into Eclipse as usual:
*File -> Import -> Existing projects into workspace*
Browse to the *'solace-samples-java'* root directory. All projects should import
free of errors.
#### Using IntelliJ IDEA
To generate IDEA metadata (.iml and .ipr files), do the following:
./gradlew idea
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Authors
See the list of [contributors](https://github.com/SolaceSamples/solace-samples-mqtt/contributors) who participated in this project.
## License
This project is licensed under the Apache License, Version 2.0. - See the [LICENSE](LICENSE) file for details.
## Resources
For more information try these resources:
- [Tutorials](https://tutorials.solace.dev/)
- The Solace Developer Portal website at: http://dev.solace.com
- Get a better understanding of [Solace technology](https://solace.com/products/tech/).
- Check out the [Solace blog](http://dev.solace.com/blog/) for other interesting discussions around Solace technology
- Ask the [Solace community.](https://solace.community)
| 0 |
mkirsche/Jasmine | Jasmine: SV Merging Across Samples | null | [![install with bioconda](https://img.shields.io/badge/install%20with-bioconda-brightgreen.svg?style=flat)](http://bioconda.github.io/recipes/jasminesv/README.html)
[![European Galaxy server](https://img.shields.io/badge/usegalaxy-.eu-brightgreen?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAASCAYAAABB7B6eAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAACXBIWXMAAAsTAAALEwEAmpwYAAACC2lUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNS40LjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZmPSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOlJlc29sdXRpb25Vbml0PjI8L3RpZmY6UmVzb2x1dGlvblVuaXQ+CiAgICAgICAgIDx0aWZmOkNvbXByZXNzaW9uPjE8L3RpZmY6Q29tcHJlc3Npb24+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgICAgIDx0aWZmOlBob3RvbWV0cmljSW50ZXJwcmV0YXRpb24+MjwvdGlmZjpQaG90b21ldHJpY0ludGVycHJldGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KD0UqkwAAAn9JREFUOBGlVEuLE0EQruqZiftwDz4QYT1IYM8eFkHFw/4HYX+GB3/B4l/YP+CP8OBNTwpCwFMQXAQPKtnsg5nJZpKdni6/6kzHvAYDFtRUT71f3UwAEbkLch9ogQxcBwRKMfAnM1/CBwgrbxkgPAYqlBOy1jfovlaPsEiWPROZmqmZKKzOYCJb/AbdYLso9/9B6GppBRqCrjSYYaquZq20EUKAzVpjo1FzWRDVrNay6C/HDxT92wXrAVCH3ASqq5VqEtv1WZ13Mdwf8LFyyKECNbgHHAObWhScf4Wnj9CbQpPzWYU3UFoX3qkhlG8AY2BTQt5/EA7qaEPQsgGLWied0A8VKrHAsCC1eJ6EFoUd1v6GoPOaRAtDPViUr/wPzkIFV9AaAZGtYB568VyJfijV+ZBzlVZJ3W7XHB2RESGe4opXIGzRTdjcAupOK09RA6kzr1NTrTj7V1ugM4VgPGWEw+e39CxO6JUw5XhhKihmaDacU2GiR0Ohcc4cZ+Kq3AjlEnEeRSazLs6/9b/kh4eTC+hngE3QQD7Yyclxsrf3cpxsPXn+cFdenF9aqlBXMXaDiEyfyfawBz2RqC/O9WF1ysacOpytlUSoqNrtfbS642+4D4CS9V3xb4u8P/ACI4O810efRu6KsC0QnjHJGaq4IOGUjWTo/YDZDB3xSIxcGyNlWcTucb4T3in/3IaueNrZyX0lGOrWndstOr+w21UlVFokILjJLFhPukbVY8OmwNQ3nZgNJNmKDccusSb4UIe+gtkI+9/bSLJDjqn763f5CQ5TLApmICkqwR0QnUPKZFIUnoozWcQuRbC0Km02knj0tPYx63furGs3x/iPnz83zJDVNtdP3QAAAABJRU5ErkJggg==)](https://usegalaxy.eu/root?tool_id=jasminesv)
# Jasmine
JASMINE: Jointly Accurate Sv Merging with Intersample Network Edges
Version 1.1.5
This tool is used to merge structural variants (SVs) across samples. Each sample has a number of SV calls, consisting of position information (chromosome, start, end, length), type and strand information, and a number of other values. Jasmine represents the set of all SVs across samples as a network, and uses a modified minimum spanning forest algorithm to determine the best way of merging the variants such that each merged variants represents a set of analogous variants occurring in different samples.
## Conda Installation
The recommended installation method is through [bioconda](https://bioconda.github.io/).
Conda Installation command (typically takes under a minute to install):
```
conda config --add channels bioconda
conda config --add channels conda-forge
conda install jasminesv
```
## Instructions for building from source
When running Jasmine, one of the preprocessing options is to run Iris, a tool which refines the sequences and breakpoints of insertions in datasets with high-error reads. Iris depends on samtools, minimap2, and racon by default, which can be installed separately and either added to your path or pointed to with the `iris_args` parameter. Once these dependencies are installed (or if running Jasmine without Iris preprocessing), Jasmine can be built with the following command:
```
path_to_jasmine_repo/build_jar.sh
```
## Instructions for running
After building the jar file, Jasmine can be run with the executable file `jasmine`, which will be in the main folder of this repository if building from source, or in the condabin folder if installed through conda. Running it with no parameters will print a usage menu describing the required and optional arguments.
## Demo Dataset
To run Jasmine on HiFi data from the HG002 trio, run the following commands (typically takes about a minute to download and under five minutes to run on a modern desktop):
```
wget https://bx.bio.jhu.edu/data/jasmine/HG002Trio/UnmergedVCFs/HG002vGRCh38_wm_50md_PBCCS_sniffles.s2l20.refined.nSVtypes.ism.vcf .
wget https://bx.bio.jhu.edu/data/jasmine/HG002Trio/UnmergedVCFs/HG003vGRCh38_wm_50md_PBCCS_sniffles.s2l20.refined.nSVtypes.ism.vcf .
wget https://bx.bio.jhu.edu/data/jasmine/HG002Trio/UnmergedVCFs/HG004vGRCh38_wm_50md_PBCCS_sniffles.s2l20.refined.nSVtypes.ism.vcf .
wget https://bx.bio.jhu.edu/data/jasmine/HG002Trio/HG002Trio_HiFi.merged.vcf .
ls *vGRCh38_wm_50md_PBCCS_sniffles.s2l20.refined.nSVtypes.ism.vcf > filelist.txt
jasmine file_list=filelist.txt out_file=merged.vcf
jasmine --dup_to_ins --postprocess_only out_file=merged.vcf
```
The output of merged.vcf should then exactly match the contents of HG002Trio_HiFi.merged.vcf.
## Optimized SV Inference Pipeline
Jasmine is offered as standalone software and will accurately merge SV calls from any SV callers, including short-read callers. However, if calling SVs from genomic long reads (PacBio CLR, PacBio HiFi, or Oxford Nanopore), for best results, we recommend using the following optimized pipeline to obtain population-scale SV calls from FASTQ files. This pipeline is provided as a [Snakemake pipeline](https://github.com/mkirsche/Jasmine/tree/master/pipeline).
![Jasmine SV Inference Pipeline](https://github.com/mkirsche/Jasmine/blob/master/pipeline/pipelineoverview.svg)
## IGV visualization module
Jasmine also includes a module for automating the creation of [IGV](http://software.broadinstitute.org/software/igv/) screenshots of variants of interest. It can be run through the `igv_jasmine` executable file. Running it with no parameters will print a usage menu describing the required and optional arguments, and it requires at minimum the following:
- BAM files from which variants were called in each sample
- The reference genome
- The merged VCF file, or a BED file with regions of interest
Running this module creates a folder which will store IGV screenshots for each variant (optionally filtered based on the command line parameters), and populates that folder with a .bat file, a script which can be run through IGV by selecting Tools -> Run Batch Script and navigating to the file. After running this script, the folder containing the .bat file will also include images of the regions surrounding each variant of interest.
## User Manual
The user manual with detailed information about input/output files and command line arguments can be found here: https://github.com/mkirsche/Jasmine/wiki/Jasmine-User-Manual
| 0 |
keets2012/Spring-Cloud_Samples | based on Spring-Cloud `Finchley` version. | null | ## Spring-Cloud-Samples
#### based on Spring-Cloud `Finchley` version.
## modules
- spring-cloud-gateway-server
- user-server(gateway-client) | 0 |
Simba-cheng/ApacheCamelDemo | Apache Camel Demo (Learning Sample Demo) | apachecamel cxf java | # Apache Camel Demo
PS:
各位学习、参考此Demo的朋友请注意,由于时间、兼容性问题,此项目中的jar版本很少变动,只会修复 dependabot 提醒的漏洞,如你要在生产环境使用,请使用最新的jar版本,并进行兼容性测试。
Apache Camel Blog:https://blog.csdn.net/simba_cheng/category_9271875.html
之前不小心将一些无用的配置文件上传了,请自行清除
该项目中包含
* Apache Camel - FTP组件
* Apache Camel - CXF组件(Code First and WSDL File First)
* Apache Camel - JMS/ActiveMQ组件
* Apache Camel - Jetty组件
* Apache Camel - Timer组件
* Apache Camel - JDBC组件
* Apache Camel - Dynamic Control Route(动态控制)
* Camel 各种路由...
学习期间,参考的PDF资料,都上传了,需要的童鞋请自取:
* [Mastering Apache Camel](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Mastering%20Apache%20Camel.pdf)
* [Red_Hat_Fuse-7.0-Apache_Camel_Development_Guide-en-US](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Red_Hat_Fuse-7.0-Apache_Camel_Development_Guide-en-US.pdf)
* [Apache Camel Developer's Cookbook](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Apache%20Camel%20Developer's%20Cookbook.pdf)
后续不定期更新。
# Apache Camel Demo(Learning Sample Demo)
PS:
All of you who study and refer to this demo please note that due to time and compatibility issues, the jar versions in this project rarely change and will only fix the bugs that dependabot reminds us of. If you want to use it in a production environment, please use the latest jar version and conduct compatibility tests.
Apache Camel Blog:https://blog.csdn.net/simba_cheng/category_9271875.html
I accidentally uploaded some useless configuration files before, please clear them yourself.
Included in the project :
* Apache Camel - FTP component
* Apache Camel - CXF component(Code First and WSDL File First)
* Apache Camel - JMS/ActiveMQ components
* Apache Camel - Jetty component
* Apache Camel - Timer component
* Apache Camel - JDBC component
* Apache Camel - Dynamic Control Route
* Apache Camel - Message Routing
Reference book :
* [Mastering Apache Camel](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Mastering%20Apache%20Camel.pdf)
* [Red_Hat_Fuse-7.0-Apache_Camel_Development_Guide-en-US](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Red_Hat_Fuse-7.0-Apache_Camel_Development_Guide-en-US.pdf)
* [Apache Camel Developer's Cookbook](https://github.com/Simba-cheng/ApacheCamelDemo/blob/master/book/Apache%20Camel%20Developer's%20Cookbook.pdf)
Irregular update...
# Code Tool
![Java profiler](./image/jprofiler_large.png)
[Java profiler](https://www.ej-technologies.com/products/jprofiler/overview.html)
# Stargazers over time
[![Stargazers over time](https://starchart.cc/Simba-cheng/ApacheCamelDemo.svg)](https://starchart.cc/Simba-cheng/ApacheCamelDemo)
| 1 |
githubhaohao/MVVMRxJavaRetrofitSample | MVVM RxJava Retrofit Sample | mvvm retrofit rxjava sample | ## Sample 简介
一个简单的结合 Retrofit 和 RxJava 框架实现 MVVM 架构的例子。
最近在研究 [Kotlin](https://github.com/githubhaohao/JavaToKotlin) for Android,做了一个基于 Clean 架构以及 Retrofit , RxKotlin , Dagger 框架实现的 Kotlin for Android App ,更多详情请[戳这里](https://github.com/githubhaohao/DoubanBook)。
## 效果预览
![result](https://github.com/githubhaohao/MVVMRxJavaRetrofitSample/blob/master/image/sample.gif?raw=true)
[Demo 下载](https://github.com/githubhaohao/MVVMRxJavaRetrofitSample/blob/master/demo.apk)
## 准备知识
### MVC
![mvc](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/mvc.PNG?raw=true)
- **视图(View)**:用户界面。
- **控制器(Controller)**:业务逻辑
- **模型(Model)**:数据保存
---
1. View 传送指令到 Controller
2. Controller 完成业务逻辑后,要求 Model 改变状态
3. Model 将新的数据发送到 View,使用户得到反馈
**缺陷**:View 和 Model 是相互可知,耦合性大,像 Activity 或者 Fragment 既是 Controller 层,又是 View 层,造成工程的可扩展性可维护性非常差。
### MVP
![mvp](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/mvp.png?raw=true)
在 MVP 设计架构中,Controller 变成了 Presenter。
1. 各层之间的通信,都是双向的。
2. View 与 Model 不直接发生联系,都通过 Presenter 进行间接通信。
3. Model 层与 Presenter 层,Presenter 层与 View 层之间通过接口建立联系。
采用 MVP 设计架构,Activity 与 Fragment 只位于 View 层。
**MVP 的缺陷在于**:由于我们使用了接口的方式去连接 View 层和 Presenter 层,这样就导致了一个问题,当你的页面逻辑很复杂的时候,你的接口会有很多,如果你的 app 中有很多个这样复杂的页面,维护接口的成本就会变的非常的大。
### MVVM
![MVVM](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/mvvp.PNG?raw=true)
MVVM 模式将 Presenter 改名为 ViewModel,基本上与 MVP 模式完全一致。
**区别在于**: View 层与 ViewModel 层通过`DataBinding`相互绑定,View的变动,自动反映在 ViewModel,反之亦然。
### [RxJava](https://github.com/ReactiveX/RxJava )
RxJava 在 GitHub 主页上的自我介绍是 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一个在 Java VM 上使用可观测的序列来组成异步的、基于事件的程序的库)。
RxJava 本质上是一个异步操作库,是一个能让你用极其简洁的逻辑去处理繁琐复杂任务的异步事件库。
简而言之,RxJava 可以用几个关键字概括:**简洁**,**队列化**,**异步**。
### [Retrofit](https://github.com/square/retrofit)
![retrofit](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/android-libs-retrofit-1-638.jpg?raw=true)
一个 Android 和 Java 上 HTTP 库(利用注解和 okhttp 来实现和服务器的数据交互)。
[**Retrofit 官方文档:http://square.github.io/retrofit/**](http://square.github.io/retrofit/)
### [DataBinding](https://developer.android.com/topic/libraries/data-binding/index.html)
![data-binding](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/data_binding.png?raw=true)
在今年的 Google IO 2015 中,Google 在 support-v7 中新增了 Data Binding,使用 Data Binding 可以直接在布局的 xml 中绑定布局与数据,从而简化代码,Android Data Binding 是Android 的 MVVM 框架。因为 Data Binding 是包含在 support-v7 包里面的,所以可以向下兼容到最低 Android 2.1 (API level 7+).
## 实践
嫌代码不够高亮?请移步博客[http://haohaochang.cn](http://haohaochang.cn/2017/02/12/MVVM%EF%BC%8CRxJava%E5%92%8CRetrofit%E7%9A%84%E4%B8%80%E6%AC%A1%E5%AE%9E%E8%B7%B5/)
直接上代码。
### 依赖的第三方类库
```gradle
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.github.bumptech.glide:glide:3.7.0'
```
### API
`https://api.douban.com/v2/movie/top250?start=0&count=20`
### 引入DataBinding
```gradle
android {
......
dataBinding {
enabled = true
}
}
```
### 工程目录结构
![目录](https://github.com/githubhaohao/ImageRoom/blob/master/Images/mvvm/%E7%9B%AE%E5%BD%95.png?raw=true)
### MVVM 之 View
**MainActivity.java**
```java
getFragmentManager().beginTransaction().add(R.id.movie_fragment, MovieFragment.getInstance()).commit();
```
**MovieFragment.java**
```java
public class MovieFragment extends Fragment implements CompletedListener,SwipeRefreshLayout.OnRefreshListener{
private static String TAG = MovieFragment.class.getSimpleName();
private MainViewModel viewModel;
private MovieFragmentBinding movieFragmentBinding;
private MovieAdapter movieAdapter;
public static MovieFragment getInstance() {
return new MovieFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.movie_fragment, container, false);
movieFragmentBinding = MovieFragmentBinding.bind(contentView);
initData();
return contentView;
}
private void initData() {
movieAdapter = new MovieAdapter();
movieFragmentBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
movieFragmentBinding.recyclerView.setItemAnimator(new DefaultItemAnimator());
movieFragmentBinding.recyclerView.setAdapter(movieAdapter);
movieFragmentBinding.swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark);
movieFragmentBinding.swipeRefreshLayout.setOnRefreshListener(this);
viewModel = new MainViewModel(movieAdapter,this);
movieFragmentBinding.setViewModel(viewModel);
}
@Override
public void onRefresh() {
movieAdapter.clearItems();
viewModel.refreshData();
}
@Override
public void onCompleted() {
if (movieFragmentBinding.swipeRefreshLayout.isRefreshing()) {
movieFragmentBinding.swipeRefreshLayout.setRefreshing(false);
}
}
}
```
**activity_main.xml**
```xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".view.MainActivity">
<!-- ... -->
<FrameLayout
android:layout_marginTop="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/movie_fragment"/>
<!-- ... -->
</android.support.design.widget.CoordinatorLayout>
```
**movie_fragment.xml**
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="com.jc.mvvmrxjavaretrofitsample.viewModel.MainViewModel"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:visibility="@{viewModel.contentViewVisibility}"
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:background="#ddd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
</android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:id="@+id/progress_bar"
android:visibility="@{viewModel.progressBarVisibility}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/error_info_layout"
android:visibility="@{viewModel.errorInfoLayoutVisibility}"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.exception}"/>
</LinearLayout>
</RelativeLayout>
</layout>
```
**movie_item.xml**
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.jc.mvvmrxjavaretrofitsample.viewModel.MovieViewModel"/>
</data>
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp"
card_view:cardBackgroundColor="@color/background"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_margin="8dp"
android:layout_width="60dp"
android:layout_height="100dp"
android:src="@drawable/cover"
app:imageUrl="@{viewModel.imageUrl}"
android:id="@+id/cover"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:orientation="vertical">
<TextView
android:textColor="@android:color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.title}"
android:textSize="12sp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatRatingBar
android:id="@+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:isIndicator="true"
android:max="10"
android:numStars="5"
android:rating="@{viewModel.rating}" />
<TextView
android:id="@+id/rating_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="6dp"
android:text="@{viewModel.ratingText}"
android:textColor="?android:attr/textColorSecondary"
android:textSize="10sp" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorSecondary"
android:textSize="10sp"
android:text="@{viewModel.movieType}"
android:id="@+id/movie_type_text"
android:layout_marginTop="6dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?android:attr/textColorSecondary"
android:textSize="10sp"
android:text="@{viewModel.year}"
android:id="@+id/year_text"
android:layout_marginTop="6dp"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</layout>
```
**MovieAdapter.java**
```java
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.BindingHolder> {
private List<Movie> movies;
public MovieAdapter() {
movies = new ArrayList<>();
}
@Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MovieItemBinding itemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.movie_item, parent, false);
return new BindingHolder(itemBinding);
}
@Override
public void onBindViewHolder(BindingHolder holder, int position) {
MovieViewModel movieViewModel = new MovieViewModel(movies.get(position));
holder.itemBinding.setViewModel(movieViewModel);
}
@Override
public int getItemCount() {
return movies.size();
}
public void addItem(Movie movie) {
movies.add(movie);
notifyItemInserted(movies.size() - 1);
}
public void clearItems() {
movies.clear();
notifyDataSetChanged();
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private MovieItemBinding itemBinding;
public BindingHolder(MovieItemBinding itemBinding) {
super(itemBinding.cardView);
this.itemBinding = itemBinding;
}
}
}
```
回调接口** CompletedListener.java**
```java
public interface CompletedListener {
void onCompleted();
}
```
### MVVM 之 ViewModel
**MainViewModel.java**
```java
public class MainViewModel {
public ObservableField<Integer> contentViewVisibility;
public ObservableField<Integer> progressBarVisibility;
public ObservableField<Integer> errorInfoLayoutVisibility;
public ObservableField<String> exception;
private Subscriber<Movie> subscriber;
private MovieAdapter movieAdapter;
private CompletedListener completedListener;
public MainViewModel(MovieAdapter movieAdapter,CompletedListener completedListener) {
this.movieAdapter = movieAdapter;
this.completedListener = completedListener;
initData();
getMovies();
}
private void getMovies() {
subscriber = new Subscriber<Movie>() {
@Override
public void onCompleted() {
Log.d("[MainViewModel]", "onCompleted");
hideAll();
contentViewVisibility.set(View.VISIBLE);
completedListener.onCompleted();
}
@Override
public void onError(Throwable e) {
hideAll();
errorInfoLayoutVisibility.set(View.VISIBLE);
exception.set(e.getMessage());
}
@Override
public void onNext(Movie movie) {
movieAdapter.addItem(movie);
}
};
RetrofitHelper.getInstance().getMovies(subscriber, 0, 20);
}
public void refreshData() {
getMovies();
}
private void initData() {
contentViewVisibility = new ObservableField<>();
progressBarVisibility = new ObservableField<>();
errorInfoLayoutVisibility = new ObservableField<>();
exception = new ObservableField<>();
contentViewVisibility.set(View.GONE);
errorInfoLayoutVisibility.set(View.GONE);
progressBarVisibility.set(View.VISIBLE);
}
private void hideAll(){
contentViewVisibility.set(View.GONE);
errorInfoLayoutVisibility.set(View.GONE);
progressBarVisibility.set(View.GONE);
}
}
```
**MovieViewModel.java**
```java
public class MovieViewModel extends BaseObservable {
private Movie movie;
public MovieViewModel(Movie movie) {
this.movie = movie;
}
public String getCoverUrl() {
return movie.getImages().getSmall();
}
public String getTitle() {
return movie.getTitle();
}
public float getRating() {
return movie.getRating().getAverage();
}
public String getRatingText(){
return String.valueOf(movie.getRating().getAverage());
}
public String getYear() {
return movie.getYear();
}
public String getMovieType() {
StringBuilder builder = new StringBuilder();
for (String s : movie.getGenres()) {
builder.append(s + " ");
}
return builder.toString();
}
public String getImageUrl() {
return movie.getImages().getSmall();
}
@BindingAdapter({"app:imageUrl"})
public static void loadImage(ImageView imageView,String url) {
Glide.with(imageView.getContext())
.load(url)
.placeholder(R.drawable.cover)
.error(R.drawable.cover)
.into(imageView);
}
}
```
### MVVM 之 Model
**DouBanMovieService.java**
```java
public interface DouBanMovieService {
String BASE_URL = "https://api.douban.com/v2/movie/";
@GET("top250")
Observable<Response<List<Movie>>> getMovies(@Query("start") int start, @Query("count") int count);
}
```
**RetrofitHelper.java**
```java
public class RetrofitHelper {
private static final int DEFAULT_TIMEOUT = 10;
private Retrofit retrofit;
private DouBanMovieService movieService;
OkHttpClient.Builder builder;
/**
* 获取RetrofitHelper对象的单例
* */
private static class Singleton {
private static final RetrofitHelper INSTANCE = new RetrofitHelper();
}
public static RetrofitHelper getInstance() {
return Singleton.INSTANCE;
}
public RetrofitHelper() {
builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(DouBanMovieService.BASE_URL)
.build();
movieService = retrofit.create(DouBanMovieService.class);
}
public void getMovies(Subscriber<Movie> subscriber, int start, int count) {
movieService.getMovies(start, count)
.map(new Func1<Response<List<Movie>>, List<Movie>>() {
@Override
public List<Movie> call(Response<List<Movie>> listResponse) {
return listResponse.getSubjects();
}
})
.flatMap(new Func1<List<Movie>, Observable<Movie>>() {
@Override
public Observable<Movie> call(List<Movie> movies) {
return Observable.from(movies);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
}
```
还有 entity 类,这里就不贴出来了。
| 1 |
hantsy/spring-r2dbc-sample | Code samples for demonstrating R2dbc, Spring R2dbc, and Spring Data R2dbc. | r2dbc r2dbc-h2 r2dbc-mssql r2dbc-mysql r2dbc-oracle r2dbc-postgresql spring spring-boot spring-data-r2dbc testcontainers | # Spring R2dbc Example
>This repository contains the latest changes in the Spring R2dbc(part of Spring Framework 5.3), Spring Data R2dbc 1.2 and Spring Boot 2.4.
I have created several R2dbc examples in the [spring-reactive-sample](https://github.com/hantsy/spring-reactive-sample/) repository since it was born. But Spring Data R2dbc evolved very quickly, thre are plenty of breaking changes introduced since Spring 5.2 and Spring Data R2dbc 1.2.
Compare to the Spring Data R2dbc 1.1, some breaking changes are notable.
* The old DatabaseClient in Spring Data R2dbc 1.1 was split into two parts, a simple new `DatabaseClient` is part of Spring framework, as an alternative of Jdbc.
* Another part of the old DatabaseClient is reorganized into a new class `R2dbcEntityTemplate` which acts as the role of `JdbcTemplate`.
## Notes
* [Introduction to R2dbc](./docs/intro.md)
* [Working with Relational Database using R2dbc DatabaseClient](./docs/database-client.md)
* [*Update*: Accessing RDBMS with Spring Data R2dbc](./docs/data-r2dbc.md)
* [Data Auditing with Spring Data R2dbc](./docs/auditing.md)
* [Dealing with Postgres specific Json/Enum type and NOTIFY/LISTEN with R2dbc](./docs/pg.md)
* [Building Chat Application with R2dbc and Postgres](./docs/chat.md)
## Sample Codes
| Example | Description |
|---|---|
| [connection-factories](https://github.com/hantsy/spring-r2dbc-sample/tree/master/connection-factories) | R2dbc driver's `ConnectionFactory` examples for MySQL, H2, PostgreSQL, MSSQL, Oracle, etc|
| [database-client](https://github.com/hantsy/spring-r2dbc-sample/tree/master/database-client) | Spring R2dbc `DatabaseClient` example |
| [data-r2dbc-entitytemplates](https://github.com/hantsy/spring-r2dbc-sample/tree/master/data-r2dbc-entitytemplate) | Spring Data R2dbc `R2dbcEntityTemplate` example |
| [data-r2dbc-repositories](https://github.com/hantsy/spring-r2dbc-sample/tree/master/data-r2dbc-repositories) | Spring Data R2dbc `R2dbcRepository` interface example |
| [entitycallbacks](https://github.com/hantsy/spring-r2dbc-sample/tree/master/entitycallbacks) | Spring Data R2dbc `BeforeConvertEntityCallback`, `AfterConvertEntityCallback`, etc. |
| [testcontainers](https://github.com/hantsy/spring-r2dbc-sample/tree/master/testcontainers) | Spring Data R2dbc `@DataR2dbcTest` with Testcontainers. |
| [boot](https://github.com/hantsy/spring-r2dbc-sample/tree/master/boot) | Spring Boot example (with Postgres specific `Enum`, `Json`, `NOTIFY/LISTEN`, etc.)|
| [boot-oracle](https://github.com/hantsy/spring-r2dbc-sample/tree/master/boot-oracle) | Spring Boot with Oracle Example|
| [boot-filepart](https://github.com/hantsy/spring-r2dbc-sample/tree/master/boot-filepart) | Spring Boot FilePart example, Postgres `bytea` type mapping to `byte[]`, `ByteBuffer`, R2dbc `Blob`|
| [r2dbc-migrate](https://github.com/hantsy/spring-r2dbc-sample/tree/master/r2dbc-migrate) | [R2dbc Migrate](https://github.com/nkonev/r2dbc-migrate) example|
| [auditing](https://github.com/hantsy/spring-r2dbc-sample/tree/master/auditing) | Spring Data R2dbc Auditing example |
| [kotlin-co](https://github.com/hantsy/spring-r2dbc-sample/tree/master/kotlin-co) | Kotlin Coroutines example |
| [jooq](https://github.com/hantsy/spring-r2dbc-sample/tree/master/jooq) | R2dbc and JOOQ example |
| [jooq-kotlin-co-gradle](https://github.com/hantsy/spring-r2dbc-sample/tree/master/jooq-kotlin-co-gradle) | R2dbc/JOOQ/Kotlin Coroutines and Gradle generator config example |
| [bookstore](https://github.com/hantsy/spring-r2dbc-sample/tree/master/bookstore) | **(WIP)** An example to track the associations support of Spring Data R2dbc |
## Reference
* [pgjdbc/r2dbc-postgresql](https://github.com/pgjdbc/r2dbc-postgresql)
* [R2dbc spec ](https://r2dbc.io/spec/0.8.2.RELEASE/spec/html/)
* [A Practical Guide to MySQL JSON Data Type By Example](https://www.mysqltutorial.org/mysql-json/)
* [Convert between Java enums and PostgreSQL enums](https://www.gotoquiz.com/web-coding/programming/java-programming/convert-between-java-enums-and-postgresql-enums/)
* [Java & Postgres enums - How do I make them work together for update?](https://stackoverflow.com/questions/40356750/java-postgres-enums-how-do-i-make-them-work-together-for-update)
* [How to delete an enum type value in postgres?](https://stackoverflow.com/questions/25811017/how-to-delete-an-enum-type-value-in-postgres)
* [Create a type if not exist Postgresql](https://stackoverflow.com/questions/56647514/create-a-type-if-not-exist-postgresql)
* [jOOQ#12218: Reactive transaction with Spring and R2dbc](https://github.com/jOOQ/jOOQ/issues/12218)
| 0 |
CompEvol/beast2 | Bayesian Evolutionary Analysis by Sampling Trees | bayesian-inference beast evolution java mcmc phylogenetics | BEAST 2
=======
[![Build Status](https://github.com/CompEvol/beast2/workflows/Core%20tests/badge.svg)](https://github.com/CompEvol/beast2/actions?query=workflow%3A%22Core+tests%22)
BEAST is a cross-platform program for Bayesian inference using MCMC of
molecular sequences. It is entirely oriented towards rooted,
time-measured phylogenies inferred using strict or relaxed molecular
clock models. It can be used as a method of reconstructing phylogenies
but is also a framework for testing evolutionary hypotheses without
conditioning on a single tree topology. BEAST uses MCMC to average
over tree space, so that each tree is weighted proportional to its
posterior probability. We include a simple to use user-interface
program for setting up standard analyses and a suit of programs for
analysing the results.
NOTE: This directory contains the BEAST 2 source code, and is
therefore of interest primarily to BEAST 2 developers. For binary
releases, user tutorials and other information you should visit the
project website at [beast2.org](https://www.beast2.org).
Development Rules and Philosophy
--------------------------------
Aspects relating to BEAST 2 development such as coding style, version
numbering and design philosophy are discussed on the BEAST 2 web page at
[beast2.org/package-development-guide/core-development-rules](https://www.beast2.org/package-development-guide/core-development-rules/).
License
-------
BEAST 2 is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. A copy of the license is contained
in the file COPYING, located in the root directory of this repository.
This software is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License contained in the file COPYING for more
details.
| 0 |
minerllabs/minerl | MineRL Competition for Sample Efficient Reinforcement Learning - Python Package | null | # The [MineRL](http://minerl.io) Python Package
[![Documentation Status](https://readthedocs.org/projects/minerl/badge/?version=latest)](https://minerl.readthedocs.io/en/latest/?badge=latest)
[![Downloads](https://pepy.tech/badge/minerl)](https://pepy.tech/project/minerl)
[![PyPI version](https://badge.fury.io/py/minerl.svg)](https://badge.fury.io/py/minerl)
[!["Open Issues"](https://img.shields.io/github/issues-raw/minerllabs/minerl.svg)](https://github.com/minerllabs/minerl/issues)
[![GitHub issues by-label](https://img.shields.io/github/issues/minerllabs/minerl/bug.svg?color=red)](https://github.com/minerllabs/minerl/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3Abug)
[![Discord](https://img.shields.io/discord/565639094860775436.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.gg/BT9uegr)
Python package providing easy to use Gym environments and data access for training agents in Minecraft.
Curious to see what people have done with MineRL? See [this page where we collect projects using MineRL](https://minerl.readthedocs.io/en/latest/notes/useful-links.html). **Got a project using MineRL (academic or fun hobby project)?** Edit [this file](https://github.com/minerllabs/minerl/blob/dev/docs/source/notes/useful-links.rst), add links to your projects and create a PR!
To get started with MineRL, [check out the docs here](http://minerl.io/docs/)!
## MineRL Versions
MineRL consists of three unique versions, each with a slightly different sets of features. See full comparison [here](https://minerl.readthedocs.io/en/v1.0.0/notes/versions.html).
* v1.0: [[Code](https://github.com/minerllabs/minerl)][[Docs](https://minerl.readthedocs.io/en/latest/)]
This version you are looking at. Needed for the [OpenAI VPT](https://github.com/openai/Video-Pre-Training) models and the [MineRL BASALT 2022](https://www.aicrowd.com/challenges/neurips-2022-minerl-basalt-competition) competition.
* v0.4: [[Code](https://github.com/minerllabs/minerl/tree/v0.4)][[Docs](https://minerl.readthedocs.io/en/v0.4.4/)]
Version used in the 2021 competitions (Diamond and BASALT). Supports the original [MineRL-v0 dataset](https://arxiv.org/abs/1907.13440). Install with `pip install minerl==0.4.4`
* v0.3: [[Code](https://github.com/minerllabs/minerl/tree/pypi_0.3.7)][[Docs](https://minerl.readthedocs.io/en/v0.3.7/)]
Version used prior to 2021, including the first two MineRL competitions (2019 and 2020). Supports the original [MineRL-v0 dataset](https://arxiv.org/abs/1907.13440). Install with `pip install minerl==0.3.7`
## Installation
Install [requirements](https://minerl.readthedocs.io/en/latest/tutorials/index.html) (Java JDK 8 is **required**. Mac may require [additional steps](https://github.com/minerllabs/minerl/issues/659#issuecomment-1306635414)) and then install MineRL with
```
pip install git+https://github.com/minerllabs/minerl
```
## Basic Usage
Can be used much like any Gym environment:
```python
import gym
import minerl
# Uncomment to see more logs of the MineRL launch
# import coloredlogs
# coloredlogs.install(logging.DEBUG)
env = gym.make("MineRLBasaltBuildVillageHouse-v0")
obs = env.reset()
done = False
while not done:
ac = env.action_space.noop()
# Spin around to see what is around us
ac["camera"] = [0, 3]
obs, reward, done, info = env.step(ac)
env.render()
env.close()
```
Check the [documentation](https://minerl.readthedocs.io/en/latest) for further examples and notes.
## Major changes in v1.0
- New Minecraft version (11.2 -> 16.5)
- Larger resolution by default (64x64 -> 640x360)
- Near-human action-space: no more `craft` and `smelt` actions. Only GUI and mouse control (camera action moves mouse around).
- Observation space is only pixels, no more inventory observation by default.
| 1 |
AlfrescoArchive/activiti-spring-boot-samples | null | null | # activiti-spring-boot-samples
Examples of how to use spring boot with com.activiti
Make sure you have alfresco-internal maven reposiotry configured in your .m2/settings.xml
```xml
<servers>
<server>
<id>alfresco-internal</id>
<username>YOUR-USERNAME</username>
<password>YOUR-PASSWORD</password>
<configuration></configuration>
</server>
</servers>
<mirrors>
<mirror>
<id>alfresco-internal</id>
<name>Nexus Public Mirror</name>
<url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-enterprise-releases/</url>
<mirrorOf>*</mirrorOf>
</mirror>
</mirrors>
```
| 0 |
GoogleChromeLabs/cronet-sample | A sample for the Cronet library | null | Cronet Sample
===================================
[Cronet](https://chromium.googlesource.com/chromium/src/+/master/components/cronet?autodive=0%2F%2F)
is Chromium's Networking stack packaged as a library. This sample app shows how to use the library.
### Getting Started
---------------
1. Clone or download this repository.
2. Import the project in Android Studio (File → New →
Import Project) by selecting the top level build.gradle file inside the
"android" directory.
3. Connect a physical Android device or start an emulator.
4. Run the app from Android Studio by pressing the "run" (green triangle)
button. Alternatively,
run "gradlew :app:installDebug" from the command line inside the "android"
directory.
### License
---------------
```
Copyright 2018 Google, Inc.
Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for
additional information regarding copyright ownership. The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
```
| 1 |
googletez/inapp-payment-samples | null | null | # inapp-payment-samples | 0 |
odrotbohm/rest-microservices | Sample for Spring Boot based REST microservices | null | null | 1 |
se-edu/addressbook-level3 | :ab::three: Address Book sample application (Level 3) | education java javafx students | [![CI Status](https://github.com/se-edu/addressbook-level3/workflows/Java%20CI/badge.svg)](https://github.com/se-edu/addressbook-level3/actions)
![Ui](docs/images/Ui.png)
* This is **a sample project for Software Engineering (SE) students**.<br>
Example usages:
* as a starting point of a course project (as opposed to writing everything from scratch)
* as a case study
* The project simulates an ongoing software project for a desktop application (called _AddressBook_) used for managing contact details.
* It is **written in OOP fashion**. It provides a **reasonably well-written** code base **bigger** (around 6 KLoC) than what students usually write in beginner-level SE modules, without being overwhelmingly big.
* It comes with a **reasonable level of user and developer documentation**.
* It is named `AddressBook Level 3` (`AB3` for short) because it was initially created as a part of a series of `AddressBook` projects (`Level 1`, `Level 2`, `Level 3` ...).
* For the detailed documentation of this project, see the **[Address Book Product Website](https://se-education.org/addressbook-level3)**.
* This project is a **part of the se-education.org** initiative. If you would like to contribute code to this project, see [se-education.org](https://se-education.org#https://se-education.org/#contributing) for more info.
| 1 |
Bahmni/OpenElis | Fork of OpenELIS for managing Lab workflows (Tests, Results, Samples, etc). | emr hacktoberfest hospital-management-system java social-impact tech4good | OpenElis
========
[![Build and Publish OpenELIS](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis.yml/badge.svg)](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis.yml)
[![Build and Publish OpenELIS Demo DB](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis_demoDB.yml/badge.svg)](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis_demoDB.yml)
[![Build and Publish OpenELIS Fresh DB](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis_freshDB.yml/badge.svg)](https://github.com/Bahmni/OpenElis/actions/workflows/build_publish_openelis_freshDB.yml)
forked from OpenElis_v3.1_r2013_02_21 branch in svn
*Requirements to build OpeneLIS*
* `java` version <= "1.7"
* `ant` version <= "1.9.1"
* `ruby` version <= "2.2" and `gem install compass`
*To build OpenElis run*
* `ant dist` Creates OpenELIS War
* `ant setupDB test test-only dist` Creates clinlims database in postgres, runs tests, and then creates OpenELIS War
* `./scripts/vagrant-deploy.sh` Create OpenELIS War and deploys it to your vagrant's tomcat
* `./scripts/vagrant-database.sh` Runs Liquibase migration script in your vagrant
## Bahmni OpenELIS (bahmni-lab) docker image
Docker images for [OpenELIS](https://hub.docker.com/r/bahmni/openelis/tags) and it's [database](https://hub.docker.com/r/bahmni/openelis-db/tags) are built using [Github Actions](/.github/workflows).
Resources to build the following docker images can be found in the [package](/package) directory.
1. bahmni/openelis
2. bahmni/openelis-db:fresh
3. bahmni/openelis-db:demo
Transifex Configuration
===========================
Transifex is a web based translation platform where one can do the translations and can be pulled into the codebase.
[Link](http://docs.transifex.com/client/config/#transifexrc) to setup the Transifex Client
* `tx pull -a` downloads the property files
For more information please refer this [link](https://bahmni.atlassian.net/wiki/display/BAH/Translating+Bahmni)
Technical issues with the codebase
======================================
- Transaction and Hibernate session management
- Pagination handled via HttpSession
- Code duplication in various places (need examples here)
- ResultValidationPaging, ResultsPaging and AnalyzerResultsPaging. Same copy-pasted code with very minor difference.
Functional changes made by us
=============================
- The order should contain the panel along with the tests. Hence making panel more than convenience tool for selecting multiple tests.
- AtomFeed based integration with OpenMRS and OpenERP
- REST endpoint for Patient, LabResults
- Added functionality to validate test results by a particular accession number. Also you can see items to be validated across all test sections.
Technical improvements
======================
- Added ant buld
- Shortcircuited all calls to Session.clear
| 0 |
kbastani/service-block-samples | Spring Cloud Function Service Block Samples | null | # Spring Cloud Function Service Block Samples
This repository contains a collection of service block examples that will help you learn how to use Spring Cloud Function in your microservice architecture.
## What are Service Blocks?
Service blocks are cloud-native applications that share many characteristics with microservices. The key difference with microservices is that a service block is a self-contained system that has multiple independently deployable units—mixing together serverless functions with containers.
![Service block example](http://i.imgur.com/yLwadYi.png)
While microservices can be created entirely as serverless functions, a service block focuses on a contextual model that combines together traditional "always-on" applications with portable on-demand functions.
## Usage
This repository contains a collection of experimental sample projects that demonstrate the service block patterns. Check the README of each service block in this repository to see the status of the project.
- [Basic Service Block](https://github.com/kbastani/service-block-samples/tree/master/basic-block)
- [CQRS Service Block](https://github.com/kbastani/service-block-samples/tree/master/cqrs-block)
An introduction to service block architectures can be found _here_.
## License
This project is licensed under Apache License 2.0. | 0 |
primefaces/primefaces-test | Sample project to provide test cases | null | ![PrimeFaces icon](https://www.primefaces.org/wp-content/uploads/2016/10/prime_logo_new.png)
# PrimeFaces Test
This is a sample maven project that uses <strong>Latest PrimeFaces Release</strong> version. If you have a PrimeFaces issue, please download or fork this project. Then, you should change these files by yourself so that PrimeFaces Team can see your problem. Finally, you can send a link or attach the project. <strong>Please make sure that project is runnable with the command below.</strong>
You can execute the sample with <strong>mvn jetty:run</strong> command and hit <strong>http://localhost:8080/</strong> to run the page.
### JSF Versions
***
Per default the application uses Mojarra 2.2.x.
You can also use other versions with the available maven profiles: myfaces22, myfaces23, myfaces23next, mojarra23
`mvn clean jetty:run -Pmyfaces22`
`mvn clean jetty:run -Pmyfaces23`
`mvn clean jetty:run -Pmyfaces23next`
`mvn clean jetty:run -Pmojarra22`
`mvn clean jetty:run -Pmojarra23`
### Server Port
***
By default the application runs on port 8080 but if you would like to use a different port you can pass `-Djetty.port=5000` like:
`mvn clean jetty:run -Djetty.port=5000`
### Jakarta EE10 Version
***
The branch `jakarta` contains a PrimeFaces Test setup to run again Jakarta EE10 profile using Jetty 11. You can also use other versions with the available maven profiles: mojarra40, myfaces40
`mvn clean jetty:run -mojarra40`
`mvn clean jetty:run -myfaces40`
### JPA Lazy Datatable
***
The branch `jpa` contains a PrimeFaces Test setup to run with JPA using the JPA LazyDatatable advanced example.
### Visual Studio Code Quickstart
***
See the [quickstart guide for running in Visual Studio Code](./vscode-quickstart.md) for more information.
| 1 |
aws-containers/retail-store-sample-app | Sample application for demonstrating container platforms and related technology | amazon-eks aws containers docker docker-compose golang java javascript kubernetes | # AWS Containers Retail Sample
This is a sample application designed to illustrate various concepts related to containers on AWS. It presents a sample retail store application including a product catalog, shopping cart and checkout.
It provides:
- A distributed component architecture in various languages and frameworks
- Utilization of a variety of different persistence backends for different components like MySQL, DynamoDB and Redis
- The ability to run in various container orchestration technologies like Docker Compose, Kubernetes etc.
- Pre-built containers image for both x86-64 and ARM64 CPU architectures
- All components instrumented for Prometheus metrics and OpenTelemetry OTLP tracing
- Support for Istio on Kubernetes
- Load generator which exercises all of the infrastructure
**This project is intended for educational purposes only and not for production use.**
![Screenshot](/docs/images/screenshot.png)
## Application Architecture
The application has been deliberately over-engineered to generate multiple de-coupled components. These components generally have different infrastructure dependencies, and may support multiple "backends" (example: Carts service supports MongoDB or DynamoDB).
![Architecture](/docs/images/architecture.png)
| Component | Language | Container Image | Description |
|-----------|----------|---------------------|-----------------------------------------------------------------------------|
| ![ui workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-ui.yml/badge.svg) | Java | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-ui) | Aggregates API calls to the various other services and renders the HTML UI. |
| ![catalog workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-catalog.yml/badge.svg) | Go | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-catalog) | Product catalog API |
| ![cart workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-cart.yml/badge.svg) | Java | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-cart) | User shopping carts API |
| ![orders workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-orders.yml/badge.svg) | Java | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-orders) | User orders API |
| ![checkout workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-checkout.yml/badge.svg) | Node | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-checkout) | API to orchestrate the checkout process |
| ![assets workflow](https://github.com/aws-containers/retail-store-sample-app/actions/workflows/ci-assets.yml/badge.svg) | Nginx | [Link](https://gallery.ecr.aws/aws-containers/retail-store-sample-assets) | Serves static assets like images related to the product catalog |
## Quickstart
The following sections provide quickstart instructions for various platforms. All of these assume that you have cloned this repository locally and are using a CLI thats current directory is the root of the code repository.
### Kubernetes
This deployment method will run the application in an existing Kubernetes cluster.
Pre-requisites:
- Kubernetes cluster
- `kubectl` installed locally
Use `kubectl` to run the application:
```
kubectl apply -f https://raw.githubusercontent.com/aws-containers/retail-store-sample-app/main/dist/kubernetes/deploy.yaml
kubectl wait --for=condition=available deployments --all
```
Get the URL for the frontend load balancer like so:
```
kubectl get svc ui
```
To remove the application use `kubectl` again:
```
kubectl delete -f https://raw.githubusercontent.com/aws-containers/retail-store-sample-app/main/dist/kubernetes/deploy.yaml
```
### Docker Compose
This deployment method will run the application on your local machine using `docker-compose`, and will build the containers as part of the deployment.
Pre-requisites:
- Docker installed locally
Change directory to the Docker Compose deploy directory:
```
cd dist/docker-compose
```
Use `docker compose` to run the application containers:
```
MYSQL_PASSWORD='<some password>' docker compose --file dist/docker-compose/docker-compose.yml up
```
Open the frontend in a browser window:
```
http://localhost:8888
```
To stop the containers in `docker compose` use Ctrl+C. To delete all the containers and related resources run:
```
docker compose -f dist/docker-compose/docker-compose.yml down
```
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## License
This project is licensed under the MIT-0 License.
This package depends on and may incorporate or retrieve a number of third-party
software packages (such as open source packages) at install-time or build-time
or run-time ("External Dependencies"). The External Dependencies are subject to
license terms that you must accept in order to use this package. If you do not
accept all of the applicable license terms, you should not use this package. We
recommend that you consult your company’s open source approval policy before
proceeding.
Provided below is a list of External Dependencies and the applicable license
identification as indicated by the documentation associated with the External
Dependencies as of Amazon's most recent review.
THIS INFORMATION IS PROVIDED FOR CONVENIENCE ONLY. AMAZON DOES NOT PROMISE THAT
THE LIST OR THE APPLICABLE TERMS AND CONDITIONS ARE COMPLETE, ACCURATE, OR
UP-TO-DATE, AND AMAZON WILL HAVE NO LIABILITY FOR ANY INACCURACIES. YOU SHOULD
CONSULT THE DOWNLOAD SITES FOR THE EXTERNAL DEPENDENCIES FOR THE MOST COMPLETE
AND UP-TO-DATE LICENSING INFORMATION.
YOUR USE OF THE EXTERNAL DEPENDENCIES IS AT YOUR SOLE RISK. IN NO EVENT WILL
AMAZON BE LIABLE FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY DIRECT,
INDIRECT, CONSEQUENTIAL, SPECIAL, INCIDENTAL, OR PUNITIVE DAMAGES (INCLUDING
FOR ANY LOSS OF GOODWILL, BUSINESS INTERRUPTION, LOST PROFITS OR DATA, OR
COMPUTER FAILURE OR MALFUNCTION) ARISING FROM OR RELATING TO THE EXTERNAL
DEPENDENCIES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, EVEN
IF AMAZON HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
AND DISCLAIMERS APPLY EXCEPT TO THE EXTENT PROHIBITED BY APPLICABLE LAW.
MySQL Community Edition - [LICENSE](https://github.com/mysql/mysql-server/blob/5.7/LICENSE)
| 1 |
pravega/video-samples | Obsolete - see https://github.com/pravega/gstreamer-pravega | null |
# Pravega Video Samples
## ATTENTION - THIS REPOSITORY IS OBSOLETE
## This repository and the techniques demonstrated in it are obsolete. Those interested in video with Pravega should refer to https://github.com/pravega/gstreamer-pravega.
## Overview
![grid-sample](images/video-samples-diagram.png)
This project demonstrates methods to store, process, and read video with Pravega and Flink
which are key components of Dell EMC Streaming Data Platform (SDP).
It also includes an application that performs object detection using TensorFlow and YOLO.
## Components
- Pravega: Pravega provides a new storage abstraction - a stream - for continuous and unbounded data.
A Pravega stream is a durable, elastic, append-only, unbounded sequence of bytes that has good performance and strong consistency.
Pravega provides dynamic scaling that can increase and decrease parallelism to automatically respond
to changes in the event rate.
For more information, see <http://pravega.io>.
- Flink: Apache Flink® is an open-source stream processing framework for distributed, high-performing, always-available, and accurate data streaming applications.
See <https://flink.apache.org> for more information.
- Docker: This demo uses Docker and Docker Compose to greatly simplify the deployment of the various
components on Linux and/or Windows servers, desktops, or even laptops.
For more information, see <https://en.wikipedia.org/wiki/Docker_(software)>.
## Building and Running the Video Samples
In the steps below, only some sections will apply to your environment.
These are identified as follows:
- **(Local)**: A local workstation deployment of Pravega (standalone or Docker).
- **(SDP)**: A deployment of Streaming Data Platform (SDP).
- **(GPU)**: GPUs are available on SDP Kubernetes worker nodes.
### Download this Repository
```
cd
git clone https://github.com/pravega/video-samples
cd video-samples
```
### Install Operating System
Install Ubuntu 18.04 LTS. Other operating systems can also be used but the commands below have only been tested
on this version.
### Install Java 8
```
apt-get install openjdk-8-jdk
```
### (Optional) Install IntelliJ
Install from <https://www.jetbrains.com/idea>.
Enable the Lombok plugin.
Enable Annotations (settings -> build, execution, deployment, -> compiler -> annotation processors).
### (Local) Install Docker and Docker Compose
See <https://docs.docker.com/install/linux/docker-ce/ubuntu/>
and <https://docs.docker.com/compose/install/>.
### (Local) Run Pravega
This will run a development instance of Pravega locally.
Note that the default *standalone* Pravega used for development is likely insufficient for testing video because
it stores all data in memory and quickly runs out of memory.
In the command below, replace x.x.x.x with the IP address of a local network interface such as eth0.
```
cd pravega-docker
export HOST_IP=x.x.x.x
docker-compose up -d
```
You must also create the Pravega scope. This can be performed using the REST API.
```
curl -X POST -H "Content-Type: application/json" -d '{"scopeName":"examples"}' http://localhost:10080/v1/scopes
```
You can view the Pravega logs with `docker-compose logs --follow`.
You can view the stream files stored on Tier 2 `ls -h -R /tmp/pravega-tier2`.
#### Alternative for low-memory systems
If your system does not have enough memory to run all of the Pravega containers, you may run
the standalone container using the following commands.
```
export HOST_IP=x.x.x.x
docker run -it --rm -e HOST_IP -p 9090:9090 -p 10080:9091 -p 12345:12345 pravega/pravega:latest standalone
curl -X POST -H "Content-Type: application/json" -d '{"scopeName":"examples"}' http://localhost:10080/v1/scopes
```
### Install Pravega Client and Pravega Flink Connector Libraries (optional)
This step is only required when using pre-release versions of Pravega and/or SDP.
It will install required libraries in the local Maven repository.
```
cd
git clone https://github.com/pravega/pravega
pushd pravega
git checkout r0.7
./gradlew install
popd
git clone https://github.com/pravega/flink-connectors
pushd flink-connectors
git checkout r0.7
./gradlew install
popd
```
### (SDP) Ensure Kubernetes Connectivity
Ensure that the following command works. Refer to the SDP User's Guide for details.
```
kubectl get nodes
```
### (SDP) Configure SDP Authentication
Obtain the Pravega authentication credentials.
This will be needed to allow applications on your local workstations to connect to Pravega.
```
export NAMESPACE=examples
kubectl get secret ${NAMESPACE}-pravega -n ${NAMESPACE} -o jsonpath="{.data.keycloak\.json}" | base64 -d > ${HOME}/keycloak.json
chmod go-rw ${HOME}/keycloak.json
```
**Note:** When running the example applications, you must set the following environment variables.
This can be done by setting the IntelliJ run configurations. If you set this in IntelliJ,
you must manually replace `${HOME}` with your actual home directory.
```
export pravega_client_auth_method=Bearer
export pravega_client_auth_loadDynamic=true
export KEYCLOAK_SERVICE_ACCOUNT_FILE=${HOME}/keycloak.json
```
### Determine the Pravega Controller URL
- Local:
`tcp://127.0.0.1:9090`
- SDP, TLS enabled:
The DNS name can be retrieved by running the following command and using the HOST value.
`kubectl get ingress -n nautilus-pravega pravega-controller`
The controller will have the form `tls://pravega-controller.example.com:443`.
- SDP, TLS disabled:
The DNS name can be retrieved by running:
`kubectl get -n nautilus-pravega svc nautilus-pravega-controller -o go-template=$'{{index .metadata.annotations "external-dns.alpha.kubernetes.io/hostname"}}\n'`
The controller will have the form `tcp://pravega-controller.example.com:9090`.
### Install Flink Image with TensorFlow
#### Build Flink Image with TensorFlow (optional)
This is only required if you wish to further customize the Flink image.
```
cd GPUTensorflowImage
docker build .
```
Tag the image, push it, and then edit GPUTensorflowImage/ClusterFlinkImage.yaml with the
correct tag.
#### (GPU) Enable TensorFlow GPU Support
If you have GPUs on the SDP worker nodes, then set the following in gradle.properties.
```
enableGPU=true
```
### Running the Examples in IntelliJ (optional)
Run the Flink `VideoDataGeneratorJob` using the following parameters:
```
--controller
tcp://127.0.0.1:9090
--output-minNumSegments
6
--output-stream
examples/video1
```
Next, run a streaming Flink job that reads all video streams and combines them into a single video stream
where each image is composed of the input images in a square grid.
Run the Flink `MultiVideoGridJob` with the following parameters:
```
--controller
tcp://127.0.0.1:9090
--parallelism
2
--output-minNumSegments
6
--input-stream
examples/video1
--output-stream
examples/grid1
```
Run the Flink `VideoReaderJob` using the following parameters:
```
--jobClass
io.pravega.example.videoprocessor.VideoReaderJob
--controller
tcp://127.0.0.1:9090
--parallelism
2
--input-stream
examples/grid1
```
This will write a subset of images to `/tmp/camera*.png`.
Below shows the example output from 4 camera feeds.
Note that image backgrounds are filled with random bytes to make them incompressible for testing purposes.
![grid-sample](images/grid-sample.png)
### Running the Examples in SDP (optional)
1. Create and edit the file scripts/env-local.sh that defines your environment.
```
cp scripts/env-example.sh scripts/env-local.sh
```
2. Build and deploy the Flink jobs.
```
scripts/redeploy.sh
```
You can edit the file (charts/multi-video-grid-job/values.yaml)[charts/multi-video-grid-job/values.yaml]
to change various parameters such as the image dimensions, frames per second, and
number of cameras.
If you make changes to the source code or values.yaml, you may redeploy your application by repeating step 2.
Note: You may use the script `scripts/uninstall.sh` to delete your Flink application and cluster.
This will also delete any savepoints.
### Viewing Logs in SDP (optional)
To troubleshoot a failed job, begin with the following command.
```
kubectl describe FlinkApplication -n examples multi-video-grid
```
When Flink applications write to stdout, stderr, or use slf4j logging, the output will be
available in one of several locations.
Output written by the driver (e.g. directly called by `main()`) will be available in the job's log
and can be viewed with the following command.
```
kubectl logs jobs/video-data-generator-app-v1-1 -n examples | less
```
Output written by operators (e.g. `map()`) will be available in the Flink task manager log
and can be viewed with the following command.
```
kubectl logs video-data-generator-taskmanager-0 -n examples -c server | less
```
When troubleshooting application issues, you should also review the Flink job manager log,
which can be viewed with the following command.
```
kubectl logs video-data-generator-jobmanager-0 -n examples -c server | less
```
You may want to use the kubectl logs `--follow`, `--tail`, and `--previous` flags.
You may also use the Kubernetes UI to view these logs.
## Camera Recorder Application (optional)
The Camera Recorder application reads images from a USB camera and writes them to
a Pravega stream.
It uses the same video encoding protocol as the Flink applications in this project.
It currently does not support chunking so each image must be less than 1 MB after JSON encoding.
To start it:
```
export PRAVEGA_CONTROLLER_URI=tcp://127.0.0.1:9090
export OUTPUT_STREAM_NAME=video1
./gradlew camera-recorder:run
```
See (AppConfiguration.java)[camera-recorder/src/main/java/io/pravega/example/camerarecorder/AppConfiguration.java]
for more options.
## Video Player Application (optional)
The Video Player application reads images from a Pravega stream and displays
them in a window on the screen.
It uses the same video encoding protocol as the Flink applications in this project.
It currently does not support images split over multiple chunks.
To start it:
```
export PRAVEGA_CONTROLLER_URI=tcp://127.0.0.1:9090
export INPUT_STREAM_NAME=grid1
export CAMERA=1000
./gradlew video-player:run
```
See (AppConfiguration.java)[video-player/src/main/java/io/pravega/example/videoplayer/AppConfiguration.java]
for more options.
# Jupyter Hub
Jupyter Hub provides a Python notebook interface.
See [Jupyter Hub](jupyterhub/README.md).
# Chunking
See [Chunking](chunking.md).
# Object Detection
![object-detection-arch](images/object-detection-arch.png)
This is for running the object detection application on SDP. YOLO model and Tensorflow are being used for object detection.
## Running on IntelliJ
Assuming you have the CameraRecorder, and VideoPlayer running, run the FlinkObjectDetectorJob using following parameters:
```
--controller
tcp://127.0.0.1:9090
--scope
examples
--input-stream
examples-raw
--output-stream
examples-detected
--CAMERA
3
--startAtTail
true
```
## Running on SDP
Refer to **Running the Examples in SDP** and update the file to use **object-detector-job**
# Facial Recognition and Authentication
The object detection use case has been extended to facial recognition and authentication. This involves managing a in-memory database of valid personnel, and matching scanned badges with records and recognized face. This creates a multi-factor authentication system which is more secure.
## Components
- Adding personnel: Personnel records can be added to in-memory database to match with scanned badges and faces.
![adding-personnel](images/add_personnel.png)
- Pass Case: Upon matching a scanned badge and face to existing personnel records, passes the the authenticated system.
![pass-case](images/pass_face_recognition.png)
- Fail Case: Upon matching a scanned badge and face to existing personnel records, fails the the authenticated system. Can be modified to take specific actions to deal with failing authentication.
![fail-case](images/fail_face_recognition.png)
## Running on SDP and IntelliJ
Run CameraRecorderTwoStreams if you only have a single webcam as show below:
```
export PRAVEGA_SCOPE=examples
export OUTPUT_STREAM_NAME=face-detection-raw
export PRAVEGA_CONTROLLER_URI=tcp://YOUR_COUNTROLLER_URI:9090
export IS_CREATE_SCOPE=false
export CAMERA=3
export CAMERA_DEVICE_NUMBER=0
export FRAMES_PER_SEC=3
```
Else run CameraRecorder with updated stream name for each webcam used in the charts
For a Facial Recognition App, run with following parameters for FlinkFaceRecognizerJob on IntelliJ:
```
--controller
tcp://CONTROLLER_URI:9090
--scope
examples
--input-stream
STREAM_NAME_FACE_WEBCAM
--output-stream
face-detection-detected
--person-database-stream
person-database-transaction
--CAMERA
3
--startAtTail
true
--readerParallelism
1
--parallelism
1
--checkpointIntervalMs
10000
```
Note: Make sure to update CONTROLLER_URI, and STREAM_NAME_FACE_WEBCAM with stream name for webcam that scans faces.
For a Facial Recognition with authentication, run with following parameters for BadgeSecurityJob on IntelliJ:
```
--controller
tcp://CONTROLLER_URI:9090
--scope
examples
--input-stream
STREAM_NAME_FACE_WEBCAM
--output-stream
face-detection-detected
--person-database-stream
person-database-transaction
--badge-stream
STREAM_NAME_BADGE_WEBCAM
--CAMERA
3
--startAtTail
true
--readerParallelism
1
--parallelism
1
--checkpointIntervalMs
10000
--maxOutOfOrdernessMs
10
```
Note: Make sure to update CONTROLLER_URI, and STREAM_NAME_FACE_WEBCAM with stream name for webcam that scans faces, and STREAM_NAME_BADGE_WEBCAM with stream name for webcam that scans badges.
To add valid personnel records into the face recogniton job, run the following:
```
cd video-samples
. ./scripts/person-database/setup.sh
./scripts/person-database/populate-database.sh
```
In **setup.sh**, you can update the controller to reflect whether it is running on SDP or locally. More images of valid personnel can be added to ``./images/person-database`` with the name of person as folder name, and images of the person within.
To run on SDP, refer to **Running the Examples in SDP** and update the file to use **face-recognizer-job** for face recognition, or update the file to use **badge-recognition-job** for facial recognition with authentication
# References
- <http://pravega.io/>
| 0 |
TheGreyGhost/MinecraftByExample | Working sample code for the basic concepts in Minecraft and Forge. | null | MinecraftByExample [1.16.4]
==================
The purpose of MinecraftByExample is to give simple working examples of the important concepts in Minecraft and Forge. If you're anything like me, a good code example is worth several screens of waffling explanation, and can very quickly explain the key concepts. I also find it much easier to adapt and debug something that already works, than to have to synthesize something from scratch and spend hours trying to discover the missing bit of information I didn't know about.
I've tried to keep the code simple and obvious and to resist the urge to be clever. The examples might not be the most efficient or succinct implementation, I've deliberately left the optimization to you.
Each example is split up to be totally independent of all the others. The only part of the code which is common to more than one example is the MinecraftByExample class.
If you want more information and explanatory text about the concepts, the following links might be useful:
- [The Official Forge documentation][forgedocs] (parts of it are rather outdated but on the whole still very useful starting reference)
- [Guide to how Minecraft works][greyminecraftcoder] (explaining the key concepts for understanding vanilla code)
- [Fabric Wiki][fabricwiki] (some of it is specific to the Fabric API, but a lot of useful general info too)
- [Forge modder support forum][Forge forum] ask for advice from the experts
- [McJty tutorials][McJty] lots of step-by-step instructions / tutorial
- [Mr Crayfish Furniture Mod (lots of examples)](https://github.com/MrCrayfish/MrCrayfishFurnitureMod)
- [Cadiboo's example mod](https://github.com/Cadiboo/Example-Mod) some great tutorials for when you're starting out
#### For earlier versions, see the relevant GitHub branch:
- MBE for Forge 1.8: [1-8final][version1-8]
- MBE for Forge 1.8.9: [1-8-9final][version1-8-9]
- MBE for Forge 1.10.2: [1-10-2final][version1-10-2]
- MBE for Forge 1.11: [1-11final][version1-11]
- MBE for Forge 1.11.2: [1-11-2final][version1-11-2]
- MBE for Forge 1.12.2: [1-12-2final][version1-12-2]
- MBE for Forge 1.14.4: [1-14-4partial][version1-14-4] (partially updated only)
- MBE for Forge 1.15.2: [1-15-2][version1-15-2]
- MBE for Forge 1.16.3: [1-16-3][version1-16-3]
If you are updating from previous forge versions, you will probably find [this link][versionupdates] and [this link][versionupdates1-15] very helpful. For better or for worse, MCP decided to rename a very large number of classes (eg all Blocks Blockxxx --> xxxxBlock, etc) so this might save you a stack of time.
If you use IntelliJ, you might find these [xml mapping files][mapfiles] useful too
## List of examples
See [here](https://greyminecraftcoder.blogspot.com/2020/05/minecraft-by-example.html) for pictures of what each example looks like in-game.
### Blocks
- [MBE01][01] - a simple cube
- [MBE02][02] - a block with a more complicated shape
- [MBE03][03] - two types of blocks which vary their appearance / shape:<br>
a block (coloured signpost) with multiple variants- four colours, can be placed facing in four directions<br>
a block (3D Web) with multiple parts (multipart) similar to a vanilla fence.
- [MBE04][04] - dynamically created block models<br>
a camouflage ("secret door") block which dynamically changes its appearance to match adjacent blocks - uses IBlockModel.getQuads(), ModelBakeEvent, IForgeBakedModel and IModelData<br>
an "altimeter" block which shows the block altitude (y coordinate) on the side in digital display - as camouflage block but uses programmatic generation of quads
- [MBE05][05] - multilayer block (lantern block with transparent glass) with animated flame texture
- [MBE06][06] - several different types of block which use redstone
- [MBE08][08] - how to add a creative tab for organising your custom blocks / items
### Items
- [MBE10][10] - a simple item
- [MBE11][11] - an item with multiple variants - rendered using multiple models and multiple layers
- [MBE12][12] - an item that stores extra information in NBT, also illustrates the "in use" animation similar to drawing a bow
- [MBE15][15] - a chessboard item with 1 - 64 pieces; uses ItemOverrideList.getModelWithOverrides(), IBlockModel.getQuads() and onModelBakeEvent()
### TileEntities
- [MBE20][20] - using a tile entity to store information about a block - also shows examples of using NBT storage
- [MBE21][21] - using the TileEntityRenderer to render unusual shapes or animations
### Containers (Inventories)
- [MBE30][30] - a simple container for storing items in the world - similar to a Chest
- [MBE31][31] - a functional container such as a Furnace or Crafting Table
- [MBE32][32] - an item (bag of flowers) which can store other items inside it. Also shows how to use Capability
### Recipes (Crafting/Furnace)
- [MBE35][35] - some typical example crafting recipes and furnace (smelting) recipes
### Commands
- [MBE45][45] - custom commands
### Particles - particle effects
- [MBE50][50] - shows how to use vanilla Particles; also how to generate your own custom Particles
### Network
- [MBE60][60] - send network messages between client and server
### Capabilities
- [MBE65][65] - define new Capabilities and attach them to vanilla objects
### Testing tools
- [MBE75][75] - a tool to help you automate testing of your classes in-game.
### Entities and Models
- [MBE80][80] - Shows the basics of Models (eg PigModel), model parameters adjustable in real time using commands
- [MBE81][81] - Projectile Entities (eg snowballs, arrows)
### Miscellaneous Debugging Tools
- [DebuggingTools]- This package is a bunch of functions and tools that I use occasionally, mostly for debugging
## Usage
- You can browse directly in GitHub, or alternatively, download it as a zip and browse it locally.
- If you want to install it and compile it, the basic steps for beginners are:
1. Download the project as a zip.
2. Unzip it to an appropriate folder on your computer, such as My Documents. (Or, if you know how to fork a project on GitHub and import it into a local git repository, you can do that instead)
3. Look at Forge's README.txt file in this folder and follow the instructions to import it into Eclipse or IntelliJ IDEA.
4. Use the gradle task runClient to run or debug the project.
### How to compile and run:
1) Execute gradle task runClient to test the client installation
or
2) Execute gradle task runServer to test the dedicated server installation. (The first time you run this task it will exit without starting the server. You then need to edit the eula.txt file in the run directory, and execute runServer again.)
#### If You're Still Confused
Head over [here][more_help] if this didn't make sense to you (check comments for differences with latest versions of IDEA).
[main_classes]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample
[greyminecraftcoder]: https://greyminecraftcoder.blogspot.com/p/list-of-topics-1144.html
[forgedocs]:https://mcforge.readthedocs.org/en/latest/
[more_help]:https://suppergerrie2.com/minecraft-1-14-modding-with-forge-1-setting-up-a-dev-environment/
[01]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe01_block_simple
[02]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe02_block_partial
[03]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe03_block_variants
[04]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe04_block_dynamic_block_models
[05]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe05_block_advanced_models
[06]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe06_redstone
[08]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe08_itemgroup
[10]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe10_item_simple
[11]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe11_item_variants
[12]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe12_item_nbt_animate
[13]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe14_item_camera_transforms
[14]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe14_item_camera_transforms
[15]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe15_item_dynamic_item_model
[20]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe20_tileentity_data
[21]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe21_tileentityrenderer
[30]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe30_inventory_basic
[31]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe31_inventory_furnace
[32]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe32_inventory_item
[35]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe35_recipes
[40]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe40_hud_overlay
[45]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe45_commands
[50]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe50_particle
[60]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe60_network_messages
[65]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe65_capability
[75]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe75_testing_framework
[80]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe80_model_renderer
[81]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/mbe81_entity_projectile
[DebuggingTools]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/src/main/java/minecraftbyexample/usefultools
[Forge forum]: https://www.minecraftforge.net/forum/forum/70-modder-support/
[fabricwiki]: https://fabricmc.net/wiki/start
[McJty]: https://wiki.mcjty.eu/modding/index.php?title=YouTube-1.14
[gradle_tool_window]: https://www.jetbrains.com/idea/help/gradle-tool-window.html
[version1-8]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-8final
[version1-8-9]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-8-9final
[version1-10-2]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-10-2final
[version1-11]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-11-final
[version1-11-2]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-11-2-final
[version1-12-2]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-12-2-final
[version1-14-4]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-14-4-partial
[version1-15-2]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-15-2-final
[version1-16-3]: https://github.com/TheGreyGhost/MinecraftByExample/tree/1-16-3-final
[versionupdates]: https://gist.github.com/williewillus/353c872bcf1a6ace9921189f6100d09a
[versionupdates1-15]:https://gist.github.com/williewillus/30d7e3f775fe93c503bddf054ef3f93e
[mapfiles]: https://github.com/TheGreyGhost/MinecraftByExample/tree/master/miscellaneous/name_remappings
With thanks to these helpful folks:
alvaropp,
yooksi,
Brandon3035,
twrightsman (greekphysique),
Nephroid,
Herbix, and
Shadowfacts
## Licence Info:
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
| 1 |
boxfuse/boxfuse-sample-java-war-hello | Boxfuse Sample Hello World Java application packaged as a war file | null | boxfuse-sample-java-war-hello
=============================
Boxfuse Sample Hello World Java application packaged as a war file
## Prerequisites
- Git
- Java
- Maven
- VirtualBox
- Boxfuse
## Running
1. git clone https://github.com/boxfuse/boxfuse-sample-java-war-hello
2. cd boxfuse-sample-java-war-hello
3. mvn package
4. boxfuse run target/hello-1.0.war
Done!
Open your browser at http://localhost:8888 or simple type ```boxfuse open hello:1.0``` to see your brand new instance in action!
| 1 |
vdenotaris/spring-boot-security-saml-sample | SBS3 — A sample SAML 2.0 Service Provider built on Spring Boot. | authentication iam identity java saml spring spring-boot spring-security-saml sso | [SBS3] Spring Boot Sample SAML 2.0 Service Provider
====================
[![Build Status](https://travis-ci.org/vdenotaris/spring-boot-security-saml-sample.svg?branch=master)](https://travis-ci.org/vdenotaris/spring-boot-security-saml-sample)
[![DOI](https://zenodo.org/badge/22013861.svg)](https://zenodo.org/badge/latestdoi/22013861)
![GitHub release](https://img.shields.io/github/release/vdenotaris/spring-boot-security-saml-sample.svg)
[![GitHub forks](https://img.shields.io/github/forks/vdenotaris/spring-boot-security-saml-sample.svg)](https://github.com/vdenotaris/spring-boot-security-saml-sample/network)
[![GitHub stars](https://img.shields.io/github/stars/vdenotaris/spring-boot-security-saml-sample.svg)](https://github.com/vdenotaris/spring-boot-security-saml-sample/stargazers)
[![GitHub license](https://img.shields.io/badge/license-Apache%202-blue.svg)](https://raw.githubusercontent.com/vdenotaris/spring-boot-security-saml-sample/master/LICENSE)
---------
<img src="https://i.ibb.co/CKbFBzH/logo-small.png" align="right" />
## Project description
This project represents a sample implementation of a **SAML 2.0 Service Provider**, completely built on **Spring Framework**. In particular, it shows how to develop a web solution devised for Federated Authentication, by integrating **Spring Boot** and **Spring Security SAML**. The configuration has been completely defined using *Java annotations* (no XML).
**SSOCircle** ([ssocircle.com](http://www.ssocircle.com/en/portfolio/publicidp/)) is used as public Identity Provider for test purpose.
- **Author:** Vincenzo De Notaris ([dev@vdenotaris.com](mailto:dev@vdenotaris.com))
- **Website:** [www.vdenotaris.com](http://www.vdenotaris.com)
- **Version:** ` 2.4.0.RELEASE`
- **Last update**: December 19th, 2021
Thanks to *Vladimír Schäfer* ([github.com/vschafer](https://github.com/vschafer)) for supporting my work.
### References
#### Spring Boot
> Spring Boot makes it easy to create Spring-powered, production-grade applications and services with absolute 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.
> - **Ref.:** [http://projects.spring.io/spring-boot/](http://projects.spring.io/spring-boot/)
#### Spring Security SAML Extension
> Spring SAML Extension allows seamless inclusion of SAML 2.0 Service Provider capabilities in Spring applications. All products supporting SAML 2.0 in Identity Provider mode (e.g. ADFS 2.0, Shibboleth, OpenAM/OpenSSO, Ping Federate, Okta) can be used to connect with Spring SAML Extension.
> - **Ref.:** [http://projects.spring.io/spring-security-saml/](http://projects.spring.io/spring-security-saml/)
---------
## Changelog [new]
- Version `2.4.0.RELEASE`:
- Update to Spring Boot `2.6.1`
- Update to JUnit `5`
- Update to Log4J `2.17.0` (see: [CVE-2021-44228](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44228))
- Update to Jackson `2.13.0`
- Update to Apache Commons `4.4`
- A circular reference exists between the beans `samlEntryPoint` and `samlIDPDiscovery` that depends on the original design of the core *Spring SAML extension* library.
---------
## Walkthrough
### Run as Docker container
To make it even easier, it is possible to run the project "as-is" also as Docker container. A valid account on [SSOCircle](https://www.ssocircle.com/en/) is needed to perform the authentication process.
**Run as container building a Docker image**
Run a pre-built fat-jar:
```
docker run -it --rm -p 8080:8080 -t vdenotaris/spring-saml-sp:latest
```
or compile the code and run the application with Maven:
```
docker run -it --rm -p 8080:8080 -t vdenotaris/spring-saml-sp:2.4.0-mvn-jdk-8
```
*Note: the related Docker image is publicly available on [Docker Hub](https://hub.docker.com/r/vdenotaris/spring-saml-sp/).*
The Service Provider is deployed as web application. Enter [http://localhost:8080/](http://localhost:8080/) in a browser to see the application running.
If you’re using Docker natively on Linux, Docker for Mac, or Docker for Windows, then the web app should now be listening on port 8080 on your Docker daemon host. Point your web browser to http://localhost:8080 to find the starting page. If this doesn’t resolve, you can also try [http://127.0.0.1:8080/](http://127.0.0.1:8080/).
If you’re using Docker Machine on a Mac or Windows, use `docker-machine ip MACHINE_VM` to get the IP address of your Docker host. Then, open *http://MACHINE_VM_IP:8080* in a browser. However, please note that the Service Provider is statically registered with localhost as endpoint on SSOCircle. Thus you need to reconfigure the application.
------
### Unit tests
I would like to say thank you to *Alexey Syrtsev* ([github.com/airleks](https://github.com/airleks)) for his contribution on unit tests.
| Metric | Result |
| ------------- | -----:|
| Coverage % | 99% |
| Lines Covered | 196 |
| Total Lines | 199 |
------
### Additional notes
1. The certificate on [https://idp.ssocircle.com/](https://idp.ssocircle.com/) seems to change on a fairly regular basis. This results in the following exception.
`javax.net.ssl.SSLPeerUnverifiedException: SSL peer failed hostname validation for name: null`
To update the SSOCircle certificates within the keystore, just run:
cd src/main/resources/saml/ && sh ./update-certifcate.sh
2. Sometimes SSO Circle could display you an error during the authenticaton process. In this case, please update your federation metadata directly on [https://idp.ssocircle.com](https://idp.ssocircle.com):
> Manage Metadata > Service Provider Metadata
Remove the current record and add a new one, using your FQDN and providing a new copy of your metadata: your can retrieve them at [http://localhost:8080/saml/metadata](http://localhost:8080/saml/metadata).
3. When the project version corresponds with the Spring Boot parent version, Maven may give you a warning as follows:
> Version is duplicate of parent version.
Actually there is nothing wrong with the used configuration, thus you can just ignore that message.
---------
### License
Copyright 2021 Vincenzo De Notaris
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| 1 |
javaee-samples/javaee7-simple-sample | A simple Java EE 7 Sample | null | null | 1 |
stefoxp/head-first-design-patterns | Book's notes and samples | design-patterns exercises | # Head First - Design Patterns
This is my summary of the "Head First - Design Patterns", by Eric Freeman & Elisabeth Freeman.
- [Book reviews on GoodReads.com](https://www.goodreads.com/book/show/58128.Head_First_Design_Patterns)
I use it while learning and as quick reference. It is not intended to be an standalone substitution of the book so if you really want to learn the concepts here presented, buy and read the book and use this repository as a reference and guide.
If you are the publisher and think this repository should not be public, just write me on [http://linkedin.com/in/stepasquini](http://linkedin.com/in/stepasquini) and I will make it private.
Contributions: Issues, comments and pull requests are welcome.
## Concepts
- [Design Patterns](design_patterns.md)
- [Design Principles](design_principles.md)
## Chapters
1. [Welcome to Design Patterns](welcome_to_design_patterns.md);
2. [Keeping your Objects in the know](keeping_your_objects_in_the_know.md);
3. [Decorating Objects](decorating_objects.md);
4. [Baking with OO Goodness](baking_with_oo_goodness.md)
5. [One of a Kind Objects](one_of_a_kind_objects.md)
6. [Encapsulating Invocation](encapsulating_invocation.md)
7. [Being Adaptive](being_adaptive.md)
8. [Encapsulating Algorithms](encapsulating_algorithms.md)
9. [Well-Managed Collections](well_managed_collections.md)
10. [The State of Things](the_state_of_things.md)
11. [Controlling Object Access](controlling_object_access.md)
## Book's samples (my interpretation)
- [Duck Behavior](01_duck_behavior)
- [Weather Monitoring application](02_weather_monitoring_application)
- [Starbuzz Coffee](03_starbuzz_coffee)
- [Java I/O Decorator](04_java_io_decorator)
- [Pizza Store](05_pizza_store)
- [Home automation](06_home_automation)
- [Duck Adapter](07_duck_adapter)
- [Home Theater Facade](08_home_theater_facade)
- [Caffeine Beverage With Hook](09_caffeine_beverage_with_hook)
- [Duck sorting](10_duck_sorting)
- [Iterator Pattern and Composite Pattern](11_iterator_pattern)
- [Gumball Machine](12_gumball_machine)
| 0 |
cloudfoundry-samples/hello-spring-cloud | Spring Cloud Connectors sample application. | null | Hello Spring Cloud Connectors
============
A [Spring Boot application](http://github.com/cloudfoundry-samples/hello-spring-cloud) that uses [Spring Cloud Connectors](https://cloud.spring.io/spring-cloud-connectors/) to connect to cloud services and get information about cloud environment.
## Building the application
Use Maven to build the application:
~~~
$ mvn clean package
~~~
## Running the application on Cloud Foundry
To run the application on Cloud Foundry, first target and long into a Cloud Foundry environment, then run this command:
~~~
$ cf push
~~~
The application will be deployed using settings in the provided `manifest.yml` file. The output from the command will show the URL that has been assigned to the application. Browse to the provided URL to view information about the application.
### Creating and binding services
Using the provided manifest, the application will not be bound to any data services. The application UI will show default connections provided by Spring Boot. You can create relational database, Redis, MongoDB, and AMQP services and bind them to the application to test creation of service connections with Spring Cloud Connectors.
On [Pivotal Web Services](https://run.pivotal.io/) you can create and bind each type of service using these commands:
~~~
$ cf create-service cleardb spark mysql-service
$ cf bind-service hello-spring-cloud mysql-service
$ cf create-service rediscloud 30mb redis-service
$ cf bind-service hello-spring-cloud redis-service
$ cf create-service mlab sandbox mongodb-service
$ cf bind-service hello-spring-cloud mongodb-service
$ cf create-service cloudamqp spark amqp-service
$ cf bind-service hello-spring-cloud amqp-service
$ cf restart
~~~
On [Pivotal Cloud Foundry](https://pivotal.io/platform) you can create and bind each type of service using these commands:
~~~
$ cf create-service p-mysql 100mb mysql-service
$ cf bind-service hello-spring-cloud mysql-service
$ cf create-service p-redis shared-vm redis-service
$ cf bind-service hello-spring-cloud redis-service
$ cf create-service p-rabbitmq standard amqp-service
$ cf bind-service hello-spring-cloud amqp-service
$ cf restart
~~~
Consult the [Pivotal Cloud Foundry documentation](http://docs.pivotal.io/) for more details.
| 1 |
bleeding182/samples | Code samples and tutorials | null | # samples
Code samples and tutorials
| 0 |
treygrainger/solr-in-action | Sample code, data, and configuration for the book | null | null | 1 |
eddumelendez/testcontainers-samples | Testcontainers samples | java testcontainers | null | 0 |
easybest/spring-data-mybatis-samples | This is a demo project based on Spring Data NyBatis. According to this demo project, you can quickly learn the basic usage of Spring Data MyBatis. | null | <p align="center">
<a href="https://github.com/easybest/spring-data-mybatis">
<img src="https://raw.githubusercontent.com/easybest/spring-data-mybatis/main/logo.png"/>
</a>
</p>
----
<p align="center">
<a href="https://github.com/easybest/spring-data-mybatis/actions/workflows/github-actions-ci.yml" title="Build">
<img src="https://github.com/easybest/spring-data-mybatis/actions/workflows/github-actions-ci.yml/badge.svg"/>
</a>
<a href="https://maven-badges.herokuapp.com/maven-central/io.easybest/spring-data-mybatis" title="Maven Central">
<img src="https://maven-badges.herokuapp.com/maven-central/io.easybest/spring-data-mybatis/badge.svg"/>
</a>
<a href="https://github.com/hatunet/spring-data-mybatis/blob/main/LICENSE" title="License: Apache 2.0">
<img src="https://img.shields.io/badge/license-Apache_2.0-brightgreen.svg"/>
</a>
<a href="https://gitter.im/spring-data-mybatis" title="Gitter chat">
<img src="https://badges.gitter.im/gitterHQ/gitter.png"/>
</a>
</p>
This is a demo project based on [Spring Data MyBatis](https://github.com/easybest/spring-data-mybatis).
According to this demo project, you can quickly learn the basic usage of Spring Data MyBatis.
## How to Start
```shell
./mvnw spring-boot:run
``` | 0 |
nashtech-garage/yas | YAS: Yet Another Shop, a sample microservices project in Java | docker ecommerce hacktoberfest java keycloak kubernetes microservices sample-project shop spring-boot | # YAS: Yet Another Shop
YAS is a pet project aim to practice building a typical microservice application in Java
[![storefront-ci](https://github.com/nashtech-garage/yas/actions/workflows/storefront-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/storefront-ci.yaml)
[![storefront-bff-ci](https://github.com/nashtech-garage/yas/actions/workflows/storefront-bff-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/storefront-bff-ci.yaml)
[![backoffice-ci](https://github.com/nashtech-garage/yas/actions/workflows/backoffice-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/backoffice-ci.yaml)
[![backoffice-bff-ci](https://github.com/nashtech-garage/yas/actions/workflows/backoffice-bff-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/backoffice-bff-ci.yaml)
[![product-ci](https://github.com/nashtech-garage/yas/actions/workflows/product-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/product-ci.yaml)
[![media-ci](https://github.com/nashtech-garage/yas/actions/workflows/media-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/media-ci.yaml)
[![cart-ci](https://github.com/nashtech-garage/yas/actions/workflows/cart-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/cart-ci.yaml)
[![customer-ci](https://github.com/nashtech-garage/yas/actions/workflows/customer-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/customer-ci.yaml)
[![rating-ci](https://github.com/nashtech-garage/yas/actions/workflows/rating-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/rating-ci.yaml)
[![location-ci](https://github.com/nashtech-garage/yas/actions/workflows/location-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/location-ci.yaml)
[![order-ci](https://github.com/nashtech-garage/yas/actions/workflows/order-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/order-ci.yaml)
[![inventory-ci](https://github.com/nashtech-garage/yas/actions/workflows/inventory-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/inventory-ci.yaml)
[![tax-ci](https://github.com/nashtech-garage/yas/actions/workflows/tax-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/tax-ci.yaml)
[![search-ci](https://github.com/nashtech-garage/yas/actions/workflows/search-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/search-ci.yaml)
[![promotion-ci](https://github.com/nashtech-garage/yas/actions/workflows/promotion-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/promotion-ci.yaml)
[![payment-ci](https://github.com/nashtech-garage/yas/actions/workflows/payment-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/payment-ci.yaml)
[![payment-paypal-ci](https://github.com/nashtech-garage/yas/actions/workflows/payment-paypal-ci.yaml/badge.svg)](https://github.com/nashtech-garage/yas/actions/workflows/payment-paypal-ci.yaml)
## Tentative technologies and frameworks
- Java 21
- Spring boot 3.2
- Next.js
- Keycloak
- Kafka
- Elasticsearch
- K8s
- GitHub Actions
- SonarCloud
- OpenTelemetry
- Grafana, Loki, Prometheus, Tempo
## Local development architecture
![Yas - local development architecture](https://raw.githubusercontent.com/nashtech-garage/yas/main/yas-architecture-local.png)
## Getting started with Docker Compose
1. Get the latest source code
2. Add the following records to your host file:
```
127.0.0.1 identity
127.0.0.1 api.yas.local
127.0.0.1 pgadmin.yas.local
127.0.0.1 storefront
127.0.0.1 backoffice
127.0.0.1 loki
127.0.0.1 tempo
127.0.0.1 grafana
127.0.0.1 elasticsearch
127.0.0.1 kafka
127.0.0.1 akhq
```
3. Open terminal of your choice, go to `yas` directory, run `docker compose up`, wait for all the containers up and running
> *_Warning:_* To run all the containers, you need a minimum of 16GB of RAM. Otherwise, you can only run the core services with this command `docker compose -f docker-compose.yml up`
4. All the containers up and running then we start source connectors by run script, open any terminal window... go to the YAS root folder and type: ./start-source-connectors.sh
5. Open your browser, now you can access the websites via `http://storefront/`; `http://backoffice/` login with admin/password
#### You might also want to explore:
1. `http://pgadmin.yas.local/`. Account login: `admin@yas.com` / admin. Register a server: postgres, port 5432, username admin, password admin. The Postgresql server is also exposed to the host machine: servername: localhost, port: 5432, username: admin, password: admin
2. `http://api.yas.local/swagger-ui/` for all the REST API document of all the services
3. `http://identity/` for Keycloak console, account admin/admin
4. `http://grafana/` for observability: log, trace, matrix
5. `http://elasticsearch/` for calling Elasticsearch APIs
#### About docker-compose files
1. docker-compose.yml for all core services
2. docker-compose.search.yml for search service
3. docker-compose.o11y.yml for observability services
## Deploy to Kubernetes
https://github.com/nashtech-garage/yas/tree/main/k8s/deploy
## Documentation
https://github.com/nashtech-garage/yas/tree/main/docs
## Contributing
- Give us a star
- Reporting a bug
- Participate discussions
- Propose new features
- Submit pull requests. If you are new to GitHub, consider to [learn how to contribute to a project through forking](https://docs.github.com/en/get-started/quickstart/contributing-to-projects)
- [Developer guidelines](https://github.com/nashtech-garage/yas/wiki/Developer-guidelines)
By contributing, you agree that your contributions will be licensed under MIT License.
| 1 |
bmuschko/docker-for-jvm-projects | The exercises and samples for the training Docker for JVM projects"." | null | # Docker for JVM projects
Want to use Docker with your Java Virtual Machine (JVM) projects but don’t know where to start? You’ve come to the right place.
Join expert Benjamin Muschko to learn how Docker can help you deliver reliable, containerized software as part of your automation process. You’ll containerize, distribute, and test a Java application with Docker and explore the tooling integration for Docker, including IDEs, build tools, and CI, to make you even more productive. You’ll leave with a firm understanding of the role Docker plays in the development lifecycle and prepared to immediately use Docker in your own JVM projects.
## Prerequisites
All exercises are based on a sample Java project. Please make sure to follow the [instructions](./prerequisites/instructions.md) for setting up the sample project before joining the training.
## Exercises
All [exercises](./exercises) are numbered and live in dedicated directories starting with the name `exercise-`. You'll find instructions for each exercise in each folder. Solutions are available in the `solution` folder. Try to solve each exercise yourself before having a look at the solution. | 0 |
ddewaele/spring-cloud-security-samples | null | null | Contains a number of spring Boot Security / SSO samples.
# sample1
A simple authserver / gateway / ui / resource pattern.
- Everything goes through the gateway
- Authentication against an auth server
- Both UIs and Resources are behind gateway.
- Everything secured with Oauth2
- Out of the box config (simple annotations)
![](images/sample1.png)
When accessing the UI directly (temporarily enabling basic authentication to bypass the authserver) I can access the protected resource.
```
Secure object: FilterInvocation: URL: /protected.html; Attributes: [hasRole('ROLE_USER')]
Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@48ba0d1: Principal: org.springframework.security.core.userdetails.User@36ebcb: Username: user; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_ADMIN,ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: F54370F9513AE2EB79619859190CCCC7; Granted Authorities: ROLE_ADMIN, ROLE_USER
Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2a54d2a7, returned: 1
Authorization successful
```
So the antMatchers work fine, and the protected.html can be seen by users with the proper role.
When accessing the UI through the gateway, I get redirected to the authserver (expected) and when passing authentication with a user with ROLE_USER, but I get this in the gateway logs :
```
2016-03-23 14:23:20.245 DEBUG 4194 --- [nio-8888-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /ui/protected.html; Attributes: [authenticated]
2016-03-23 14:23:20.245 DEBUG 4194 --- [nio-8888-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@402417f1: Principal: user; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, sessionId=<SESSION>, tokenType=bearertokenValue=<TOKEN>; Granted Authorities: {authority=ROLE_USER}
2016-03-23 14:23:20.245 DEBUG 4194 --- [nio-8888-exec-3] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@71da2205, returned: 1
2016-03-23 14:23:20.245 DEBUG 4194 --- [nio-8888-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
```
So I am seeing the OAuth2Authentication here, but this is on the gateway level where it sees /ui/protected.html. I don't think the gateway is the place to define fine-grained access control for my UI. (I want to do that in the UI itself)
However, In the UI logs (where I actually defined the authorization rules) I don't see the Oauth2Authentication anymore :
```
Secure object: FilterInvocation: URL: /protected.html; Attributes: [hasRole('ROLE_USER')]
Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@905571d8: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: CCF6C2F33B3794D28F3D45D20E59BAE0; Granted Authorities: ROLE_ANONYMOUS
Voter: org.springframework.security.web.access.expression.WebExpressionVoter@69681cd, returned: -1
AuditEvent [timestamp=Wed Mar 23 14:28:32 CET 2016, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]
Access is denied (user is anonymous); redirecting to authentication entry point
```
So it is not able to access the protected resource.
```
curl -v -H "Cookie:JSESSIONID=728D85124207C56D56A856657046F4AA;" http://localhost:8888/ui/protected.html
* Trying ::1...
* Connected to localhost (::1) port 8888 (#0)
> GET /ui/protected.html HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.43.0
> Accept: */*
> Cookie:JSESSIONID=728D85124207C56D56A856657046F4AA;
>
< HTTP/1.1 403 Forbidden
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< X-Application-Context: bootstrap:8888
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Set-Cookie: JSESSIONID=84C0D6801187087B5690A85F718DD408; Path=/ui/; HttpOnly
< Set-Cookie: XSRF-TOKEN=8ddd2a8b-1ace-4db3-a488-72c25ae64d50; Path=/
< Date: Wed, 23 Mar 2016 13:32:14 GMT
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"timestamp":1458739934740,"status":403,"error":"Forbidden","message":"Access Denied","path":"/ui/protected.html"}
```
It is able to access the oauth2 protected /resource endpoint thorugh the gateway
```
curl -v -H "Cookie:JSESSIONID=728D85124207C56D56A856657046F4AA;" http://localhost:8888/resource
* Trying ::1...
* Connected to localhost (::1) port 8888 (#0)
> GET /resource HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.43.0
> Accept: */*
> Cookie:JSESSIONID=728D85124207C56D56A856657046F4AA;
>
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< X-Application-Context: bootstrap:8888
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Date: Wed, 23 Mar 2016 13:32:08 GMT
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"id":"ec7d167d-53b7-457c-995f-63d13ab7dbd1","content":"Hello World from resource"}
```
Some Questions :
If I want SSO via the GW to all my resources / UIs, I only need to have EnableOAuth2Sso on the gateway ?
My authorization rules can remain in the UIApplication ? These don't need to be moved to the gateway
# References
- https://github.com/spring-projects/spring-boot/issues/5482
- http://presos.dsyer.com/decks/oauth-rest.html
- http://projects.spring.io/spring-security-oauth/docs/oauth2.html
- https://spring.io/guides/tutorials/spring-boot-oauth2/
- https://spring.io/blog/2013/07/11/spring-security-java-config-preview-readability/
- https://raymondhlee.wordpress.com/2014/12/21/implementing-oauth2-with-spring-security/
- https://raymondhlee.wordpress.com/2015/12/05/oauth2-authorization-server-with-spring-security/
- http://cloud.spring.io/spring-cloud-netflix/spring-cloud-netflix.html
- https://github.com/spring-cloud/spring-cloud-security/issues/94
- https://github.com/leon/spring-oauth-social-microservice-starter
- https://github.com/kakawait/uaa-behind-zuul-sample
| 0 |
hantsy/spring-puzzles | Code samples for tips, problem-resolving methods, patterns in Spring development | spring spring-boot | # Spring puzzles
My personal playground to share tips, code samples, techniques, problem-resolving methods, answers of StackOverflow questions or cutting-edge features in the progress of Spring application development.
* [Switching between multi DataSources in Spring](./jdbc-ds-vanilla/GUIDE.md)
* [Using multi DataSources simultaneously in a single Spring Boot application](./multi-ds/GUIDE.md)
* [Configure an Oracle JNDI DataSource in Spring Boot embedded Tomcat](./oracle-jndi-ds-jar/GUIDE.md)
* [Configure an Oracle JNDI DataSource in an external Tomcat](./oracle-jndi-ds-war/GUIDE.md)
| 0 |
gengjiawen/ci-sample | React Native CI Sample | null | ## Build React Native App Using CI
[![CircleCI](https://circleci.com/gh/gengjiawen/ci-sample.svg?style=svg)](https://circleci.com/gh/gengjiawen/ci-sample)
[![pipeline status](https://gitlab.com/gengjiawen/ci-sample/badges/master/pipeline.svg)](https://gitlab.com/gengjiawen/ci-sample/commits/master)
[![Build Status](https://travis-ci.com/react-native-community/ci-sample.svg?branch=master)](https://travis-ci.com/react-native-community/ci-sample)
[![Build Status](https://dev.azure.com/gengjiawen/open-source/_apis/build/status/react-native-ci-sample/react-native-ci-sample?branchName=master)](https://dev.azure.com/gengjiawen/open-source/_build/latest?definitionId=3?branchName=master)
![Github Actions](https://github.com/react-native-community/ci-sample/workflows/Github%20Actions/badge.svg)
[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/rnc-archive/ci-sample)
## Motivation
Showcase for using ci to build react native app.
Docker related repo: https://github.com/react-native-community/docker-android.
# CI Currently includes:
* circleci
* gitlab
* travis-ci
* azure devops
* github actions
| 1 |
DexPatcher/dexpatcher-gradle-samples | Sample projects using the DexPatcher Gradle plugins | null | null | 1 |
SAP/cloud-security-services-integration-library | Integration libraries and samples for authenticating users and clients bound to XSUAA authentication and authorization service or Identity authentication service. | open-source | [![REUSE status](https://api.reuse.software/badge/github.com/SAP/cloud-security-services-integration-library)](https://api.reuse.software/info/github.com/SAP/cloud-security-services-integration-library)
[![Maven Build main](https://github.com/SAP/cloud-security-services-integration-library/actions/workflows/maven-build.yml/badge.svg?branch=main)](https://github.com/SAP/cloud-security-services-integration-library/actions/workflows/maven-build.yml)
[![Fosstars security rating](https://raw.githubusercontent.com/SAP/cloud-security-xsuaa-integration/fosstars-report/fosstars_badge.svg)](https://github.com/SAP/cloud-security-xsuaa-integration/blob/fosstars-report/fosstars_report.md)
[![CodeQL](https://github.com/SAP/cloud-security-xsuaa-integration/workflows/CodeQL/badge.svg)](https://github.com/SAP/cloud-security-xsuaa-integration/actions?query=workflow%3ACodeQL)
# SAP BTP Security Services Integration Libraries
This repository offers a comprehensive set of libraries designed to simplify the integration of [SAP Business Technology Platform](https://www.sap.com/products/technology-platform.html) (SAP BTP) security services (XSUAA and Identity Services).
Tailored to support Jakarta EE and Spring Boot applications running on Cloud Foundry or Kubernetes environments.
The libraries focus on streamlining [OAuth 2.0](https://oauth.net) access token validation for tokens issued by XSUAA and Identity Services. In addition, it offers a token-client library to easily fetch tokens without cumbersome setup for http requests. Finally, it offers testing utility that mocks Xsuaa and Identity service behaviour and makes it easy to write integration and unit tests.
## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Usage](#usage)
- [2.1 Token Validation](#21-token-validation)
- [2.1.1 Jakarta EE web applications](#211-Jakarta-EE-web-applications)
- [2.1.2 Spring Boot applications](#212-spring-boot-web-applications)
- [2.2 Token Flows](#22-token-flows-for-token-retrievals)
- [2.3 Testing utilities](#23-testing-utilities)
3. [Installation](#installation)
4. [Troubleshooting](#troubleshooting)
5. [Common Pitfalls](#common-pitfalls)
6. [Contributing](#contributing)
7. [How to get support](#how-to-get-support)
8. [License](#license)
## Prerequisites
Before you can use the SAP Cloud Security Services Integration libraries, you must fulfil the following requirements:
1. Knowledge of Java programming and (Optional) Spring Boot framework.
2. Access to an SAP BTP account and the XSUAA or Identity service.
3. Familiarity with OAuth 2.0 and JWT (JSON Web Tokens).
4. Java 17
5. Maven 3.9.0 or later
6. (Optional) Spring Boot 3.0.0 or later, Spring Security 6.0.0 or later if using the Spring integration
:exclamation: For Java 8 and 11 please use [2.x release](https://github.com/SAP/cloud-security-services-integration-library/tree/main-2.x) of this library.
## Usage
Typical web applications consist of a gateway server serving HTML content to the user client and one or more servers behind the gateway providing REST APIs. The gateway server acts as OAuth2 client executing an OAuth2 Authorization Code Flow to retrieve an access token when a new user client session is created. Requests from the user client are correlated with a session id on the gateway server which appends the access token to subsequent requests and forwards them to the REST APIs. The session flow looks as follows:
1. A user accesses the web application using a browser or mobile device which begins a new server session.
2. The web application redirects the user client to the OAuth2 server for authentication. In typical SAP Business Technology Platform scenarios, this is handled by an application router. Upon authentication, the web application receives an authorization code from the user client issued by the OAuth2 server.
3. An access token is retrieved from the OAuth2 server in exchange for the authorization code.
4. The web application uses the access token to access resources on an OAuth2 resource server via a REST API. The OAuth2 resource server validates the token using online or offline validation to restrict access to the API.
![OAuth 2.0 Authorization code flow](docs/oauth.png)
OAuth2 resource servers (as the one in step 4) require libraries for validating access tokens.
### 2.1. Token Validation
Key features:
* Automatic OAuth2 service configuration based on SAP BTP service bindings found in the environment
* OAuth2 Token Validation based on these service configurations
* Easy access to principal and token claims within request handlers
* Automatic or sample integrations for common web application frameworks (i.e. Jakarta EE / Spring Security)
#### 2.1.1. Jakarta EE web applications
Developers who need OAuth2 token validation and token access in their Jakarta EE applications can utilize the [java-security](./java-security) library. This library simplifies the process of acquiring token information such as principal and audiences from the security context and takes over token validation for tokens issued by Xsuaa or Identity services.
This library is also integrated in SAP Java Buildpack.
In the table below you'll find links to detailed information.
| Library | Usage Examples |
|-------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [java-security](/java-security) | [java-security-xsuaa-usage](/samples/java-security-usage) demonstrates java-security usage with Xsuaa service <br/> [java-security-identity-usage](/samples/java-security-usage-ias) demonstrates java-security usage with Identity service <br/> [sap-java-builpack-api-usage](/samples/sap-java-buildpack-api-usage) demonstrates java-security usage with SAP Java Buildpack |
:bulb: Changes with SAP Java Buildpack 1.26.0
The former SAP Java Buildpack versions have used deprecated (Spring) Security libraries and had to be updated. As of version 1.26.0 SAP Java Buildpack uses the [`java-security`](/java-security) library. Please consider these (migration) guides:
- [MANDATORY: clean-up deprecated dependencies](https://github.com/SAP/cloud-security-services-integration-library/blob/main/java-security/Migration_SAPJavaBuildpackProjects.md)
- [OPTIONAL: Leverage new APIs and features](https://github.com/SAP/cloud-security-services-integration-library/blob/main/java-security/Migration_SAPJavaBuildpackProjects_V2.md)
#### 2.1.2. Spring Boot web applications
Developers seeking OAuth2 token validation and access to token information for their Spring Boot applications can benefit from the [spring-security](/spring-security) library.
This library streamlines the process of handling token validation for tokens issued by Xsuaa or Identity services and obtaining token details, such as principal and audiences from the security context.
:exclamation: For backward compatibility there is [spring-xsuaa](/spring-xsuaa) library available that supports only Xsuaa service integration, but with the next major release it will be removed.
- If you're already using [spring-xsuaa](/spring-xsuaa) in your project you should plan the time to migrate to the [spring-security](/spring-security), see [migration guide](/spring-xsuaa/Migration_JavaContainerSecurityProjects.md).
- If you're just setting up your project you should use [spring-security](/spring-security) library.
In the table below you'll find links to detailed information.
| Library | Usage Examples |
|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [spring-security](/spring-security) | [spring-security-hybrid-usage](samples/spring-security-hybrid-usage) demonstrates usage of xsuaa and Identity service token validation |
| [spring-xsuaa](/spring-xsuaa) | [spring-security-basic-auth](/samples/spring-security-basic-auth) demonstrates how a user can access Rest API via basic authentication (user/password) <br/> [spring-xsuaa-usage](/samples/spring-security-xsuaa-usage) demonstrates xsuaa only setup |
### 2.2. Token Flows for token retrievals
Java applications that require access tokens (JWT) from Xsuaa or Identity services can utilize the Token Flows API from the [token-client](./token-client) library, to fetch JWT tokens for their clients (applications) or users.
Typical use cases:
* technical user / system tokens for service to service communication
* user token exchange for principal propagation in service to service communication
In the table below you'll find links to detailed information.
| Library | Usage Examples |
|-------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [token-client](/token-client) | [java-tokenclient-usage](samples/java-tokenclient-usage) demonstrates usage of token client library in Jakarta EE application<br/> [spring-security-xsuaa-usage](samples/spring-security-xsuaa-usage) demonstrates usage in Spring Boot application |
### 2.3 Testing utilities
For authentication/authorization flow testing purposes there is [java-security-test](/java-security-test) library at your disposal that can be used for unit and integration tests to test the Xsuaa or Identity service client functionality in the application.
It provides a [JwtGenerator](/java-security-test/src/main/java/com/sap/cloud/security/test/JwtGenerator.java) to generate custom JWT tokens that work together with a pre-configured [WireMock](http://wiremock.org/docs/getting-started/) web server that stubs outgoing calls to the Identity or Xsuaa service, e.g to fetch the JWKS used to check the validity of the token signature.
With this library you can test end to end all your secured endpoints or app logic that is dependant on information from the tokens.
Key features:
* Generates and signs tokens with user provided attributes
* Provides a pre-configured local authorization server that mocks communication with the BTP security services to validate self-generated tokens
* For Jakarta EE application sets up a local application server that is pre-configured with a security filter matching self-generated tokens. It can be configured to serve the servlets you want to test with mocked authorization
In the table below you'll find links to detailed information.
| Library | Usage Examples |
|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [java-security-test](/java-security-test) | [Integration test code snippet](/samples/spring-security-hybrid-usage/src/test/java/sample/spring/security/junitjupiter/TestControllerIasTest.java) for Spring application <br/>[Integration test code snippet](/samples/java-security-usage/src/test/java/com/sap/cloud/security/samples/HelloJavaServletIntegrationTest.java) for Jakarta EE web.xml based servlets <br/> [Integration test code snippet](/samples/java-security-usage-ias/src/test/java/com/sap/cloud/security/samples/ias/HelloJavaServletIntegrationTest.java) for Jakarta EE annotation based servlets <br/> |
## Installation
The SAP Cloud Security Services Integration is published to maven central: https://search.maven.org/search?q=com.sap.cloud.security and is available as a Maven dependency. Add the following BOM to your dependency management in your `pom.xml`:
```xml
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.sap.cloud.security</groupId>
<artifactId>java-bom</artifactId>
<version>3.4.0</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
```
along with libraries that you intend to use e.g. `java-security`
```xml
<dependencies>
<dependency>
<groupId>com.sap.cloud.security</groupId>
<artifactId>java-security</artifactId>
</dependency>
</dependencies>
```
:bulb: Please refer to the Maven Dependencies section in the README.md of the library you intend to use for detailed information on which dependencies need to be added to the `pom.xml`.
If you intend to extend this library you can clone this repository and install this project with `mvn` as follows:
```sh
git clone https://github.com/SAP/cloud-security-services-integration-library
cd cloud-security-services-integration-library
mvn clean install
```
## Troubleshooting
Please refer to each library's Troubleshooting section
| Link to troubleshooting section |
|---------------------------------------------------------------|
| [spring-security](/spring-security/README.md#Troubleshooting) |
| [spring-xsuaa](/spring-xsuaa/README.md#Troubleshooting) |
| [java-security](/java-security/README.md#Troubleshooting) |
| [token-client](/token-client/README.md#Troubleshooting) |
## Common Pitfalls
### java.lang.NoSuchMethodError and java.lang.ClassNotFoundException errors
Most common reason for these errors are out of sync client library versions. All the modules of the Security Client libraries
should be always in the same version.
This can be verified by executing `mvn dependency:tree` command.
The easiest way to manage the module versions and keep them in sync is to use the [BOM](https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#bill-of-materials-bom-poms)
The usage of the Security Client Libraries BOM is demonstrated also in the [spring-security-hybrid-usage sample](https://github.com/SAP/cloud-security-services-integration-library/blob/main/samples/spring-security-hybrid-usage/pom.xml#L35-L45)
### reference-instance plan not supported
The `reference-instance` plan is not an original plan of the Xsuaa service, therefore it is not supported by the Security Client Libraries out of the box.
For a workaround please refer to the https://github.com/SAP/cloud-security-services-integration-library/issues/1279#issuecomment-1735542987
## Contributing
We welcome contributions to this project. Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more details on how to contribute.
## How to get support
**Support is no longer provided via the Issues feature in this Github repository.**
Please use SAP official support channels to get support under component `BC-CP-CF-SEC-LIB` or `Security Client Libraries`.
Before opening support tickets, please check the [Troubleshooting](#troubleshooting) and [Common Pitfalls](#common-pitfalls) sections first in addition to the READMEs of the modules that you are using from this repository.
Make sure to include the following mandatory information to get a response:
- List of module(s) of this library used by your application (java-security, spring-security, spring-xsuaa etc...) and version of this library installed in your application.\
*Alternative*: maven dependency tree
- Auth service set-up of your application (XSUAA, IAS, XSUAA+IAS, IAS+AMS, etc.)
- For exceptions: Stack trace that includes the executed code locations of this library that lead to the exception
- For unexpected 401 / 403 response codes: relevant log output of this library with active DEBUG flag (see module READMEs for a guide how to enable it)
- Steps you have tried to fix the problem
- Reason why you believe a bug in this library is causing your problem
Unfortunately, we can *NOT* offer consulting via support channels.
## License
Please see our [LICENSE](LICENSES/Apache-2.0.txt) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available in the [REUSE tool](https://api.reuse.software/info/github.com/SAP/cloud-security-xsuaa-integration).
| 0 |
scottfrederick/spring-music | A sample application for using database services on Cloud Foundry with Spring Framework. | null | Spring Music
============
This is a sample application for using database services on [Cloud Foundry](http://cloudfoundry.org) with the [Spring Framework](http://spring.io) and [Spring Boot](http://projects.spring.io/spring-boot/).
This application has been built to store the same domain objects in one of a variety of different persistence technologies - relational, document, and key-value stores. This is not meant to represent a realistic use case for these technologies, since you would typically choose the one most applicable to the type of data you need to store, but it is useful for testing and experimenting with different types of services on Cloud Foundry.
The application use Spring Java configuration and [bean profiles](http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html) to configure the application and the connection objects needed to use the persistence stores. It also uses the [Spring Cloud Connectors](http://cloud.spring.io/spring-cloud-connectors/) library to inspect the environment when running on Cloud Foundry. See the [Cloud Foundry documentation](http://docs.cloudfoundry.org/buildpacks/java/spring-service-bindings.html) for details on configuring a Spring application for Cloud Foundry.
## Building
This project requires Java 8 or later to compile.
To build a runnable Spring Boot jar file, run the following command:
~~~
$ ./gradlew clean assemble
~~~
## Running the application locally
One Spring bean profile should be activated to choose the database provider that the application should use. The profile is selected by setting the system property `spring.profiles.active` when starting the app.
The application can be started locally using the following command:
~~~
$ java -jar -Dspring.profiles.active=<profile> build/libs/spring-music.jar
~~~
where `<profile>` is one of the following values:
* `mysql`
* `postgres`
* `mongodb`
* `redis`
If no profile is provided, an in-memory relational database will be used. If any other profile is provided, the appropriate database server must be started separately. Spring Boot will auto-configure a connection to the database using it's auto-configuration defaults. The connection parameters can be configured by setting the appropriate [Spring Boot properties](http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html).
If more than one of these profiles is provided, the application will throw an exception and fail to start.
## Running the application on Cloud Foundry
When running on Cloud Foundry, the application will detect the type of database service bound to the application (if any). If a service of one of the supported types (MySQL, Postgres, Oracle, MongoDB, or Redis) is bound to the app, the appropriate Spring profile will be configured to use the database service. The connection strings and credentials needed to use the service will be extracted from the Cloud Foundry environment.
If no bound services are found containing any of these values in the name, an in-memory relational database will be used.
If more than one service containing any of these values is bound to the application, the application will throw an exception and fail to start.
After installing the 'cf' [command-line interface for Cloud Foundry](http://docs.cloudfoundry.org/cf-cli/), targeting a Cloud Foundry instance, and logging in, the application can be built and pushed using these commands:
~~~
$ cf push
~~~
The application will be pushed using settings in the provided `manifest.yml` file. The output from the command will show the URL that has been assigned to the application.
### Creating and binding services
Using the provided manifest, the application will be created without an external database (in the `in-memory` profile). You can create and bind database services to the application using the information below.
#### System-managed services
Depending on the Cloud Foundry service provider, persistence services might be offered and managed by the platform. These steps can be used to create and bind a service that is managed by the platform:
~~~
# view the services available
$ cf marketplace
# create a service instance
$ cf create-service <service> <service plan> <service name>
# bind the service instance to the application
$ cf bind-service <app name> <service name>
# restart the application so the new service is detected
$ cf restart
~~~
#### User-provided services
Cloud Foundry also allows service connection information and credentials to be provided by a user. In order for the application to detect and connect to a user-provided service, a single `uri` field should be given in the credentials using the form `<dbtype>://<username>:<password>@<hostname>:<port>/<databasename>`.
These steps use examples for username, password, host name, and database name that should be replaced with real values.
~~~
# create a user-provided Oracle database service instance
$ cf create-user-provided-service oracle-db -p '{"uri":"oracle://root:secret@dbserver.example.com:1521/mydatabase"}'
# create a user-provided MySQL database service instance
$ cf create-user-provided-service mysql-db -p '{"uri":"mysql://root:secret@dbserver.example.com:3306/mydatabase"}'
# bind a service instance to the application
$ cf bind-service <app name> <service name>
# restart the application so the new service is detected
$ cf restart
~~~
#### Changing bound services
To test the application with different services, you can simply stop the app, unbind a service, bind a different database service, and start the app:
~~~
$ cf unbind-service <app name> <service name>
$ cf bind-service <app name> <service name>
$ cf restart
~~~
#### Database drivers
Database drivers for MySQL, Postgres, Microsoft SQL Server, MongoDB, and Redis are included in the project.
To connect to an Oracle database, you will need to download the appropriate driver (e.g. from http://www.oracle.com/technetwork/database/features/jdbc/index-091264.html). Then make a `libs` directory in the `spring-music` project, and move the driver, `ojdbc7.jar` or `ojdbc8.jar`, into the `libs` directory.
In `build.gradle`, uncomment the line `compile files('libs/ojdbc8.jar')` or `compile files('libs/ojdbc7.jar')` and run `./gradle assemble`
| 1 |
cloudgrey-io/appiumpro | Sample code to accompany the appiumpro.com newsletter | null | # appiumpro
Sample code to accompany the appiumpro.com newsletter
| 1 |
ThomasVitale/spring-boot-multitenancy | Samples showing how to build multitenant applications with Java and Spring Boot | java keycloak micrometer multitenancy spring-boot testcontainers | # Spring Boot Multitenancy
## Stack
* Java 21
* Spring Boot 3.2
* Grafana OSS
## Usage
You can use Docker Compose to run the necessary backing services for observability, authentication, and AI.
From the project root folder, run Docker Compose.
```bash
docker-compose up -d
```
The Instrument Service application can be run as follows to rely on Testcontainers to spin up a PostgreSQL database:
```bash
./gradlew bootTestRun
```
The Edge Service application can be run as follows:
```bash
./gradlew bootRun
```
The Chat Service application can be run using one of the two techniques described above. If you don't want to rely on Testcontainers,
make sure you have [Ollama](https://ollama.ai/) installed and the Llama2 model available (`ollama run llama2`).
Two tenants are configured: `dukes` and `beans`. Ensure you add the following configuration to your `hosts` file to resolve tenants from DNS names.
```bash
127.0.0.1 dukes.rock
127.0.0.1 beans.rock
```
Now open the browser window and navigate to `http://dukes.rock/instruments/`. You'll be redirected to the Keycloak authentication page. Log in with `isabelle/password`. The result will be the list of instruments from the Dukes rock band.
Now open another browser window and navigate to `http://beans.rock/instruments/`. You'll be redirected to the Keycloak authentication page. Log in with `bjorn/password`. The result will be the list of instruments from the Beans rock band.
| 0 |
Marketo/REST-Sample-Code | Marketo REST API sample code. | null | # Marketo REST API Sample Code
This repository contains language-specific directories with samples. The samples simply show how to invoke various REST API endpoints.
# Documentation
Reference documentation can be found on the [Marketo Developers website](http://developers.marketo.com/rest-api/).
# Contributing
We encourage members of the community to contribute bug fixes and new samples. To contribute simply fork the repository, make your changes, and submit a pull request.
Additional questions or comments? Please contact [developerfeedback@marketo.com](mailto:developerfeedback@marketo.com?subject=REST-Sample-Code).
# Samples by Category
## Asset
|Category | Language|
|----------|---------|
|Channels | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Channels) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Channels) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Channels) / Ruby|
|Email Templates | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/EmailTemplates) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/EmailTemplates) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/EmailTemplates) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/EmailTemplates)|
|Emails | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Emails) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Emails) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Emails) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/Emails)|
|Files | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Files) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Files) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Files) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/Files)|
|Folders | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Folders) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Folders) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Folders) / Ruby|
|Landing Page Templates | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/LandingPageTemplates) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/LandingPageTemplates) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/LandingPageTemplates) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/LandingPageTemplates)|
|Programs | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Programs) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Programs) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Programs) / Ruby|
|Snippets | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Snippets) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Snippets) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Snippets) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/Snippets)|
|Tags | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Tags) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Tags) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Tags) / Ruby|
|Tokens | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Asset/Tokens) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Asset/Tokens) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/Asset/Tokens) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Asset/Tokens)|
## Authentication
|Category | Language|
|----------|---------|
|Identity | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/Authentication/Identity) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/Authentication/Identity) / PHP / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/Authentication/Identity)|
## Lead Database
|Category | Language|
|----------|---------|
|Activities | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Activities) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Activities) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Activities) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Activities)|
|Campaigns | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Campaigns) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Campaigns) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Campaigns) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Campaigns)|
|Companies | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Companies) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Companies) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Companies) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Companies)|
|Custom Objects | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/CustomObjects) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/CustomObjects) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/CustomObjects) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/CustomObjects)|
|Leads | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Leads) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Leads) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Leads) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Leads) / [Python](https://github.com/Marketo/REST-Sample-Code/tree/master/python/LeadDatabase/Leads) |
|Opportunities | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Opportunities) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Opportunities) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Opportunities) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Opportunities)|
|Sales Persons | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/SalesPersons) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/SalesPersons) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/SalesPersons) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/SalesPersons)|
|Static Lists | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/StaticLists) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/StaticLists) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/StaticLists) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/StaticLists)|
|Usage | [C#](https://github.com/Marketo/REST-Sample-Code/tree/master/c%23/LeadDatabase/Usage) / [Java](https://github.com/Marketo/REST-Sample-Code/tree/master/java/LeadDatabase/Usage) / [PHP](https://github.com/Marketo/REST-Sample-Code/tree/master/php/LeadDatabase/Usage) / [Ruby](https://github.com/Marketo/REST-Sample-Code/tree/master/ruby/LeadDatabase/Usage)|
| 1 |
cafebazaar/TrivialDrive | In-app Purchase Sample | null | null | 1 |
michaelisvy/proxy-samples | null | null | null | 0 |
tarek360/BottomNavigation-RichPath-Sample | BottomNavigation RichPath Sample | animation bottom-navigation bottomnavigation-demo bottomnavigationview path richpath svg vector vectordrawable | # Bottom navigation sample, made by [RichPath](https://github.com/tarek360/RichPath)
<img src="/gifs/demo.gif">
| 1 |
acmeair/acmeair | A Java implementation of the Acme Air Sample Application. | null | # Acme Air Sample and Benchmark
This application shows an implementation of a fictitious airline called "Acme Air". The application was built with the some key business requirements: the ability to scale to billions of web API calls per day, the need to develop and deploy the application in public clouds (as opposed to dedicated pre-allocated infrastructure), and the need to support multiple channels for user interaction (with mobile enablement first and browser/Web 2.0 second).
There are two implementations of the application tier. Each application implementation, supports multiple data tiers. They are:
- **Node.js**
- MongoDB
- Cloudant
- **Java**
- WebSphere Liberty Profile to WebSphere eXtreme Scale
- WebSphere Liberty Profile to Mongodb
## Repository Contents
Source:
- **acmeair-common**: The Java entities used throughout the application
- **acmeair-loader**: A tool to load the Java implementation data store
- **acmeair-services**: The Java data services interface definitions
- **acmeair-service-wxs**: A WebSphere eXtreme Scale data service implementation
- **acmeair-service-morphia**: A mongodb data service implementation
- **acmeair-webapp**: The Web 2.0 application and associated Java REST services
## How to get started
* Instructions for [setting up and building the codebase](Documentation/Build_Instructions.md)
* Deploying the sample application to [Websphere Liberty](Documentation/Liberty_Instructions.md)
* Websphere Liberty Profile to [MongoDB Instructions](https://github.com/acmeair/acmeair/blob/master/MONGO_README.md)
* Deploying to [IBM Bluemix](Documentation/Bluemix_Instructions.md)
* Acme Air for Node.js [Instructions](https://github.com/acmeair/acmeair-nodejs/blob/master/README.md)
* Extending Acme Air by [adding additional data services.](Documentation/Extending_AcmeAir_Services.md)
## Ask Questions
Questions about the Acme Air Open Source Project can be directed to our Google Groups.
* Acme Air Users: [https://groups.google.com/forum/?fromgroups#!forum/acmeair-users](https://groups.google.com/forum/?fromgroups#!forum/acmeair-users)
## Submit a bug report
We use github issues to report and handle bug reports.
## OSS Contributions
We accept contributions via pull requests.
CLA agreements needed for us to accept pull requests soon can be found in the [CLAs directory](CLAs) of the repository.
| 1 |
Snapchat/login-kit-sample | Sample App For Login Kit | null | # Login Kit Sample Apps
- [Sample iOS App](ios)
- [Sample Android App](android)
- [Sample React Native](react-native)
| 1 |
haibuzou/MVPSample | MVP Sample | null | # MVPSample
一点点MVP的个人心得
博客介绍: http://blog.csdn.net/dantestones/article/details/50899235
## MVC VS MVP
同样的功能使用MVC和MVP2种实现方式,比较才能更好的理解
![](http://img.blog.csdn.net/20160317163144720)
## MVC架构
- M : 业务层和模型层,相当与javabean和我们的业务请求代码
- V : 视图层,对应Android的layout.xml布局文件
- C : 控制层,对应于Activity中对于UI 的各种操作
## MVP架构
- M : 还是业务层和模型层
- V : 视图层的责任由Activity来担当
- P : 新成员Presenter 用来代理 C(control) 控制层
## MVP通用类
新增了MVP通用类,更少的代码,更好使用
* BaseView
* BasePresenter
* BaseMvpActivity
| 1 |
morevaadin/More-Vaadin | Sample projects of articles on morevaadin.com | null | # More Vaadin code
This repository hosts the code for http://morevaadin.com.
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/nfrankel/more-vaadin/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
| 1 |
refactown/cleancode | Clean Code Samples | null | # Curso de Clean Code (Udemy)
Este projeto é parte integrante do curso sobre "Clean Code" disponibilizado na Udemy.
Para maiores informações clique no link abaixo:
[https://www.udemy.com/course/clean-code-na-pratica/?referralCode=24F598EE94626485768C](https://www.udemy.com/course/clean-code-na-pratica/?referralCode=24F598EE94626485768C)
| 0 |
gradle/exemplar | Discover and verify code samples and services | documentation gradle-bt gradle-bt-build-infrastructure samples testing | null | 0 |
ta893115871/VideoEdit | A sample for video edit ui | null | # 高仿微信视频编辑页
android视频编辑页面-高仿微信视频编辑页
# 效果图
<img src="/pic1.png" width=360 height=640/>
<img src="/pic2.png" width=360 height=640/>
# 介绍
http://blog.csdn.net/ta893115871/article/details/70188162
http://www.jianshu.com/p/55dcb62ca0b3
| 1 |
sbrannen/spring-events | Spring Events Sample Application | null | ## Spring Events
_Spring Events_ is a sample application that demonstrates how to implement and test a modern Spring-powered web application.
The following highlight the technologies used and features of the application.
* Java 11
* Spring Framework 5.2.0
* Spring Boot 2.2.0
* Spring Security 5.2.0
* JUnit 5.5.2
* TestNG 7.0.0
* Simple POJO `Event` domain entity using JPA, Bean Validation, and Spring formatting annotations
* Transactional service layer
* Spring Data JPA repository layer
* Spring @MVC + Thymeleaf & REST presentation layer
## Running the Application
To see the application in action, simply execute `gradlew bootRun` and then go to [localhost:8080](http://localhost:8080/).
To create a new event, click on the `New` link on the right-hand side and enter `admin` and `test` for the username and password.
| 1 |
pivotal-cf/identity-sample-apps | Pivotal Single Sign-On Service Sample Applications | null | # Pivotal Single Sign-On Service Sample Applications
This repo holds separate sample applications for each one of the four OAuth 2.0 grant types supported by the Pivotal Single Sign-On Service. The grant type specific environment variables are configured to their relevant values in the manifests of sample application. Each grant type maps to an Application Type as seen in the Pivotal Single Sign-On Service Dashboard. For more information about how to determine SSO Application Type, please read [PCF SSO Documentation](https://docs.pivotal.io/p-identity/determine-type.html).
Application Type | Grant Type | Pivotal SSO Version | Spring Cloud SSO Starter library version
------------- | -------------- | --------------------- | ---------------------
[Web App](/authcode) | authorization_code | any | 1.1.2.RELEASE
[Service-to-Service App](/client-credentials) | client_credentials | any | 1.1.2.RELEASE
[Web & Service-to-Service App](/authcode-client-credentials) | authorization_code, client_credentials | v1.10+ | 1.1.2.RELEASE
[Resource Server App](/resource-server) | n/a | any | n/a
The latest version of this repository supports the following dependencies:
Dependency | Version
------------- | ----------
[Spring Boot](https://github.com/spring-projects/spring-boot/tree/2.3.x) | 2.3.4+
[Spring Security](https://github.com/spring-projects/spring-security/tree/5.3.x) | 5.3.4+
[Spring Cloud SSO Starter library](https://github.com/pivotal-cf/java-cfenv/tree/master/java-cfenv-boot-pivotal-sso) | 1.1.2.RELEASE
The sample apps using Spring Boot 1.5 and Spring Security 2 is located on the [spring-boot-1.5 branch](https://github.com/pivotal-cf/identity-sample-apps/tree/spring-boot-1.5).
The sample apps using Spring Boot 2.1 and Spring Security 5.1 is located on the [spring-boot-2.1 branch](https://github.com/pivotal-cf/identity-sample-apps/tree/spring-boot-2.1).
The sample applications for the corresponding grant types are located in subdirectories of this project:
## Prerequisites
1. Login as a Space Developer into the required Org and Space on your PCF Foundation
cf login -a api.<your-domain>
1. Ensure that an SSO (p-identity) [Service Plan](https://docs.pivotal.io/p-identity/manage-service-plans.html) exists for your Org. Record the name of the plan you wish to select to be used as the `<plan_tier>` value for the next step.
cf marketplace | grep p-identity
1. Create a [Service Instance](https://docs.pivotal.io/p-identity/manage-service-instances.html) named 'p-identity-instance' from the 'p-identity' service using an available Service Plan
cf create-service p-identity <plan_tier> p-identity-instance
## <a name="quick-start">Quick Start</a>
You can deploy the authcode and resource server sample applications using application bootstrapping with the steps below. You can read more about these topics in the following sections.
### Deploying Resource Server Sample App
1. Navigate to the *resource-server* directory
1. Update the `SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_ISSUERURI` <PLAN_AUTH_DOMAIN> and <YOUR_DOMAIN> placeholders in the *resource-service* manifest.
1. Build (`./gradlew build`) and push (`cf push`) the *resource-server* application. (You may have to use `--random-route` flag when cf pushing your application if a route already exists with your application name.)
### Deploying Authorization Code Sample App
1. Navigate to the *authcode* directory
1. Update the `RESOURCE_URL` value in the *authcode* manifest.yml file to the route of the deployed *resource-server* (which you can find by running `cf apps`).
1. Build (`./gradlew build`) and push (`cf push`) the *authcode* project. (You may have to use `--random-route` flag when cf pushing your application if a route already exists with your application name.) The sample application will be immediately bound to the SSO Service after `cf push`.
### Deploying Client Credentials Sample App
1. Navigate to the *client-credentials* directory
1. Update the `RESOURCE_URL` value in the *client-credentials* manifest.yml file to the route of the deployed *resource-server* (which you can find by running `cf apps`).
1. Build (`./gradlew build`) and push (`cf push`) the *client-credentials* project. (You may have to use `--random-route` flag when cf pushing your application if a route already exists with your application name.) The sample application will be immediately bound to the SSO Service after `cf push`.
### Deploying Authorization Code & Client Credentials Sample App
1. Navigate to the *authcode-client-credentials* directory
1. Update the `RESOURCE_URL` value in the *authcode-client-credentials* manifest.yml file to the route of the deployed *resource-server* (which you can find by running `cf apps`).
1. Build (`./gradlew build`) and push (`cf push`) the *authcode-client-credentials* project. (You may have to use `--random-route` flag when cf pushing your application if a route already exists with your application name.) The sample application will be immediately bound to the SSO Service after `cf push`.
## Testing the Sample Apps
1. Preparing a test user with sufficient scopes
Contact your cloud administrator to determine whether your Service Plan is has configured the "Internal User Store" as an Identity Provider or an external Identity Provider (like LDAP).
- If your SSO Service plans is configured with the 'Internal User Store' option, you can use the instruction in [Manage Users in an Internal User Store](https://docs.pivotal.io/p-identity/manage-users.html) documentation to create a user to `todo.read` and `todo.write` scopes.
- If your plan is configured with an alternative Identity Provider (like LDAP), your administrator will need to provide you credentials with memberships to the `todo.read` and `todo.write` scopes.
1. Visit the deployed sample apps by entering the urls of the apps (which you can find by running `cf apps`). (The Resource Server sample app is a backend API and not intended to be accessed through a browser.)
# Unsupported Grant Types
### Implicit Grant Type:
The Implicit Grant Type is supported by Spring Security 5, but has generally fallen out of favor as an architectural pattern for SPAs. It has been determined that we will not provide Sample Apps to demonstrate this grant type moving forward. The current recommendation for SPAs is to use the Authorization Code Flow in conjuntion with the [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636) to protect the Authorization Code in the client's browser. For more information, please see the Okta developers blog article: [Is The OAuth Implict Flow Dead](https://developer.okta.com/blog/2019/05/01/is-the-oauth-implicit-flow-dead#the-oauth-authorization-code-flow-is-better).
### Resource Owner Password Credentials (i.e. Password) Type:
The Resource Owner Password Credentials grant type is no longer supported by Spring Security 5 (see the Grant Type [Support Matrix](projects/spring-security/wiki/OAuth-2.0-Features-Matrix#client-support)). The Password grant type is more commonly used with programs, like CLIs, that are unlikley to be dependendant on Spring or other Web based software libraries. For more information, see the [OAuth 2 Password Grant specification](https://tools.ietf.org/html/rfc6749#section-4.3.2).
If your use cases require the Password grant type for a Spring application, you will need to implement the access token request on your own. However, if your Java based CF application is bound to an SSO service instance and using the [Spring Boot SSO Starter Library](https://github.com/pivotal-cf/java-cfenv/tree/master/java-cfenv-boot-pivotal-sso), you may find it useful to reference the table of [Spring Security 5 Java properties](https://github.com/pivotal-cf/java-cfenv/tree/master/java-cfenv-boot-pivotal-sso#spring-applications) built from VCAP_SERVICES to help craft your request.
# Bootstrap Application Client Configurations for the Pivotal Single Sign-On Service Instance
Beginning in SSO 1.4.0, you can set environment variables in your application's manifest to bootstrap client configurations for your applications automatically when binding or rebinding your application to the service instance. These values will be automatically populated to the client configurations for your application through CF environment variables.
**NOTE:** These configurations are only applied at the initial service binding time. Subsequent `cf push` of the application will **NOT** update the configurations. You will either need to manually update the configurations via the SSO dashboard or unbind and rebind the service instance.
When you specify your own scopes and authorities, consider including openid for scopes on auth code, implicit, and password grant type applications, and uaa.resource for client credentials grant type applications, as these will not be provided if they are not specified.
The table in [SSO Documentation - Configure SSO Properties with Environment Variables](https://docs.pivotal.io/p-identity/configure-apps/index.html#configure) provides a description and the default values. Further details and examples are provided in the sample application manifests.
To remove any variables set through bootstrapping, you must use `cf unset-env <APP_NAME> <PROPERTY_NAME>` and rebind the application.
---
#### Running in Unsafe Environment with Self-signed Certificates
⚠️⚠️⚠️ **WARNING** ⚠️⚠️⚠️ Do not use the following steps in your production environments; instead, use trusted certificates within your environment.
If necessary to push the sample apps to an unsafe environment with self-signed certificates, you can add the [cloudfoundry-certificate-truster](https://github.com/pivotal-cf/cloudfoundry-certificate-truster) dependency to the gradle file. Follow the instructions from the cloudfoundry-certificate-truster readme.
| 1 |
jkazama/sample-boot-jpa | Spring Boot + JPA [ DDD Sample ] | ddd devcontainer gradle java jpa spring-boot spring-security | sample-boot-jpa
---
### Preface
It is DDD sample implementation from [Spring Boot](https://spring.io/projects/spring-boot) / [Spring Security](https://spring.io/projects/spring-security) / [Spring Data JPA](https://spring.io/projects/spring-data-jpa).
It is not a framework, please use it as a base template when you start a project using Spring Boot.
#### Concept of Layering
It is three levels of famous models, but considers the infrastructure layer as cross-sectional interpretation.
| Layer | |
| -------------- | ----------------------------------------------------------- |
| UI | Receive use case request |
| Application | Use case processing (including the outside resource access) |
| Domain | Pure domain logic (not depend on the outside resource) |
| Infrastructure | DI container and ORM, various libraries |
Usually perform public handling of UI layer using Thymeleaf, but this sample assume use of different types of clients and perform only API offer in RESTfulAPI.
#### Use policy of Spring Boot
Spring Boot is available for various usage, but uses it in the following policy with this sample.
- Components that require extended definitions are registered with @Bean. register other component in @Component.
- `ApplicationConfig` / `ApplicationDbConfig` / `ApplicationSecurityConfig`
- The exception handling defines it in a endpoint (`RestErrorAdvice`). The whitelabel function disabled it.
- Specialized in Hibernate as JPA implementation.
- The certification method of Spring Security is HttpSession not the basic certification.
- Easily prepare for the basic utility that Spring does not support.
#### Use policy of Java coding
- Java17 over
- The concept / notation added in Java17 is used positively.
- Use Lombok positively and remove diffuseness.
- The name as possible briefly.
- Do not abuse the interface.
- DTO becoming a part of the domain defines it in an internal class.
#### Resource
Refer to the following for the package / resource constitution.
```
main
java
sample
context … Infrastructure Layer
controller … UI Layer
model … Domain Layer
usecase … Application Layer
util … Utilities
- Application.java … Bootstrap
resources
- application.yml … Spring Boot Configuration
- ehcache.xml … Spring Cache Configuration
- logback-spring.xml … Logging Configuration
- messages-validation.properties … Validation Message Resources
- messages.properties … Label Message Resources
```
## Use Case
Consider the following as a sample use case.
- A customer with an account balance requests withdrawal. (Event T, Delivery T + 3)
- The system closes the withdrawal request. (Allows cancellation of request until closing)
- The system sets the business day to the forward day.
- The system reflects the cash flow on delivery date to the account balance.
### Getting Started
This sample uses [Gradle](https://gradle.org/), you can check the operation without trouble with IDE and a console.
#### Server Start (VSCode DevContainer)
It is necessary to do the following step.
- Check Instablled Docker.
- Check Instablled VSCode with DevContainer Extension.
Do the preparations for this sample in the next step.
1. You move to the cloned *sample-boot-jpa* directory.
1. Run command `code .`.
1. Choose *Open Container*
Do the server start in the next step.
1. Open VSCode "Run And Debug".
1. Choose `Run sample-boot-jpa`.
1. If console show "Started Application", start is completed in port 8080.
1. Run command `curl http://localhost:8080/actuator/health`
#### Server Start (Console)
Run application from a console of Windows / Mac in Gradle.
It is necessary to do the following step.
- Check Instablled JDK17+.
- Prepare PostgreSQL and change JDBC connection destination in application.yml.
- DDL/DML are placed under `data/db`.
Do the server start in the next step.
1. You move to the cloned *sample-boot-jpa* directory.
1. Run command `gradlew bootRun`.
1. If console show "Started Application", start is completed in port 8080
1. Run command `curl http://localhost:8080/actuator/health`
### Check Use Case
After launching the server on port 8080, you can test execution of RESTful API by accessing the following URL from console.
#### Customer Use Case
- `curl -X POST -c cookie.txt -d 'loginId=sample&password=sample' http://localhost:8080/api/login`
- `curl -X POST -b cookie.txt -H "Content-Type: application/json" -d '{"accountId" : "sample" , "currency" : "USD", "absAmount": 1000}' http://localhost:8080/api/asset/cio/withdraw`
- Request for withdrawal.
- `curl -b cookie.txt 'http://localhost:8080/api/asset/cio/unprocessedOut'`
- Search for outstanding withdrawal requests
#### Internal Use Case
- `curl -X POST -c cookie.txt -d 'loginId=ADMINISTRATOR-admin&password=admin' http://localhost:8080/api/login`
- `curl -b cookie.txt 'http://localhost:8080/api/admin/asset/cio?updFromDay=yyyy-MM-dd&updToDay=yyyy-MM-dd'`
- Search for deposit and withdrawal requests.
- Please set real date for upd\*Day
#### Batch Use Case
- `curl -X POST -c cookie.txt -d 'loginId=ADMINISTRATOR-admin&password=admin' http://localhost:8080/api/login`
- `curl -b cookie.txt -X POST http://localhost:8080/api/system/job/daily/closingCashOut`
- Close the withdrawal request.
- `curl -b cookie.txt -X POST http://localhost:8080/api/system/job/daily/forwardDay`
- Set the business day to the next day.
- `curl -b cookie.txt -X POST http://localhost:8080/api/system/job/daily/realizeCashflow`
- Realize cash flow. (Reflected to the balance on the delivery date)
> Please execute according to the business day appropriately.
> When executing from a job agent, change the port or block the path with L/B, etc. Here is an example based on the assumption that the administrator executes from the UI
### License
The license of this sample includes a code and is all *MIT License*.
Use it as a base implementation at the time of the project start using Spring Boot.
| 1 |
rcandidosilva/rest-oauth2-sample | rest-oauth2-sample | null | rest-oauth2-sample
==================
### Presentation Slides
http://www.slideshare.net/rcandidosilva/javaone-2014-securing-restful-resources-with-oauth2
| 0 |
SolaceSamples/solace-samples-cloudfoundry-java | Samples showing how to connect and exchange messages with Solace Messaging for Pivotal Cloud Foundry. | cloud-foundry solace solace-messaging solace-samples spring-boot spring-cloud-connectors | [![Build Status](https://travis-ci.org/SolaceSamples/solace-samples-cloudfoundry-java.svg?branch=master)](https://travis-ci.org/SolaceSamples/solace-samples-cloudfoundry-java)
# Getting Started Examples
## Solace Cloud Foundry Java
The repository contains example applications that use the Solace Pubsub+ service on Pivotal Cloud Foundry. The goal of these sample applications is to illustrate various ways of consuming the `VCAP_SERVICES` environment variable from a Solace Pubsub+ Cloud Foundry service instance. You can get more details on the Solace Pubsub+ Service for Pivotal Cloud Foundry [here](http://docs.pivotal.io/solace-messaging/).
This repository contains a sample application modified in the following ways:
* Simple Java Application
* Using Spring Cloud Connectors
* Connecting using Transport Level Security
While not necessary for a Java Application or a straight Spring Cloud Connector applications, the samples in this repository still make use of of Spring Boot so they can easily expose a simple REST interface to provide interactive ways to subscribe, send and receive Solace messages. Spring Boot is not required. You can make use of the Spring Cloud Connectors in any Java Application. See the walk through tutorials for more details.
All of these sample applications have full walk through tutorials that explain the code in detail. Tutorials for each sample are available here:
* https://dev.solace.com/samples/solace-samples-cloudfoundry-java/
What follows is a brief summary for people that want to dive straight into the code.
## Common Setup
The sample applications specify a dependency on a Solace Pubsub+ service instance named `solace-pubsub-sample-instance`. To create the required Solace PubSub+ service instance, do the following:
cf create-service solace-pubsub shared solace-pubsub-sample-instance
### Building
Just clone and build. For example:
1. clone this GitHub repository
1. `./gradlew build`
### Deploying
To deploy the individual applications to Cloud Foundry:
1. cd to the project directory (`java-app` or `spring-cloud`)
1. `$ cf push`
## Java Application
application name: `solace-sample-java-app`
This application uses the Java library from http://www.JSON.org/ to parse the `VCAP_SERVICES` environment variable to determine the connection details for Solace PubSub+. For more details and example usage, see the walk through tutorial here:
* [Online Tutorial](https://dev.solace.com/samples/solace-samples-cloudfoundry-java/java-app/)
## Java Application using Spring Cloud Connector
application name: `solace-sample-spring-cloud`
This application makes use of the Spring Cloud Connectors project to automatically parse the `VCAP_SERVICES` environment variable. Applications do *not* have to be a Spring Boot application to make use of Spring Cloud Connectors. This example makes use of Spring Boot for convenience in enabling the simple REST API. In any Java Applications, simply specify the following dependencies in your build:
compile 'org.springframework.cloud:spring-cloud-spring-service-connector:1.2.3.RELEASE'
compile 'org.springframework.cloud:spring-cloud-cloudfoundry-connector:1.2.3.RELEASE'
compile 'com.solace.cloud.cloudfoundry:solace-spring-cloud-connector:2.1.+'
The `solace-spring-cloud-connector` is a Spring Cloud Connectors extension to parse the `VCAP_SERVICES` for the Solace PubSub+ service instance information. Check out the project page for more details:
* https://github.com/SolaceProducts/solace-spring-cloud/tree/master/solace-spring-cloud-connector
The easiest way for applications to access the SolaceServiceCredentials object is by Service Id (ex: "MyService) as follows:
CloudFactory cloudFactory = new CloudFactory();
Cloud cloud = cloudFactory.getCloud();
SolaceServiceCredentials solaceServiceCredentials = (SolaceServiceCredentials) cloud.getServiceInfo("MyService");
Alternatively applications could search through the environment and discover matching services as follows:
SolaceServiceCredentials solaceServiceCredentials = null;
List<ServiceInfo> services = cloud.getServiceInfos();
// Connect to the first Solace PubSub+ service that is found in the services list.
for (ServiceInfo service : services) {
if (service instanceof SolaceServiceCredentials) {
solaceServiceCredentials = (SolaceServiceCredentials)service;
break;
}
}
For more details and example usage, see the walk through tutorial here:
* [Online Tutorial](https://dev.solace.com/samples/solace-samples-cloudfoundry-java/spring-cloud/)
## Java Application using Java CFEnv
application name: `solace-sample-spring-cloud-java-cfenv`
This application makes use of the Java CFEnv project to automatically parse the `VCAP_SERVICES` environment variable. In any Java Applications, simply specify the following dependencies in your build:
compile 'com.solace.cloud.cloudfoundry:solace-java-cfenv'
The `solace-java-cfenv` is the successor to `solace-spring-cloud-connector` due to the deprecation of Spring Cloud Connectors. It is a Java CFEnv extension to parse the `VCAP_SERVICES` for the Solace PubSub+ service instance information. Check out the project page for more details:
* https://github.com/SolaceProducts/solace-spring-boot/tree/master/solace-java-cfenv
To access the SolaceServiceCredentials object, applications must retrieve it in a manner similar to the following:
SolaceServiceCredentials solaceServiceCredentials = null;
List<SolaceServiceCredentials> solaceServiceCredentialsList = SolaceServiceCredentialsFactory.getAllFromCloudFoundry();
// Connect to the first Solace PubSub+ service that is found in the services list.
if (solaceServiceCredentialsList.size() > 0) {
solaceServiceCredentials = solaceServiceCredentialsList.get(0);
}
## Secure Session
application name: `solace-sample-secure-session`
This application is based on the [Solace Java CFEnv](https://github.com/SolaceProducts/solace-spring-boot/tree/master/solace-java-cfenv) described above, but shows how to use
Transport Level Security (TLS) between the Java application and the Solace PubSub+ Service Instance.
* [Online Tutorial](https://dev.solace.com/samples/solace-samples-cloudfoundry-java/secure-session/)
## LDAP
This is not a standalone application, but instead a modification to the existing sample apps.
If application access is enabled by the cloud operator, bindings will not contain application access credentials and the credentials will instead have to be provided to the application externally.
This manifests as the service instance owner having to manually configure LDAP authorization groups for application access.
* [Online Tutorial](https://dev.solace.com/samples/solace-samples-cloudfoundry-java/ldap/)
## Try out the Applications
The sample applications have a simple REST interface that allows you to subscribe, send and receive Solace messages. You can try the applications out using command like the following.
Determine the URL of the sample application and export it for use in the `curl` commands. Adjust the app name as appropriate to match the sample you're using:
export APP_NAME=solace-sample-java-app
export APP_URL=`cf apps | grep $APP_NAME | grep started | awk '{ print $6}'`
echo "The application URL is: ${APP_URL}"
Subscribe to topic "test"
curl -X POST -H "Content-Type: application/json;charset=UTF-8" -d '{"subscription": "test"}' http://$APP_URL/subscription
Send message with topic "test"
curl -X POST -H "Content-Type: application/json;charset=UTF-8" -d '{"topic": "test", "body": "TEST_MESSAGE"}' http://$APP_URL/message
The message is received asynchronously, check for the last message.
curl -X GET http://$APP_URL/message
Unsubscribe the application from topic "test"
curl -X DELETE http://$APP_URL/subscription/test
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Authors
See the list of [contributors](https://github.com/SolaceSamples/solace-samples-cloudfoundry-java/contributors) who participated in this project.
## License
This project is licensed under the Apache License, Version 2.0. - See the [LICENSE](LICENSE) file for details.
## Resources
For more information try these resources:
- [Tutorials](https://tutorials.solace.dev/)
- The Solace Developer Portal website at: http://dev.solace.com
- Get a better understanding of [Solace technology](http://dev.solace.com/tech/).
- Check out the [Solace blog](http://dev.solace.com/blog/) for other interesting discussions around Solace technology
- Ask the [Solace community.](http://dev.solace.com/community/)
| 0 |
helloworlde/spring-cloud-alibaba-component | Sample of Spring Cloud Alibaba component | nacos seata spring-boot spring-cloud spring-cloud-alibaba | # Spring Cloud Alibaba 组件使用
## Nacos
> Nacos 是一个配置和注册中心,类似 Spring Cloud Config 和 Eureka、ZooKeeper、Consul
- [Spring Boot 使用 Nacos 作为配置中心](./boot-config/README.md)
- [Spring Cloud 使用 Nacos 作为配置中心](./cloud-config/README.md)
- [Spring Cloud 使用 Nacos 作为服务注册中心](./cloud-discovery/README.md)
## Sentinel
> Sentinel 是一个流量控制框架,支持流量控制,熔断降级,系统负载保护,类似 Hystrix、resilience4j
- [Spring Cloud 使用 Sentinel 作为限流降级工具](./sentinel-nacos-config/README.md)
## OSS
> spring-cloud-starter-alicloud-oss 是用于阿里云 OSS 的 SpringBoot Starter,通过封装 SDK 实现对 OSS 的操作
- [Spring Cloud 使用阿里云 OSS](./cloud-oss/README.md)
## Dubbo
> Dubbo 是一个远程调用框架,用于实现方法的远程调用
推荐使用 ZooKeeper 作为注册中心,当前使用 Nacos 会有各种问题
- [Spring Cloud 使用 Dubbo 实现远程调用,Nacos 作为注册中心](./cloud-dubbo-nacos/README.md)
- [Spring Cloud 使用 Dubbo 实现远程调用,ZooKeeper 作为注册中心](./cloud-dubbo-zk/README.md)
## Seata
> Seata 是一个分布式事务框架,可以通过 Seata 框架的注解实现非侵入性的分布式事务
- [Spring Cloud 使用 Seata 实现分布式事务 - MyBatis](./cloud-seata-mybatis/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - JPA](./cloud-seata-jpa/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - Mybatis/Nacos](./cloud-seata-nacos/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - Mybatis/Nacos/Dubbo](./cloud-seata-dubbo-nacos/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - Mybatis/Eureka/Feign](./cloud-seata-eureka/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - Mybatis多数据源](./cloud-seata-multi-datasource/README.md)
- [Spring Cloud 使用 Seata 实现分布式事务 - Mybatis多数据源 & MyBatisPlus](./cloud-seata-multi-datasource-mybatis-plus/README.md)
MyBatis 和 JPA 通过 Seata 实现分布式事务都需要注入 `io.seata.rm.datasource.DataSourceProxy`, 不同的是,MyBatis 还需要额外注入 `org.apache.ibatis.session.SqlSessionFactory`
<details>
<summary>MyBatis</summary>
```java
@Configuration
public class DataSourceProxyConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
@Bean
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
@Bean
public SqlSessionFactory sqlSessionFactoryBean(DataSourceProxy dataSourceProxy) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSourceProxy);
return sqlSessionFactoryBean.getObject();
}
}
```
</details>
<details>
<summary>JPA</summary>
```java
@Configuration
public class DataSourceProxyConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
@Primary
@Bean
public DataSourceProxy dataSource(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
}
```
</details>
------------------
## 版本说明
相关的 Spring Boot, Spring Cloud 以及 Spring Cloud Alibaba 之间的对应关系可以参考 [版本说明](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E)
| 组件 | 版本 | 说明|
|:----|:-----|:----|
|Spring Boot |2.1.5.RELEASE||
|Spring Cloud |Greenwich.SR1||
|Spring Cloud Alibaba |2.1.0.RELEASE||
|Seata |0.7.1||
|Dubbo |2.7.3||
Spring Cloud Alibaba 毕业后,Group-id 和部分 ArtifactId 有所变化,需要注意 | 1 |
CasterIO/RxExamples | Samples from the Rx Episodes on Caster.IO | null | null | 0 |
cuub/sugared-list-animations-sample | Sugared List Animations Sample | null | SugaredListAnimations Sample
=========
<br />Demo app for [SugareListAnimations]
Donwload [here].
License
-
MIT
*Free Software, Fuck Yeah!*
[SugareListAnimations]: https://github.com/cuub/sugared-list-animations
[here]: http://goo.gl/JWIb0
| 1 |
BarathArivazhagan/spring-cloud-sidecar-polygot | This project contains samples demonstrating the usage of side car polygot | microservice nodejs side-car sidecar spring-boot spring-cloud zuul-proxy | # spring-cloud-sidecar-polygot-demo
This project demonstrates the usage of netflix`s side car polygot.
Spring cloud side car helps to register non jvm applications in eureka service registration server and available as part of service discovery to route traffic to non jvm applications through sidecar proxy.
> <b> Note: </b> Branches 1.x.x/2.x.x versions makes it compatible with spring boot versions 1.x.x/2.x.x.
> Kindly choose branch as per spring boot release versions.
![side car](images/sidecar.png)
#### Compatability Matrix
choose the branch based on below versions.
<table>
<tr>
<th style="text-align:left">Branch/Version</th>
<th style="text-align:left">Spring Boot</th>
<th style="text-align:left">Spring Cloud</th>
<th style="text-align:left">Node Js</th>
</tr>
<tr>
<td>master</td>
<td>2.3.0.RELEASE</td>
<td>Hoxton.SR5</td>
<td>14.4.0</td>
</tr>
<tr>
<td>2.2.2</td>
<td>2.2.2.RELEASE</td>
<td>Hoxton.RELEASE</td>
<td>12.4.0</td>
</tr>
<tr>
<td>2.1.5</td>
<td>2.1.5.RELEASE</td>
<td>Greenwich.SR1</td>
<td>12.4.0</td>
</tr>
<tr>
<td>2.1.4</td>
<td>2.1.4.RELEASE</td>
<td>Greenwich.RELEASE</td>
<td>12.4.0</td>
</tr>
<tr>
<td>2.1.2</td>
<td>2.1.2.RELEASE</td>
<td>Greenwich.RC2</td>
<td>10.16.0</td>
</tr>
<tr>
<td>2.0.3</td>
<td>2.0.3.RELEASE</td>
<td>Finchley.RELEASE</td>
<td>8.16.0</td>
</tr>
<tr>
<td>1.5.6</td>
<td>1.5.6.RELEASE</td>
<td>Dalston.SR3</td>
<td>8.16.0</td>
</tr>
</table>
#### Projects
<table>
<tr>
<th style="text-align:left">Name</th>
<th style="text-align:left">Port</th>
<th style="text-align:left">Description</th>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/eureka-server"> eureka-server</a></td>
<td>9000</td>
<td>Eureka server - service registration server</td>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/csstore-microservice">csstore-microservice</a></td>
<td>9001</td>
<td>Service discovery microservice registered with eureka server</td>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/msstore-microservice">msstore-microservice</a></td>
<td>9002</td>
<td>Service discovery microservice registered with eureka server</td>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/sidecar">sidecar</a></td>
<td>9004</td>
<td>Side car proxy for routing and filtering to wstore node app</td>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/wstore-node-express">wstore-node-express</a></td>
<td>3000</td>
<td>Node express (non jvm ) application </td>
</tr>
<tr>
<td><a href="https://github.com/BarathArivazhagan/spring-cloud-sidecar-sample/tree/master/zuul-proxy">zuul-proxy</a></td>
<td>9005</td>
<td>Zuul proxy for routing and filtering</td>
</tr>
</table>
## How to build and run ?
* Download/Clone the repository :
```
$ git clone https://github.com/BarathArivazhagan/spring-cloud-sidecar-polygot.git
$ cd spring-cloud-sidecar-polygot
```
* Maven build :
```sh
$ ./mvnw clean install
```
* Docker image build :
```sh
# Note change the docker images as per your image name in docker compose file
$ docker-compose build
```
* To run the application :
```sh
$ docker-compose up
```
## How to test the application ?
Use zuul proxy to route to respective microservices.
zuul route definition :
```
zuul:
routes:
msstore :
path: /msstore/**
url: http://localhost:9002
csstore:
path: /csstore/**
url: http://localhost:9001
```
## Service Urls:
<table>
<tr>
<td><a href="http://localhost:9005/msstore">http://localhost:9005/msstore</a></td><td>msstore</td>
</tr>
<tr>
<td><a href="http://localhost:9005/csstore">http://localhost:9005/csstore</a></td><td>csstore</td>
</tr>
<tr>
<td><a href="http://localhost:9004/wstore/home">http://localhost:9005/csstore</a></td><td>wstore</td>
</tr>
</table>
## Side car route definition
```
zuul:
routes:
wstore:
path: /wstore/**
url: http://localhost:3000
sidecar:
port: 3000
health-uri: http://localhost:3000/health
```
### Notes :
<b>sidecar.port</b> : Port must be same as the non jvm port <br>
<b>sidecar.health-uri</b>: non jvm application should expose this url with json message {"STATUS" : "UP"} to indicate sidecar the app is UP.
## How to test sidecar ?
<div>
Navigate to <a href="http://localhost:9004/wstore/home">http://localhost:9004/wstore/home</a> --> sidecar routes to non jvm(nodejs app)
</div>
## Why Zuul as well as side car ?
yes, thats right. `@EnableSideCar` includes `@EnableZuulProxy`,so side car can act as zuul proxy itself.
In order to provide separate proxy for side car(non jvm) based applications, this repo contains two proxies
<i>zuul-proxy</i> : provides proxy to jvm based applications. <br>
<i>sidecar </i> : provides proxy to non jvm based applications.
## How to rebuild the project after the changes?
```
$ docker-compose build
```
## References
* http://cloud.spring.io/spring-cloud-netflix/spring-cloud-netflix.html
| 0 |
rubensousa/Transitions | A sample that showcases some transitions | null | # Transitions
A sample that showcases some transitions
<img src="screenshots/fab.gif" width="350"> <img src="screenshots/shared.gif" width="350">
<img src="screenshots/layout.gif" width="350">
## References
http://guides.codepath.com/android/shared-element-activity-transition
https://github.com/lgvalle/Material-Animations
https://material.io/guidelines/motion/choreography.html#
| 1 |
ekirastogi/spring-boot-gradle-mvc | SpringBoot Gradle MVC sample application | null | # SpringBoot-MVC-application
SpringBoot Gradle MVC sample application
This is a sample Spring Boot Application that uses
1. JDBC
2. Mysql
3. JPA
4. MVC
5. Gradle
To use this application follow the steps listed below
1. git clone git@github.com:gitekiras/spring-boot-gradle-mvc.git
2. go to this directory
3. add mysql database name and password in application.properties
4. go to mysql and create a database with name mentioned in application.properties
5. run commands
a. gradle clean;
b. gradle build;
c. gradle bootRun;
And you are good to go.
#Happy coding !!
| 1 |
spring-cloud-samples/bookstore-service-broker | Sample application for Spring Cloud Open Service Broker | cloudfoundry kubernetes open-service-broker open-service-broker-api | null | 1 |
terasolunaorg/terasoluna-tourreservation-mybatis3 | Sample Application (MyBatis3 version) | null | ## Tour Reservation Sample Application
This is a reference application built completely using TERASOLUNA Server Framework for Java (5.x) ([http://terasoluna.org](http://terasoluna.org "http://terasoluna.org")).
This application shows **how an IDEAL project configuration and package structure must be like.** It also shows working sample of best practices recommended in TERASOLUNA Server Framework for Java (5.x) Development Guideline.
**This sample uses MyBatis3.**
### Getting started
#### Download
Download source code from [here](https://github.com/terasolunaorg/terasoluna-tourreservation-mybatis3/releases "here").
Extract the zip file at any location of choice.
#### Run PostgreSQL
Install and start PostgreSQL.
select 'P0stgres' as password for db user or select any password of choice. Be sure to remember the password.
If 'P0stgres' is not used, some changes will be required in configuration files. Hence be sure to remember it.
### Run PostgreSQL
Install and start PostgreSQL.
create database 'tourreserve'.
#### Insert test data
It is assumed that maven is already installed.
Move to the directory where the downloaded source-code is unzipped.
If password of db user is set to 'P0stgres' its not required to edit any file and directly execute the below command.
If it is set to any other password, then update the password in `terasoluna-tourreservation-initdb/pom.xml`.
Execute the below command:
```console
$ mvn -f terasoluna-tourreservation-initdb/pom.xml sql:execute
```
Test data is currently available in Japanese only.
#### Install jars and build war
If db user password is not set to 'P0stgres', then go to `terasoluna-tourreservation-env/src/main/resources/META-INF/spring/terasoluna-tourreservation-infra.properties` and update the password. If it is set to 'P0stgres', no changes are required.
```console
$ mvn clean install
```
#### Run server and deploy war
Deploy `terasoluna-tourreservation-web/target/terasoluna-tourreservation-web.war` to your Application server (e.g. Tomcat9)
You can also use `mvn cargo:run` to test this application quickly with option `MAVEN_OPTS=-XX:MaxPermSize=256m` in environment variable.
```console
$ mvn -f terasoluna-tourreservation-web/pom.xml cargo:run
```
access [http://localhost:8080/terasoluna-tourreservation-web/](http://localhost:8080/terasoluna-tourreservation-web/)
Alternatively, these project can also be imported into Eclipse and application can be run using WTP.
#### Test with selenium
Install Firefox to run test.
[geckodriver](https://github.com/mozilla/geckodriver/releases) (`v0.30.0` recommended) placed in application execution environment and add to `PATH`.
Run test.
```console
$ mvn -f terasoluna-tourreservation-selenium/pom.xml clean test
```
> **Note:**
>
> If GeckoDriver is not registered in the path, [webdrivermanager](https://github.com/bonigarcia/webdrivermanager) will download it automatically.
> Configure using [properties](https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api) in `wdm.properties` or Java System Properties.
| 1 |
OlivierLD/raspberry-coffee | JVM related (Java, Groovy, Scala, Kotlin, etc) samples for the Raspberry PI, relying on PI4J. IoT and friends. | electronic-components gradle java jvm jvm-languages pi4j raspberry-pi | <h1><img align="middle" alt="Raspberry Coffee" src="./raspberryCoffee.png"> Raspberry Coffee</h1>
#### Java code and wirings for the Raspberry Pi, featuring reusable libraries and snippets
> This project was started in 2015.
> Among several modules, some emerged. We clearly have two major threads:
> - Actuators and Sensors (look into `raspberry-io-pi4j` and others)
> - Navigation utilities (look into `raspberry-sailor`, `NMEA-multiplexer` and others)
>
> Those two above can interact. For example, navigation software can use sensors.
> And again, this project is not limited to those two threads, by far.
---
Main keywords:
- Raspberry Pi
- Java and JVM-related languages
- [PI4J](https://pi4j.com/), Sensors, Actuators
- Navigation, Sailing, [NMEA](https://nmea.org)
- Gradle
- Maven
- Github
---
- Sensors & Actuators interaction (through Raspberry Pi's GPIO header)
- Different communication protocols (HTTP, TCP, WebSockets, MQTT, ...)
- NMEA protocol implementations (and related utilities)
---
- Some modules will also use [`OpenCV`](https://opencv.org/) (an OpenSource Project for Computer Vision). See below how _not_ to use them, if needed. It's worth a look, though.
---
The project - and its different modules - are built using [`Gradle`](https://gradle.org/).
Some modules also use the `librxtx` library for Serial IO (details given below)
---
This project is divided in several modules (Gradle modules, not git sub-modules).
Some noticeable ones are
- `raspberry-io-pi4j`
- Contains implementation modules for various break-out boards and various communication protocols (I2C, SPI, UART, GPIO) through
the Raspberry Pi's GPIO header, and the `PI4J` library
- Other libraries (like `diozero`) might show up later.
- . . .
The point of truth, telling you what module uses what modules, is the `build.gradle` of the module you are interested in.
To see the full structure, from the repo's root, type
```
$ ./gradlew project [--info]
```
---
The modules under `raspberry-io-pi4j` use the [`PI4J library`](http://pi4j.com) (Version **1.x**. Version **2.x** brings in some new architecture and paradigm, not dealt with yet), itself relying on [`WiringPi`](http://wiringpi.com/).
> Note: `WiringPi` is now deprecated (since 2019, apparently), which makes `PI4J v1.*` deprecated too.
> ...More to come. We are evaluating other options, like
> - [`PI4J V2`](https://pi4j.com/)
> - [`diozero`](https://www.diozero.com/)
> - [`JOB`](https://github.com/OlivierLD/JOB)
>
### Java
Java downloads can come in two main flavors:
- The Java Runtime Environment (JRE), that allows you to _run_ Java programs (ie programs compiled to run on a JVM)
- The Java Development Kit (JDK), a superset ot the JRE, that also allows you to _develop_ Java programs.
Obviously, we need a JDK.
Since 2019 or so, Java (JDK 11) comes with the RasPi OS.
So you do not need to install it. To check its availability:
```
$ java -version
$ javac -version
```
#### Processing
[Processing](https://processing.org/) is a _**very cool**_ framework, initially developed for Java, that considerably simplify code development, with great results,
implementing the concept of sketchbooks, used and reused many times since its introduction.
Some examples in this repo will indeed use Processing.
It is - at least! - a great way to get started with Java.
Processing is now also available for other languages than Java.
### PI4J
PI4J is a Java library that will help you access `GPIO`, `I2C`, `SPI`, `PWM`, and other hardware protocols.
```
$ # curl -s get.pi4j.com | sudo bash
$ curl -sSL https://pi4j.com/install | sudo bash
```
### Latest (and maybe last) WiringPi
```
wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-latest.deb
```
Or from the source:
```
sudo apt-get remove wiringpi -y
sudo apt-get --yes install git-core gcc make
cd ~
git clone https://github.com/WiringPi/WiringPi --branch master --single-branch wiringpi
cd ~/wiringpi
sudo ./build
```
### Gradle
The project comes with scripts `gradlew` (and its `gradlew.bat`, for Windows).
The `w` stands for `wrapper`. When used - like in `./gradlew tasks --all`, the wrapper
will check if `gradle` is here, and install it if it is not there.
This installation is driven by the file `gradle/wrapper/gradle-wrapper.properties`.
This is the file to deal with, if an upgrade of the Gradle version is required.
> _<u>Note</u>_: We are using here the `shadowJar` Gradle plug-in. This plug-in allows the generation of what's also called a "fat-jar",
> a _**single**_ jar for all the application, including _**all**_ its dependencies.
> That does indeed make deployment and distribution much easier.
> _<u>Another note</u>_: Some scripts will be featured here, to run the different modules.
> **Those scripts are written to run in the development environment**. They can be easily tweaked to run
> in any other context.
> ```
> CP=./build/libs/NMEA-mux-PI4J-1.0-all.jar
> java -cp ${CP} nmea.consumers.client.AISClient
> ```
> You may very well run the **exact** same thing, by delivering only the script and the jar, together in the same folder,
> all you need to do is to change the location of the delivered jar-file (saying script and jar are in the same location):
> ```
> java -cp ./NMEA-mux-PI4J-1.0-all.jar nmea.consumers.client.AISClient
> ```
> _Think about that_: You might not be able to **build** (using the provided Gradle scripts) an application on a small board like a Raspberry Pi Zero,
> but this small board could very well be big enough to **run** it comfortably.
> You build it from a big-enough machine, and you `scp` the jar to the one you want to run it on,
> and be done with it.
### Gradle tweaks
From the root of this project, you can run a full build, that would also tell you if everything is working.
Just run
```
$ ./gradlew clean build
```
Depending on the size of the computer you are using (a laptop, a Raspberry Pi Zero, etc), you might want to skip
demanding steps (like Scala and Kotlin compilations), or the tests, if they are not required in your context.
To skip a task in Gradle, you need to use the `-x` (like eXclude) flag.
Example, to skip the tests:
```
$ ./gradlew clean build -x test
```
To skip the Scala and Kotlin compilations, and the tests:
```
$ ./gradlew clean build -x test \
-x :RasPISamples:compileScala \
-x :OtherJVMLanguages:compileScala \
-x :http-client-paradigm:compileScala \
-x :http-client-paradigm:compileKotlin \
-x :Project-Trunk:System-Languages:compileKotlin \
-x :Project-Trunk:System-Languages:compileScala \
-x :Project-Trunk:Weather-Station-Implementation:compileScala \
-x :Project-Trunk:REST-clients:REST-assembler:compileKotlin \
-x :Project-Trunk:REST-clients:REST-assembler:compileScala
```
_**Warning**_: Some parts of this project use `OpenCV`, that need to be installed separately. If you've not installed it,
or wish to skip those steps, use
```
$ ./gradlew clean build -x :opencv:compileJava -x :Project-Trunk:WebcamTemplate:compileJava
```
To know the structure of the full project:
```
$ ./gradlew projects [--info]
```
### git
If you can read this, you obviously know what `git` is... And just in case, Google is your friend (for that part).
### Integrated Development Environment (IDE)
IDEs are not mandatory (any editor, like `vi`, which works everywhere Linux or any [BSD](https://en.wikipedia.org/wiki/Berkeley_Software_Distribution) clone runs, would be good enough), but they make Java development _much_ easier. Several are available for free (NetBeans, Eclipse, IntelliJ, BlueJ, VisualCode...).
I like IntelliJ, but you can use anyone you want or prefer.
Depending on the IDE you are using, there are two main features you might be interested in:
- Remote development
- Your IDE might be too demanding for a Raspberry Pi (depending on the model you are using...). Remote development will allow you to
have the IDE on a laptop (or desktop, of course), and the files it deals with on the Raspberry Pi. It usually uses a protocol like `ssh` and its related technologies (`scp`, `rsync`, etc).
- Remote debugging
- This is implemented through the JPDA (Java Platform Debugging Architecture) protocol, that comes with Java, and
possibly implemented by your IDE. You _run_ the code on the Raspberry Pi, and you _debug_ (breakpoints, variable inspections, etc) on your laptop.
> _**Remote Debugging example**_:
> We want to run and debug the class `analogdigitalconverter.sample.MainMCP3008Sample`.
> Here is a script to run on the Raspberry Pi (the remote debuggee), notice the `REMOTE_DEBUG_FLAGS` variable below, and the port `5005`.
> ```
> #!/bin/bash
> echo Read an ADC
> #
> JAVA_OPTS=
> JAVA_OPTS="$JAVA_OPTS -Dadc.verbose=false"
> JAVA_OPTS="$JAVA_OPTS -Ddisplay.digit=false"
> CP=./build/libs/ADC-1.0-all.jar
> #
> REMOTE_DEBUG_FLAGS=
> REMOTE_DEBUG_FLAGS="${REMOTE_DEBUG_FLAGS} -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005"
> #
> # Channel [0..1] can be passed as prm. Default is 0
> sudo java -cp ${CP} ${JAVA_OPTS} ${REMOTE_DEBUG_FLAGS} analogdigitalconverter.sample.MainMCP3008Sample $*
> ```
> Now, from your IDE (IntelliJ here) on the debugger machine, create a profile:
> ![Remote debug profile](./remote.debug.profile.png)
> Notice the `Command line arguments for remote JVM`, and the port, `5005`.
> Depending on the kind of app you want to debug, you might need to set `suspend=y` in the `-agentlib` directive. This
> will wait for the remote debugger to connect.
> - In the IDE, in the code you want to debug, set breakpoint(s).
> - Start the app (as per the script above) on the debuggee (the Raspberry here)
> - Then start the debugger in the IDE, using the remote-debug profile you created
>
> More [here](https://www.jetbrains.com/help/idea/tutorial-remote-debug.html)
---
#### Remote Development
- For Visual Studio Code; <https://code.visualstudio.com/docs/remote/remote-overview>
- For JetBrain (IntelliJ): <https://www.jetbrains.com/help/idea/remote-development-a.html> (seems to require a 64-bit remote host)
This being said, let's go.
---
### Get started, from scratch, now!
If `git` and `java` are available (and they should) on your Raspberry Pi, just run
```
bash -c "$(curl -L https://raw.githubusercontent.com/OlivierLD/raspberry-coffee/master/install.sh)"
```
The command above will clone the repository, and install Gradle if needed.
---
This project contains Java code, many times translated from Python, dedicated to usually *one* board (like BMP180, LSM303, etc).
More consistent samples can be found in the RasPISamples module (being moved to the `Project-Trunk` module), where several components have been assembled together.
Do take a look, it also comes with a readme file.
---
Raspberry Pi's [Mechanical drawings](https://www.raspberrypi.org/documentation/hardware/raspberrypi/mechanical/README.md)
---
- [Main highlights](./Papers/README.md)
---
**Summary**
- [Setup a brand new Raspberry Pi](#setup-a-brand-new-raspberry-pi)
- [Java Virtual Machine](#java-virtual-machine-jvm)
- [How to build and run](#how-to-build-and-run)
- [Developing on the Raspberry Pi, or Developing for the Raspberry Pi ?](#developing-on-the-raspberry-pi-or-developing-for-the-raspberry-pi-)
- [Raspberry Pi, a possible thing of the Internet of Things...](#raspberry-pi-a-possible-thing-of-the-internet-of-things)
- [Project list, growing](#project-list-growing)
#### Setup a brand-new Raspberry Pi
To get started as quickly as possible, and not only for this project, from scratch.
##### Foundation Software
The goal here is to get ready with the minimal configuration you will be able to use to clone a git repository and start working on it.
Typically, you will need to have the minimal git tools and the right compilers. The code contained in the repo(s) will be responsible for
downloading the right dependencies at build time (`gradle` is definitely good at that).
##### Minimal setup
- Install Raspbian (not NOOBS) as explained at https://www.raspberrypi.org/learning/software-guide/quickstart/, and burn your SD card
- Depending on the OS you burn the SD card from, the procedure varies. Well documented in the link above.
- Boot on the Raspberry with the new SD card, USB keyboard and HDMI screen attached to it (if this is an old RPi, use a USB WiFi dongle too)
- It should boot to the Graphical Desktop.
- Connect to your local network
- Use RPi-Config (from the Desktop GUI, Menu > Preferences > Raspberry Pi Configuration) to:
- enable needed interfaces (ssh, serial, spi, i2c, VNC, etc)
- `ssh` and `VNC` will allow remote access to your Raspberry Pi, the others depend on the projects you want to work on.
- This can be modified or reverted at any time.
- setup config (keyboard, locale, etc)
- change pswd, hostname
- for the hostname, you might need to go a Terminal, reach `sudo raspi-config`, and use `Network > Hostname`.
- Reboot (and now, you can use `ssh` if it has been enabled above) and reconnect
- From a terminal, run the following commands:
```
$ sudo apt-get update
$ sudo apt-get install vim
```
- setup your `.bashrc` as needed, adding for example lines like
```
alias ll="ls -lisah"
```
- recent Raspbian releases come with a development environment that includes
- JRE & JDK
- git
- python
- C Compiler (gcc, g++)
```
# Optional: sudo apt-get install -y curl git build-essential default-jdk
# Optional too, to install nodejs and npm:
$ sudo su -
root# curl -sL https://deb.nodesource.com/setup_9.x | bash -
root# exit
$ sudo apt-get install -y nodejs
```
`screen` is nice to have too:
```
$ sudo apt-get install screen
$ screen -version
```
- make sure what you might need is installed, by typing:
```
$ java -version
$ javac -version
$ git --version
$ python --version
$ python3 --version
$ gcc -v
$ node -v
$ npm -v
```
- some utilities, to make sure they are present, type:
```
$ which scp
$ which curl
$ which wget
```
- You can use VNC (if enabled in the config above)
- Run `vncserver` from a terminal, and use `VNC Viewer` from another machine to connect.
- You may also remove unwanted software, just in case you don't need them:
- `$ sudo apt-get purge wolfram-engine` (that one's worth keeping, though)
- `$ sudo apt-get purge minecraft-pi`
- `$ sudo apt-get purge sonic-pi`
- `$ sudo apt-get purge libreoffice*`
- `$ sudo apt-get clean`
- `$ sudo apt-get autoremove`
- If you need AI and Deep Learning (Anaconda, Jupyter notebooks, TensorFlow, Keras), follow [this link](https://medium.com/@margaretmz/anaconda-jupyter-notebook-tensorflow-and-keras-b91f381405f8).
- or type:
```
$ wget https://repo.anaconda.com/archive/Anaconda3-5.3.0-Linux-x86_64.sh
```
- [Anaconda on Raspberry Pi](https://qiita.com/jpena930/items/eac02cb4e635bfba83d8)
- [Jupyter Notebooks on Raspberry Pi](https://www.instructables.com/id/Jupyter-Notebook-on-Raspberry-Pi/)
- Start Jupyter Notebooks by typing `jupyter notebook [--allow-root] --ip 0.0.0.0 --no-browser`
- Then the command to use to reach Jupyter would show up in the console.
- _Note:_ Training a Neural Network is a very demanding operation, that requires computing resources not granted on a Raspberry Pi. Installing Keras on a Raspberry Pi might not be relevant. OpenCV, though, would be an option to consider. Google it ;).
- _Jupyter Notebooks_ were originally developed for Python, but they're now also available for pretty much any language that comes with a REPL (Read Execute Print Loop), like Java (9+), Scala, NodeJS, ...
- [Spencer Park / IJava](https://github.com/SpencerPark/IJava)
- [Almond, for Scala](https://almond.sh/)
- [IJavaScript](https://github.com/n-riesco/ijavascript)
- . . .
### Extra softs
- Docker
```
$ curl -sSL https://get.docker.com | sh
```
- Go
```
$ wget https://dl.google.com/go/go1.9.2.linux-armv6l.tar.gz
$ sudo tar -C /usr/local -xzf go1.9.2.linux-armv6l.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ go version
go version go1.9.2 linux/arm
```
- dep - Package manager for Go
```
$ go get -u github.com/golang/dep/cmd/dep
$ sudo cp ~/go/bin/dep /usr/local/bin/
$ dep version
dep:
version : devel
build date :
git hash :
go version : go1.9.2
go compiler : gc
platform : linux/arm
```
- Fing CLI, nice to have.
- Make sure you use the [`Fing CLI`](https://www.fing.com/products/development-toolkit) for your system, `dpkg --print-architecture` will tell you what to choose, `lscpu` too.
- To know your architecture:
- `uname -m`, `lscpu`
- `AMRv7l` is 32 bits, `ARMv8` is 64 bits
- `file /lib/systemd/systemd`, `getconf LONG_BIT`
##### Connect to the Raspberry Pi from your laptop, using a USB cable
It's easy, and convenient. See [here](https://www.thepolyglotdeveloper.com/2016/06/connect-raspberry-pi-zero-usb-cable-ssh/),
or [here](https://magpi.raspberrypi.org/articles/build-a-raspberry-pi-zero-keyring).
To connect to a Raspberry Pi Zero, all you need is a USB cable [A-to-microB](https://www.adafruit.com/product/592).
Some other devices can be nice to have:
- [USB to TTL Serial Cable - Debug / Console Cable for Raspberry Pi](https://www.adafruit.com/product/954)
- [Zero Stem for Pi Zero 1.3 and Pi Zero W 1.1](https://www.adafruit.com/product/3945)
- [Adafruit PiUART - USB Console and Power Add-on for Raspberry Pi](https://www.adafruit.com/product/3589)
Once your RPi is connected through a USB connection, after configuring it as explained, you can use `ssh` as follow:
```
$ ssh pi@raspberrypi.local
```
where `raspberrypi` is the `hostname` of the Raspberry. No wireless connection or IP address is required.
##### Mount a CD-ROM
See <https://snapcraft.io/install/cdrom/raspbian>
```
sudo apt update
sudo apt install snapd
```
```
sudo reboot
```
```
sudo snap install core
```
```
sudo snap install [--edge] cdrom
```
##### Raspberry Pi as an Access Point _and_ Internet access.
Your Raspberry Pi can be turned into an Access Point, this means that it generates its own network, so you can connect to it from other devices (other Raspberry Pis, laptops, tablets, smart-phones, ESP8266, etc).
It can be appropriate when there is no network in the area you are in, for example when sailing in the middle of the ocean, kayaking in a remote place, hiking in the boonies, etc.
Setting up the Raspberry Pi to be an access point is well documented on the [Adafruit website](https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software).
[This one](http://hawksites.newpaltz.edu/myerse/2018/06/19/dhcp-daemon-on-raspberry-pi/) is also useful.
And [this too](https://learn.sparkfun.com/tutorials/setting-up-a-raspberry-pi-3-as-an-access-point).
As we said above, to enable `hostapd` to have your Raspberry Pi acting as a WiFi hotspot, you can follow
<a href="https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software" target="adafruit">those good instructions</a> from the Adafruit website.
Also take a look at [that one](https://github.com/OlivierLD/AllLanguagesScratchPad/blob/master/rpi.networking/setup.md).
> _**Warning**_: Since Raspbian's Stretch release, **a lot** of things have changed for the network config. See [here](http://www.raspberryconnect.com/network/item/333-raspberry-pi-hotspot-access-point-dhcpcd-method).
**>>> Skip to the next section if you run Stretch or later** (as I am). Consider the Ethernet option ;)
The thing is that when the Raspberry Pi becomes a WiFi hotspot, you cannot use it to access the Internet, cannot use `apt-get install`, cannot use
`git pull origin master`, etc, that can rapidly become quite frustrating.
Now, for development purpose, you may very well need to have an Access Point **_and_** an Internet access (i.e. access to your local or wide area network).
For that, you need 2 WiFi adapters (yes, you could also use an Ethernet connection, which is a no brainer, we talk about WiFi here).
Recent Raspberry Pis are WiFi-enabled, you just need a WiFi dongle, that would fit on a USB port.
On older Raspberry Pis (not WiFi-enabled), you need 2 USB dongles.
The Raspberry Pi 3 and the Zero W already have one embedded WiFi port, I just added another one, the small USB WiFi dongle I used to use
on the other Raspberry Pis.
This one becomes named `wlan1`. All I had to do was to modify `/etc/network/interfaces`:
```
# interfaces(5) file used by ifup(8) and ifdown(8)
# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
iface eth0 inet manual
allow-hotplug wlan0
iface wlan0 inet static
address 192.168.42.1
netmask 255.255.255.0
#iface wlan0 inet manual
# wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface wlan1 inet dhcp
wpa-ssid "ATT856"
wpa-psk "<your network passphrase>"
```
See the 4 lines at the bottom of the file, that's it!
> Note: above, `192.168.42.1` will be the address of your hotspot, aka gateway. Feel free to change it to anything else, like `192.168.127.1`...
> If that was the case, you also need to make sure that the entry you've added in `/etc/dhcp/dhcpd.conf` matches this address range:
```
subnet 192.168.127.0 netmask 255.255.255.0 {
range 192.168.127.10 192.168.127.50;
option broadcast-address 192.168.127.255;
option routers 192.168.127.1;
default-lease-time: 600;
max-lease-time: 7200;
option domain-name "local-pi";
option domain-name-servers 8.8.8.8 8.8.4.4;
}
```
The lines to pay attention to are the ones with a `127` in it...
> Note: you might also want to modify the file `/etc/dhcpcd.conf`, add the following lines:
```
interface wlan0
static ip_address=192.168.127.1/24
# static ip6_address=fd51:42f8:caae:d92e::ff/64
static routers=192.168.127.1
static domain_name_servers=192.168.127.1
```
Now, when the `wlan1` is plugged in, this Raspberry Pi is a WiFi hotspot, *_and_* has Internet access.
This means that when you are on a Raspberry Pi with **two** WiFi adapters (the Raspberry Pi 3 with an extra dongle, where you do you developments from for example), you
have **two** WiFi interfaces, `wlan0` and `wlan1`.
When the same SD card runs on a Raspberry Pi with only **one** WiFi adapter (the Raspberry Pi Zero W you use to do some logging, when kayaking in the boonies for example),
you have only **one** WiFi interface `wlan0`, and the Raspberry Pi is a hotspot generating its own network, as defined by you in `/etc/hostapd/hostapd.conf`.
> Note: In some cases, I was not able to have `hostapd` to start at boot time... It was working fine from the command line though.
> I've cheated by putting an `hostapd /etc/hostapd/hostapd.conf &` in `/etc/rc.local`. It's not elegant, but it works.
Now you're ready to rock!
##### Bonus: Mount a USB drive on the Raspberry Pi
- <https://www.raspberrypi-spy.co.uk/2014/05/how-to-mount-a-usb-flash-disk-on-the-raspberry-pi/>
---
#### Java Virtual Machine (JVM)
_Note:_
Java code is compiled into `class` files, that run on a Java Virtual Machine (`JVM`). Java is not the only language that runs a `JVM`, this project also contains some small samples of
other JVM-aware languages, invoking and using the features of this project.
Those samples include Scala, Groovy, Kotlin..., and the list is not closed!
See in the [OtherJVMLanguages](https://github.com/OlivierLD/raspberry-coffee/tree/master/OtherJVMLanguages) directory, there is more about that.
---
#### How to build and run
_Note:_
This project uses `gradle` and `git`. `Gradle` will be installed automatically if it is not present on your system,
it uses the gradle wrapper (`gradlew`).
> To have a first idea of the structure of the project, use
```
$ ./gradlew projects [--info]
```
> Sub-projects may have dependencies.
```
$ cd Project-Trunk/REST-clients/REST-assembler
$ ../../../gradlew dependencies [--info]
```
`Git` is usually installed on Linux and Mac, but not on all versions of Windows. On Windows, you need to install the [`git bash shell`](http://lmgtfy.com/?q=install+git+bash+shell+on+windows), and run _in it_ the commands mentioned in this document.
Recent versions of Windows (like Windows 10) seem to come with a git command available in a Terminal. But this forward-slash/back-slash story
remains in your way, I have not tested it.
---
To build it, clone this project (this repo), make sure the script named `gradlew` is executable, and execute `gradlew`.
> _Note_: If you wish to access serial ports, a good library (beside PI4J) is `librxtx`:
> ```bash
> sudo apt-get install librxtx-java
> ```
```
Prompt> git clone https://github.com/OlivierLD/raspberry-coffee.git
Prompt> chmod +x gradlew # if needed
Prompt> ./gradlew [--daemon | --no-daemon] build [--info] -x test
```
> _Note_: On small-memory boards, use `--no-daemon`, like in:
> ```
> ./gradlew --no-daemon clean build --info
> ```
---
<!--
_Note_: We use git submodules, see https://www.vogella.com/tutorials/GitSubmodules/article.html
AstroComputer is a git submodule
Do a `git submodule update --init` from the root after a first clone.
```
From the root of the repo (raspberry-coffee)
$ git submodule add https://github.com/OlivierLD/AstroComputer.git
This creates an AstroComputer folder in raspberry-coffee
Add dependencies on the git submodule in settings.gradle (root of raspberry-coffee)
include(':AstroComputer')
Comment plug-in version in the build.gradle submodule:
plugins {
id 'java'
id 'scala'
id 'idea'
id 'maven'
id 'com.github.johnrengelman.shadow' // version '6.0.0'
id "application"
}
```
After pulling `raspberry-coffee` for the first time, do a `git clone https://github.com/OlivierLD/AstroComputer.git` (from the `raspberry-coffee` directory), and you should be good to go.
You can also do a `git submodule update --init`.
Then the submodule can be refreshed (pulled) like any other one.
---
-->
>If you see a message like `VM is only supported on ARMv7+ VFP`, you probably need to downgrade your JDK (and JRE)
> from 11 to 8.
You are expecting an end like that one:
```
BUILD SUCCESSFUL in 55s
97 actionable tasks: 17 executed, 80 up-to-date
Prompt>
```
See the `gradle` web-site for info about Gradle.
We will also be using the `shadowJar` gradle plugin is several projects.
This plugin is aggregating the required classes _and all their dependencies_ into a single archive, called a `fat Jar`. This simplifies the syntax of the `classpath`.
Typically, this operation will be run like this:
```
Prompt> cd RESTNavServer
Prompt> ../gradlew build --info
Prompt> ../gradlew clean shadowJar [--info]
```
The expected archive will be produced in the local `build/libs` directory.
> Note: On small machines (like Raspberry Pi Zero), you might want to exclude the Scala compilation (too demanding) on some modules:
> ```
> $ ../gradlew clean shadowJar -x :AstroComputer:compileScala
> ```
> _Important_ : If `JAVA_HOME` is not set at the system level, you can set it in `set.gradle.env` and execute it before running `gradlew`:
```
Prompt> ../set.gradle.env.sh
```
> _Note:_ If you are behind a firewall, you need a proxy. Mention it in all the files named <code>gradle.propetries</code>, and in <b>all</b> the <code>build.gradle</code> scripts, uncomment the following two lines:
```
// ant.setproxy(proxyhost: "$proxyHost", proxyport: "$proxyPort") //, proxyuser="user", proxypassword="password")
// compileJava.dependsOn(tellMeProxy)
```
Or you can also set it at runtime:
```
Prompt> ../gradlew clean shadowJar -Dhttp.proxyHost=www-proxy.domain.com -Dhttp.proxyPost=80 -Dhttps.proxyHost=www-proxy.domain.com -Dhttps.proxyPost=80
```
---
### Developing _on_ the Raspberry Pi, or Developing _for_ the Raspberry Pi ?
To write code, the simplest editor is enough. I have used `vi` for ages, mostly because this was the only one available, but also because it _**is**_ indeed good enough.
`vi` (and `vim`) is (are) available on the Raspberry Pi, `nano` too, graphical editors like `gedit`, `geany` are even easier to use, on a grahical desktop.
All the code provided here can be built from Gradle (all gradle scripts are provided), _**on the Raspberry Pi**_ itself.
The Raspberry Pi is self-sufficient, if this is all you have, nothing is preventing you from accessing **_all_** the features presented here.
But let us be honest, Integrated Development Environments (IDE) are quite cool.
In my opinion, IntelliJ leads the pack, and Eclipse, JDeveloper, NetBeans follow. Cloud9 provides amazing features, on-line.
Smaller ones like GreenFoot, BlueJ are also options to consider.
Those two last ones might be able to run on a Raspberry Pi, but forget about the others..., they use way too much RAM.
The features they provide definitely increase productivity, and when you use them, you learn as you code. Code-insight, auto-completion
and similar features are here to help. And I'm not even talking about the *remote debugging* features they provide as well.
Several IDEs are also providing remote development features, through SSH. That means that you run an IDE on a laptop, powerful enough, and the code you write
sits on the Raspberry Pi. This could also be _**very**_ appealing.
So, as the Raspberry Pi is not the only machine on my desk, I develop on a laptop using IntelliJ (with several GigaBytes of RAM, like 8, 16, ...), and I use `scp` to transfer the code to (and possibly from) the Raspberry Pi.
Worst case scenario, I do a `git push` from the development machine, and a `git pull` from the Raspberry Pi.
I found it actually faster and more efficient than developing directly on the Raspberry Pi.
##### Something to keep in mind
The Java Virtual Machine (JVM) implements the Java Platform Debugging Architecture (JPDA). This allows **_remote debugging_**.
In other words, you run the code on the Raspberry Pi,
but you debug it (set breakpoints, introspect variable values, etc) on another machine (the one where the IDE runs).
This is specially useful when the code interacts with sensors and other devices that are not supported from the laptop.
This will make your life considerably easier than if you used another language missing it (like Python, C, and many others).
It uses TCP between the debugger and the debuggee.
---
### Raspberry Pi, a possible thing of the Internet of Things...
* The Raspberry Pi is a _fully featured_ Linux computer, which can - as such - connect to the Internet.
* The Raspberry Pi has a General Purpose Input Output (GPIO) interface that allows it to drive all kind of electronic components, from a simple LED to a complex robot, and including all kind of sensors (GPS, light resistors, pressure sensors, temperature sensors, all kinds!).
None of the above is new. Connecting to the Internet does not impress anyone anymore. Driving a robot, modern kitchens are full of robots, cars are loaded with electronic components...
**But** what if we put those two together, with the Raspberry Pi sitting in between.
**Then**, we can drive a robot over the Internet. And **this** is not that usual (yet).
---
The snippets provided in this project are here to help in this kind of context. Some will use the network aspect of the story, some others will interact with electronic components. The two aspects should be easy to bridge, that is the goal. If that was not the case, please let me know (email address of the left side).
---
#### Project list, growing...
Several projects are featured here:
* Basic GPIO interaction
* Two Light Emitting Diodes (LEDs)
* Use the Raspberry Pi to turn LEDs on and off, **through email** ([with doc](http://www.lediouris.net/RaspberryPI/email/readme.html))
* Read Serial Port ([with doc](http://www.lediouris.net/RaspberryPI/serial/readme.html))
* Read _and parse_ NMEA Data from a GPS ([with doc](http://www.lediouris.net/RaspberryPI/GPS/readme.html))
* Read analog data with an Analog Digital Converter (ADC). ([with doc](http://www.lediouris.net/RaspberryPI/ADC/readme.html), with [node.js and WebSocket](http://www.lediouris.net/RaspberryPI/ADC/adc-websocket.html))
* Drive servos using the PCA9685. ([with doc](http://www.lediouris.net/RaspberryPI/servo/readme.html)).
* Drive servos using the PCA9685, **over the Internet**, with an Android client option. ([with doc](http://www.lediouris.net/RaspberryPI/servo/node.servo.html)).
* Use the LSM303. (I<sup>2</sup>C compass & accelerometer, [with doc](http://www.lediouris.net/RaspberryPI/LSM303/readme.html)).
* Use the BMP180. (I<sup>2</sup>C temperature and pressure sensor, [with doc](http://www.lediouris.net/RaspberryPI/BMP180/readme.html)).
* Use the BMP183. (SPI temperature and pressure sensor, [with doc](http://www.lediouris.net/RaspberryPI/BMP183/readme.html)).
* Use a relay, through email. ([with doc](http://www.lediouris.net/RaspberryPI/Relay.by.email/readme.html)).
* Use a relay, through HTTP. ([with doc](http://www.lediouris.net/RaspberryPI/Relay.by.http/readme.html)).
* Use a seven-segment display. ([with doc](http://www.lediouris.net/RaspberryPI/SevenSegment/readme.html)).
* Use the VCNL4000 (I<sup>2</sup>C proximity sensor).
* Use the TCS34725 (I<sup>2</sup>C color sensor, [demo](http://www.lediouris.net/RaspberryPI/TCS34725/readme.html)).
* Use the TSL2561 (I<sup>2</sup>C light sensor).
* Use the L3GD20 (I<sup>2</sup>C gyroscope, [demo](http://www.lediouris.net/RaspberryPI/L3GD20/readme.html)).
* Use the MCP4725 (I<sup>2</sup>C Digital to Analog Converter, [demo](http://www.lediouris.net/RaspberryPI/DAC/readme.html)).
* ... and more.
---
All the doc - with more details than here - can be reached from [this page](http://raspberrypi.lediouris.net/).
## A Maven repo in GitHub
Yes, this is possible!
See [this](https://github.com/OlivierLD/raspberry-coffee/tree/repository).
## Why Java, why not something else?
Tricky question... Thanks for scrolling down that far.
The languages you use depend a lot on what you expect from your computer.
If you live on the hardware/sensors side of the world, you might prefer Python, as it is a simple language, close to scripting.
The programs you will write will not be bigger than a couple of thousand lines.
If you are a mathematician, developing AI models, again Python might be your friend, it is well structured (I know, it's not 100% true... Ping me for details),
and close enough to your mind set. You don't need to learn what will give extra value to - say - the JVM languages.
Now, if you need _to scale_, if you need to run on small single board computers as well as on clouds of big machines,
then this is where JVM-based languages come on stage.
They also provide some remote-debugging features, you only have to see them once to love them.
Their consistency is also an asset, and you do not have to wait for the runtime to detect problems and errors (IDEs have made tremendous progresses in this area,
leveraging the potential of the JVM). Their structure allows you to write multi-million line programs (`C` does it too, by the way).
#### This being said...
This being said, choosing your favorite language does not necessary isolate you from the rest of the world.
All languages - or almost - understand HTTP and related technologies like REST (if yours does not, drop it).
Docker and similar technologies provide this _container_ abstraction.
Nothing is preventing you from using as many languages, frameworks and techniques you want, all you need is to
package your applications as HTTP/REST servers that can communicate with each others.
Bundling those servers into Docker images gives you even more flexibility.
It is very easy to invoke Python from Java (JSR 223), but the overhead of invoking it as a script is not negligible,
and there is no in-memory status or transient state, in this case.
HTTP/REST sounds much nicer. We **will** provide examples, Java pinging a Python server, and vice-versa.
> For now: there is a skeleton/template for a Python HTTP REST Server in
> `http-tiny-server/src/main/python/http_server_skeleton.py`
Same works also for Scala (JVM based language), NodeJS, ... whatever understands HTTP.
It does indeed open **_a lot_** of possibilities.
The common protocol is REST over HTTP (JSON - or XML - is also nice to have, to format the conveyed data).
Then it becomes what latin was in Europe in the middle-age: a _common communication media_.
> Latin is not the only example of communication between people speaking different languages. The same must have happened in Arabic, Asian, and more communities, please don't get me wrong.
> And if you do not know it yet, take a listen to what people speak in places like California: 95% of the people have an accent!
I like Java and related technologies.
You're welcome here, even if you don't!
---
| 0 |
mechero/spring-boot-testing-strategies | Sample project demonstrating different Test Strategies that can be followed when using Spring Boot. | junit spring spring-boot springboottest | null | 1 |
qianxiaoai/RuntimePermissionsDemo | A runtime permission demo based on Google RuntimePermissions Sample | null | # RuntimePermissionsDemo
A runtime permission demo based on Google RuntimePermissions Sample。
谷歌权限demo地址 :
https://github.com/googlesamples/android-RuntimePermissions
* 因为工作需要,简单研究了一下Android6.0,动态权限申请,基于Google提供的demo,写了一个简单的demo。
* [原文地址:http://www.jianshu.com/p/a51593817825](http://www.jianshu.com/p/a51593817825)
## 权限申请步骤
* 1 将targetSdkVersion 设置为23,注意,如果你讲targetSdkVersion设置为>=23,则必须Android谷歌的要求,动态的申请权限,如果你暂时不打算支持动态权限申请,则targetSdkVersion最大设置为22.
* 2 在AndroidManifest.xml中申请你需要的权限,包括普通权限和需要申请的特殊权限。
* 3 开始申请权限,此处分为3部。
(1)检查是否由此权限checkSelfPermission(),如果已经开启,则直接做你想做的。
(2)如果未开启,则判断是否需要向用户解释为何申请权限shouldShowRequestPermissionRationale。
(3)如果需要(即返回true),则可以弹出对话框提示用户申请权限原因,用户确认后申请权限requestPermissions(),如果不需要(即返回false),则直接申请权限requestPermissions()。
(这里是一部门代码,底部有比较完善的代码,整个demo可以在github中下载)。
* 备注:
(1)checkSelfPermission:检查是否拥有这个权限
(2)requestPermissions:请求权限,一般会弹出一个系统对话框,询问用户是否开启这个权限。
(3)shouldShowRequestPermissionRationale:Android原生系统中,如果第二次弹出权限申请的对话框,会出现“以后不再弹出”的提示框,如果用户勾选了,你再申请权限,则shouldShowRequestPermissionRationale返回true,意思是说要给用户一个 解释,告诉用户为什么要这个权限。然而,在实际开发中,需要注意的是,很多手机对原生系统做了修改,比如小米,小米4的6.0的shouldShowRequestPermissionRationale 就一直返回false,而且在申请权限时,如果用户选择了拒绝,则不会再弹出对话框了。。。。 所以说这个地方有坑,我的解决方法是,在回调里面处理,如果用户拒绝了这个权限,则打开本应用信息界面,由用户自己手动开启这个权限。
![单个权限申请.png](http://upload-images.jianshu.io/upload_images/1975505-8797c58a6bc35b84.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
(4)每个应用都有自己的权限管理界面,里面有本应用申请的权限以及各种状态,即使用户已经同意了你申请的权限,他也随时可以关闭
![权限管理界面.png](http://upload-images.jianshu.io/upload_images/1975505-c8bc0d8e5c95cead.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
/**
* Requests permission.
*
* @param activity
* @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA
*/
public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {
if (activity == null) {
return;
}
Log.i(TAG, "requestPermission requestCode:" + requestCode);
if (requestCode < 0 || requestCode >= requestPermissions.length) {
Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
return;
}
final String requestPermission = requestPermissions[requestCode];
//如果是6.0以下的手机,ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED,
// 但是,如果用户关闭了你申请的权限(如下图,在安装的时候,将一些权限关闭了),ActivityCompat.checkSelfPermission()则可能会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null),
// 你可以使用try{}catch(){},处理异常,也可以判断系统版本,低于23就不申请权限,直接做你想做的。permissionGrant.onPermissionGranted(requestCode);
// if (Build.VERSION.SDK_INT < 23) {
// permissionGrant.onPermissionGranted(requestCode);
// return;
// }
int checkSelfPermission;
try {
checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
} catch (RuntimeException e) {
Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT)
.show();
Log.e(TAG, "RuntimeException:" + e.getMessage());
return;
}
if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");
shouldShowRationale(activity, requestCode, requestPermission);
} else {
Log.d(TAG, "requestCameraPermission else");
ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
}
} else {
Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");
Toast.makeText(activity, "opened:" + requestPermissions[requestCode], Toast.LENGTH_SHORT).show();
permissionGrant.onPermissionGranted(requestCode);
}
}
![6.0以下系统的应用程序安装界面.png](http://upload-images.jianshu.io/upload_images/1975505-ec1877b089a98891.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
## 一次申请多个权限
其实和申请一个权限是一样的,只是requestPermissions(final @NonNull Activity activity,
final @NonNull String[] permissions, final int requestCode),里面的permissions给的参数多些而已。
![申请多个权限.png](http://upload-images.jianshu.io/upload_images/1975505-010c521fdfc20714.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
/**
* 一次申请多个权限
*/
public static void requestMultiPermissions(final Activity activity, PermissionGrant grant) {
final List<String> permissionsList = getNoGrantedPermission(activity, false);
final List<String> shouldRationalePermissionsList = getNoGrantedPermission(activity, true);
//TODO checkSelfPermission
if (permissionsList == null || shouldRationalePermissionsList == null) {
return;
}
Log.d(TAG, "requestMultiPermissions permissionsList:" + permissionsList.size() + ",shouldRationalePermissionsList:" + shouldRationalePermissionsList.size());
if (permissionsList.size() > 0) {
ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]),
CODE_MULTI_PERMISSION);
Log.d(TAG, "showMessageOKCancel requestPermissions");
} else if (shouldRationalePermissionsList.size() > 0) {
showMessageOKCancel(activity, "should open those permission",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
CODE_MULTI_PERMISSION);
Log.d(TAG, "showMessageOKCancel requestPermissions");
}
});
} else {
grant.onPermissionGranted(CODE_MULTI_PERMISSION);
}
}
* 关于权限请求结果的回调。Activity实现ActivityCompat.OnRequestPermissionsResultCallback接口,重写onRequestPermissionsResult方法。
@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
}
| 1 |
christophstrobl/spring-data-solr-showcase | Sample Spring MVC Application demonstrating usage of Spring Data Solr. | null | Spring Data Solr Showcase
=========================
This example shows basic usage concepts of [Spring Data Solr](http://projects.spring.io/spring-data-solr).
The commit order from initial to latest guides you through:
1. STEP 1: Initial setup and configuration.
2. STEP 2: Custom `Repository` implementation for autocomplete.
3. STEP 3: `@Facet` annotation as alternative to custom implementation.
4. STEP 4: Highlighting of search terms in result.
5. STEP 5: Type mapping for custom types.
6. STEP 6: Use multicore support to enable automatic template configuration.
In order to run this example a 4+ [Solr Server](http://lucene.apache.org/solr/downloads.html) and [Maven](http://maven.apache.org/download.cgi) are required.
The application is meant to work with the example data provided by the Solr distribution.
### Running Solr
```emacs
:solr> cd example
:example> java -jar start.jar
:example> cd exampledocs
:exampledocs> java -jar post.jar *.xml
```
Access via [localhost:8983/solr/](http://localhost:8983/solr/#/collection1)
### Running Showcase
```emacs
:spring-data-solr-showcase> mvn spring-boot:run
```
Access via [localhost:8080/search](http://localhost:8080/search) | 1 |
zixpo/candybar-sample | Sample Implementation of CandyBar Dashboard. | null | # CandyBar Sample
[![JitPack Version](https://jitpack.io/v/zixpo/candybar.svg)](https://jitpack.io/#zixpo/candybar)
[![Build Status](https://img.shields.io/github/actions/workflow/status/zixpo/candybar-sample/android.yml?branch=main)](https://github.com/zixpo/candybar-sample/actions/workflows/android.yml)
Sample Implementation of CandyBar Dashboard.
Read the [Wiki](https://github.com/zixpo/candybar-sample/wiki) to get Started.
# License
```
Copyright (c) 2014-2016 Dani Mahardhika
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
| 1 |
sdeleuze/spring-jackson-demo | Sample Spring + Jackson application | null | This application shows various Spring Jackson integration features.
Run the Application.main() with a Java 8 runtime to start the embedded Tomcat on port 8080.
Some URL to try:
* Get one message (JSON): http://localhost:8080/1.json
* Get one message (JSONP) : http://localhost:8080/1.json?jsonp=parseResponse
* Get all messages with Json View (JSON): http://localhost:8080/.json
* Get one Message (XML): http://localhost:8080/1.xml
* Get all messages with Json View (XML): http://localhost:8080/.xml
| 1 |
forcedotcom/pub-sub-api | Sample project to get started with the Pub/Sub API | grpc pubsub salesforce | # Getting Started with the Pub/Sub API
- [About Pub/Sub API](#about-pubsub-api)
- [gRPC](#grpc)
- [Documentation and Blog Posts](#documentation-and-blog-post)
- [Code Samples](#code-samples-from-salesforce)
## About Pub/Sub API
Welcome to Pub/Sub API! Pub/Sub API provides a single interface for publishing and subscribing to platform events, including real-time event monitoring events, and change data capture events. Based on [gRPC](https://grpc.io/docs/what-is-grpc/introduction/) and HTTP/2, Pub/Sub API enables efficient delivery of binary event messages in the Apache Avro format.
This repo contains the critical [proto
file](https://github.com/developerforce/pub-sub-api/blob/main/pubsub_api.proto) that you will need to use the API.
## gRPC
gRPC [officially supports 11 languages](https://grpc.io/docs/languages/), but
there is unofficial community support in more. To encode and decode events, an
Avro library for your language of choice will be needed. See below for which
officially supported languages have well-supported Avro libraries:
|Supported gRPC Language|Avro Libraries|
|-----------------------|--------------|
|C# | [AvroConvert](https://github.com/AdrianStrugala/AvroConvert)<br />[Apache Avro C#](https://avro.apache.org/docs/current/api/csharp/html/index.html) (docs are not great)|
|C++|[Apache Avro C++](https://avro.apache.org/docs/current/api/cpp/html/index.html)|
|Dart|[avro-dart](https://github.com/sqs/avro-dart) (last updated 2012)|
|Go|[goavro](https://github.com/linkedin/goavro)|
|Java|[Apache Avro Java](https://avro.apache.org/docs/current/getting-started-java/)|
|Kotlin|[avro4k](https://github.com/avro-kotlin/avro4k)|
|Node|[avro-js](https://www.npmjs.com/package/avro-js)|
|Objective C|[ObjectiveAvro](https://github.com/jlawton/ObjectiveAvro) (but read [this](https://stackoverflow.com/questions/57216446/data-serialisation-in-objective-c-avro-alternative))|
|PHP|[avro-php](https://github.com/wikimedia/avro-php)|
|Python|[Apache Avro Python](https://avro.apache.org/docs/current/getting-started-python/)|
|Ruby|[AvroTurf](https://github.com/dasch/avro_turf)|
## Documentation, Blog Post and Videos
- [Pub/Sub API Developer Guide](https://developer.salesforce.com/docs/platform/pub-sub-api/overview)
- [Salesforce Architects Blog Post](https://medium.com/salesforce-architects/announcing-pub-sub-api-generally-available-3980c9eaf0b7)
- [Introducing the New gRPC-based Pub Sub API YouTube Developer Quick Takes](https://youtu.be/g9P87_loVVA)
## Code Samples from Salesforce
Salesforce provides these samples for demonstration purposes. They aren't meant to be used in production code. Before you use these samples in production, make sure you perform thorough functional and performance testing.
- [Java Quick Start in the Developer Guide](https://developer.salesforce.com/docs/platform/pub-sub-api/guide/qs-java-quick-start.html)
- [Python Quick Start in the Developer Guide](https://developer.salesforce.com/docs/platform/pub-sub-api/guide/qs-python-quick-start.html)
- [Python Code Examples](python/)
- [Go Code Examples](go/)
- [Java Code Examples](java/)
## Code Samples from the Developer Community
These examples are developed by the community. They aren't supported by Salesforce. Use at your own discretion.
- [E-Bikes Sample Application](https://github.com/trailheadapps/ebikes-lwc)
- [Pub/Sub API Node Client](https://github.com/pozil/pub-sub-api-node-client)
- [.NET Code Examples](https://github.com/Meyce/pub-sub-api/tree/main/.Net)
If you have a code sample for Pub/Sub API that you would like to add a link to in this section, submit a PR with the modified readme page. We don't guarantee that we can link to all samples. Priority will be given to samples implemented in a programming language that is not represented in this repository's samples. | 1 |
hantsy/angularjs-springmvc-sample | A RESTful sample using AnguarJS/Bootstrap as frontend and Spring MVC as REST API producer | angularjs bootstrap hibernate spring-boot spring-data-jpa spring-mvc | angularjs-springmvc-sample
==========================
An example application using AngularJS/Bootstrap as frontend and Spring MVC as REST API producer.
**More details about the codes, please read the online GitBook: [Building REST APIs with Spring MVC](https://www.gitbook.com/book/hantsy/build-a-restful-app-with-spring-mvc-and-angularjs/details/).**
> NOTE: This project is under maintainance, no more new features added in future. If you are looking for the new Spring Boot 2 and Angular 5, check [angular-spring-reactive-sample](https://github.com/hantsy/angular-spring-reactive-sample).
[![Build Status](https://drone.io/github.com/hantsy/angularjs-springmvc-sample/status.png)](https://drone.io/github.com/hantsy/angularjs-springmvc-sample/latest)
## Contribution
_I appreciate any contribution for this project, including suggestions, documentation improvements, reporting issues, forks and bugfixs, etc. I have found there are some unrelated issues added, before you file an issue, please **READ THE STEPS IN THIS README.md** carefully_.
**在你提交 ISSUE 前,请务必确认已经严格完成了本文中描述的操作步骤**。
Thank the DevFactory team member [@misgersameer](https://github.com/misgersameer) for sending several PRs to improve the code quaulity according to the sonar rules.
## Requirements
* JDK 8
Oracle Java 8 is required, go to [Oracle Java website](http://java.oracle.com) to download it and install into your system.
Optionally, you can set **JAVA\_HOME** environment variable and add *<JDK installation dir>/bin* in your **PATH** environment variable.
* Apache Maven
Download the latest Apache Maven from [http://maven.apache.org](http://maven.apache.org), and uncompress it into your local system.
Optionally, you can set **M2\_HOME** environment varible, and also do not forget to append *<Maven Installation dir>/bin* your **PATH** environment variable.
## Run this project
1. Clone the codes.
```
git clone https://github.com/hantsy/angularjs-springmvc-sample
```
2. And enter the root folder, run `mvn tomcat7:run` to start up an embedded tomcat7 to serve this application.
```
mvn tomcat7:run
```
3. Go to [http://localhost:8080/angularjs-springmvc-sample/](http://localhost:8080/angularjs-springmvc-sample/) to test it. If you want to explore the REST API docs online, there is a *Swagger UI* configured for visualizing the REST APIs, just go to [http://localhost:8080/angularjs-springmvc-sample/swagger-ui.html](http://localhost:8080/angularjs-springmvc-sample/swagger-ui.html).
## Spring Boot
If you are interested in Spring Boot, I have moved the `boot` branch into a new project [angularjs-springmvc-sample-boot](https://github.com/hantsy/angularjs-springmvc-sample-boot).
| 1 |
VenomVendor/RecyclerView | Sample for using RecyclerView instead of ListView | null | # RecyclerView Demo
Demo for using [RecylcerView][1] instead of ListView.
##Prerequisites
- [android-support-v4.jar](#)
- [lib-recyclerview.jar][3]
## Usage
<pre>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</pre>
## Details
Visit [this post][2], for more details.
###### Author : [VenomVendor](https://www.google.com/#newwindow=1&q=VenomVendor "Find me on Google")
#License
Copyright (C) 2014 VenomVendor <info@VenomVendor.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
[1]: https://developer.android.com/preview/material/ui-widgets.html#recyclerview "RecyclerView"
[2]: http://venomvendor.blogspot.in/2014/07/creating-animated-horizontal-vertical-recyclerview.html "Creating Animated, Horizontal, Vertical ListView using Recycler View."
[3]: https://github.com/VenomVendor/RecyclerView/tree/master/library/bin/
| 1 |
SelfZhangTQ/T-MVVM | This repository contains a detailed sample app that implements MVVM architecture using LiveData,ViewModel,Retrofit,Rxjava | livedata mvvm rxjava viewmodel | ## T-MVVM 努力打造简单实用的开发框架
## 艺术帮是一款艺术图片应用,采用LiveData+ViewModel+RxJava+okHttp+Retrofit+Glide架构的项目,仅用于学习交流,不断完善中<br/>
项目github地址:<https://github.com/SelfZhangTQ/T-MVVM> <br/>
[apk下载地址](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/app.apk)
#### T-MVVM 2.0版本更新说明<br/>
* 基于LiveBus事件除去ViewModel和Repository接口耦合。
#### 项目初衷 在此之前一直使用MVP,MVP缺点:<br/>
* Presenter中除了逻辑以外,还有大量的View->Model,Model->View的逻辑操作,造成Presenter臃肿,维护困难。<br/>
* 对UI的渲染放在了Presenter中,所以UI和Presenter的交互会过于频繁。<br/>
* Presenter过多地渲染了UI,往往会使得它与特定的UI的交互频繁。一旦UI变动,Presenter也需要变<br/>
* 接口暴增,可以说代码量成倍增长,让人无法忍受,<br/>
#### MVVM的出现提高可维护性。解决了MVP大量的手动View和Model同步的问题,但并非救世主。没有最好的框架,只有最适合自己的,
#### 此项目未使用:DataBinding原由<br/>
* 数据绑定增加Bug调试难度。<br/>
* 复杂的页面,model也会很大,虽然使用方便了也很容易保证了数据的一致性,当时长期持有,不利于释放内存。<br/>
* 数据双向绑定不利于View重用。<br/>
#### 工程代码说明<br/>
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/mvvm3.png)
## 无图无真相<br/>
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/1_video.gif)
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/2_video.gif)<br/>
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/3_video.gif)
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/4_video.gif)<br/>
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/5_video.gif)
![image](https://github.com/SelfZhangTQ/T-MVVM/raw/master/screenshots/6_video.gif)<br/>
基于ViewModel,LiveData,Retrofit,Rxjava实现T-MVVM体系结构的架构,泛型限定,深度解耦。
ViewModel优点:
* 同步关联生命周期,
* 数据共享 ,
* 复用性强 ,
LiveData优点:
* 确保UI界面的数据状态,
* 没有内存泄漏,不会因为Activity的不可见导致Crash,
* 不用再人为的处理生命周期,
* 共享资源,
此架构未使用DataBinding原由:
* 数据绑定增加Bug调试难度,
* 复杂的页面,model也会很大,虽然使用方便了也很容易保证了数据的一致性,当时长期持有,不利于释放内存,
* 数据双向绑定不利于View重用,
###T-MVVM架构分层代码
1:先定义BaseViewModel基类
/**
* @author:tqzhang on 18/7/26 16:15
*/
public class BaseViewModel<T extends BaseRepository> extends AndroidViewModel {
public T mRepository;
public BaseViewModel(@NonNull Application application) {
super(application);
mRepository = TUtil.getNewInstance(this, 0);
}
@Override
protected void onCleared() {
super.onCleared();
if (mRepository != null) {
mRepository.unSubscribe();
}
}
}
BaseViewModel通过泛型类型参数BaseRepository子类初始化Repository数据仓库,同时在activity/fragment走onDestroy()生命周期方法时 BaseViewModel回调onCleared,即页面销毁是用来取消网络请求或资源释放等操作。
正常开发一般不建议直接通过ViewModel获取网络数据,这里我们将工作交给一个新的模块Repository。Repository只负责数据处理,提供干净的api,方便切换数据来源。
2:再定义BaseRepository
public abstract class BaseRepository {
protected ApiService apiService;
public BaseRepository() {
if (null == apiService) {
apiService = HttpHelper.getInstance().create(ApiService.class);
}
}
private CompositeSubscription mCompositeSubscription;
protected void addSubscribe(Subscription subscription) {
if (mCompositeSubscription == null) {
mCompositeSubscription = new CompositeSubscription();
}
mCompositeSubscription.add(subscription);
}
public void unSubscribe() {
if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
mCompositeSubscription.clear();
}
}
BaseRepository中内容相对简单,主要是获取ApiService和网络请求订阅容器,方便管理网络请求。
3:然后自定义AbsLifecycleFragment基类继承BaseFragment,BaseFragment可自行编写。如不需要使用T-MVVM,可自行继承BaseFragment,互不影响。
public abstract class AbsLifecycleFragment<T extends BaseViewModel> extends BaseFragment {
protected T mViewModel;
/**
* init view
* @param state
*/
@Override
public void initView(Bundle state) {
mViewModel = VMProviders(this, TUtil.getInstance(this, 0));
if (null != mViewModel) {
dataObserver();
}
}
/**
* create ViewModelProviders
*
* @return ViewModel
*/
protected <T extends ViewModel> T VMProviders(BaseFragment fragment, @NonNull Class<T> modelClass) {
return ViewModelProviders.of(fragment).get(modelClass);
}
protected void dataObserver() {
}
/**
* 获取网络数据
*/
protected void getRemoteData() {
}
}
在initView方法中通过BaseViewModel子类泛型类型参数获取Class<T>,在通过ViewModelProviders.of(fragment).get(modelClass))实例化ViewModel,
到此我们的基类基本编写完毕。
4:下面我们以一个简单业务实战下,获取文章列表。
4-1:ArticleFragment
/**
* @author:tqzhang on 18/7/2 14:40
*/
public class ArticleFragment extends AbsLifecycleFragment<ArticleViewModel> {
protected TRecyclerView mRecyclerView;
protected StaggeredGridLayoutManager layoutManager;
protected DelegateAdapter adapter;
public static ArticleFragment newInstance() {
return new ArticleFragment();
}
@Override
public int getLayoutResId() {
return R.layout.fragment_list;
}
@Override
public void initView(Bundle state) {
super.initView(state);
layoutManager=new new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
//获取网络数据
getRemoteData();
}
//初始化adapter
public void initAdapter(){
adapter= new DelegateAdapter.Builder<>()
.bindArray(ArticleInfoVo.class, new ArticleRem1ItemHolder(context)
, new ArticleRem2ItemHolder(context)
, new ArticleRem3ItemHolder(context))
.bind(HeaderVo.class, new HeaderViewHolder(context, rogressStyle.Pacman))
.bind(FootVo.class, new FootViewHolder(context, ProgressStyle.Pacman))
.build();
//数据观察
@Override
protected void dataObserver() {
mViewModel.getArticleList().observe(this, articleVo -> {
if (null != articleVo) {
mRecyclerView.refreshComplete(articleVo.data.list, false);
}
});
}
//获取网络数据
@Override
protected void getRemoteData() {
mViewModel.getArticleList(typeId, lastId);
}
}
我们可以看出来ArticleFragment中只有UI初始化,发请网络请求action以及数据观察,列表展示用了[TRecyclerView,欢迎star哦](https://github.com/SelfZhangTQ/TRecyclerView)面向holder开发高复用,多类型的刷新库,从此只关心你的列表的Item展示。
通过泛型除去了MVP中通过接口传递信息的大量代码,
从此see you Mass implementation of interfaces。
4-1:ArticleViewModel
/**
* @author:tqzhang on 18/7/26 16:15
*/
public class ArticleViewModel extends BaseViewModel<ArticleRepository> {
private MutableLiveData<ArticleVo> mArticleData;
public ArticleViewModel(@NonNull Application application) {
super(application);
}
public LiveData<ArticleVo> getArticleList() {
if (mArticleData == null) {
mArticleData = new MutableLiveData<>();
}
return mArticleData;
}
public void getArticleList(String lectureLevel1, String lastId) {
mRepository.loadArticleRemList(new CallBack<ArticleVo>() {
@Override
public void onNext(ArticleVo articleObject) {
mArticleData.postValue(articleObject);
}
@Override
public void onError(String e) {
} }
});
}
ArticleViewModel中持有数据观察容器LiveData和真正发起网络请求动作,在接收到服务端返回的数据通过
mArticleData.postValue(articleObject);通知Observer数据的更改,此处需注意的是,setValue方法只能在主线程中调用,postValue可以在任何线程中调用,如果是在后台子线程中更新LiveData的值,必须调用postValue。
4-3:ArticleRepository
/**
* @author:tqzhang on 18/7/28 13:00
*/
public class ArticleRepository extends BaseRepository {
public void loadArticleRemList(final CallBack<ArticleVo> listener) {
addSubscribe(apiService.getArticleRemList()
.compose(RxSchedulers.io_main())
.subscribe(new RxSubscriber<ArticleVo>() {
@Override
public void onSuccess(ArticleVo articleObject) {
listener.onNext(articleObject);
}
@Override
public void onFailure(String msg) {
listener.onError(msg);
}
}));
}
最后我们的ArticleRepository中就提供数据,此处只提供了网络层的数据,在实际应用中可拆分类loacl data和remote data,可根据项目需求自行处理。
## 第三方库 <br/>
* okHttp <br/>
* Retrofit <br/>
* RxJava <br/>
* LiveData <br/>
* ViewModel <br/>
* ButterKnife <br/>
* Glide <br/>
* Gson <br/>
* BottomNavigationBar(轻量级底部导航栏)<br/>
* [LoadState](https://github.com/SelfZhangTQ/LoadState) (统一管理错误页面库)<br/>
* gsyVideoPlayer(视频播放)<br/>
* [TRecyclerView](https://github.com/SelfZhangTQ/TRecyclerView) (面向ViewHolder开发的刷新库,多类型item终结者,好不好用你试试就知道) <br/>
* ... <br/>
## 声明 <br/>
这个属于个人开发作品,仅做学习交流使用。诸位勿传播于非技术人员,拒绝用于商业用途,数据均属于非正常渠道获取。
| 1 |
bmuschko/testcontainers-integration-testing | The exercises and samples for the training Integration Testing with Docker and Testcontainers"." | null | # Integration Testing with Docker and Testcontainers
The process of developing an application typically involves the work of multiple engineers, and that work is usually broken down into several modules. There is always a risk that modules developed by different engineers will not sync when integrating with each other for use in production. Integration testing helps minimize this risk by enabling better integration of modules. But many organizations struggle with maintaining tests that require more complex setup procedures. As a result, integration tests become flaky and unreliable and require manual intervention. In an automate-all-the-things world, this costs organizations time and money.
Join expert Benjamin Muschko to discover how to set up and run integration and functional tests with the help of the open source library Testcontainers. You will learn how to stand up lightweight, disposable Docker instances running your application as reliable test fixtures.
## Prerequisites
Please make sure to follow the [instructions](./prerequisites/instructions.md) for setting up your environment before joining the training.
## Exercises
All [exercises](./exercises) are numbered and live in dedicated directories starting with the name `exercise-`. You'll find instructions for each exercise in each folder. Solutions are available in the `solution` folder. Try to solve each exercise yourself before having a look at the solution.
| 0 |
amitrp/spring-examples | Contains Spring and Spring Boot Code Samples used in https://www.amitph.com/ tutorials | hibernate jpa-hibernate spring spring-boot spring-data-jdbc spring-data-jpa spring-data-rest spring-mvc | # Spring Tutorials and Examples
Examples of using Spring Framework and Spring Boot
These examples are part of Spring & Spring Boot Tutorials on https://www.amitph.com/
## List of few relevant tutorials
- [Spring Data REST CRUD Example](https://www.amitph.com/spring-data-rest-example/)
- [Spring Data REST Projections and Excerpts](https://www.amitph.com/spring-data-rest-projections-and-excerpts/)
- [Spring Data JDBC Tutorial with Examples](https://www.amitph.com/introduction-spring-data-jdbc/)
- [Unit Tests for Spring Data JDBC Repositories](https://www.amitph.com/testing-spring-data-jdbc/)
- [How to Write a non-web Application with Spring Boot](https://www.amitph.com/non-web-application-spring-boot/)
- [CRUD REST Service With Spring Boot, Hibernate, and JPA](https://www.amitph.com/spring-boot-crud-hibernate-jpa/)
- [Understand Http PUT vs PATCH with Examples](https://www.amitph.com/http-put-vs-patch/)
- [Enable Spring Boot ApplicationStartup Metrics to Diagnose Slow Startup](https://www.amitph.com/spring-boot-startup-monitoring/)
- [Scheduled Tasks in Spring with @Scheduled](https://www.amitph.com/scheduled-tasks-in-spring/)
- [Spring Data JPA Composite Key with @EmbeddedId](https://www.amitph.com/spring-data-jpa-embeddedid/)
- [Spring Data JPA find by @EmbeddedId Partially](https://www.amitph.com/spring-data-jpa-find-by-embeddedid-partially/)
- [Spring Boot Actuator with Spring Boot 2](https://www.amitph.com/spring-boot-actuator-spring-boot-2/)
- [Custom Health Check in Spring Boot Actuator](https://www.amitph.com/custom-health-check-spring-boot-actuator/)
- [Introduction to Spring Boot Admin Server with Example](https://www.amitph.com/spring-boot-admin-server/)
- [How to Secure Spring Boot Actuator Endpoints](https://www.amitph.com/how-to-secure-spring-boot-actuator-endpoints/)
- [Spring Boot Admin Server Example](https://www.amitph.com/spring-boot-admin-server/)
- [Spring Data and JPA Tutorial](https://www.amitph.com/spring-data-and-jpa-tutorial/)
- [Wildcard Queries with Spring Data JPA](https://www.amitph.com/spring-data-and-jpa-tutorial/)
- [Spring Boot Runners – Application Runner and Command Line Runner](https://www.amitph.com/spring-boot-runners/)
- [Spring Boot Rest Service](https://www.amitph.com/spring-boot-rest-service/)
- [Downloading Large Files using Spring WebClient](https://www.amitph.com/spring-webclient-large-file-download/)
- [Spring @RequestParam Annotation with Examples](https://www.amitph.com/spring-requestparam-annotation/)
- [Introduction to Spring WebClient](https://www.amitph.com/introduction-to-spring-webclient/)
- [Configure timeout for Spring WebFlux WebClient](https://www.amitph.com/spring-webflux-timeouts/)
- [How to Read JSON Data with WebClient](https://www.amitph.com/spring-webclient-read-json-data/)
- [Add URI Parameters to Spring WebClient Requests](https://www.amitph.com/spring-webclient-request-parameters/)
- [Spring Boot - Spring Data JPA - MySQL Example](https://www.amitph.com/spring-boot-data-jpa-mysql/)
- [Spring Boot - Spring Data JPA - Postgres Example](https://www.amitph.com/spring-boot-data-jpa-postgres/)
- [Spring Boot Exit Codes Examples with Exception Mapping](https://www.amitph.com/spring-boot-exit-codes/)
- [Using @ConfigurationProperties in Spring Boot](https://www.amitph.com/spring-boot-configuration-properties/)
- [Reading Nested Properties in Spring Boot](https://www.amitph.com/spring-boot-nested-configuration-properties/)
- [Reading HTTP Headers in Spring REST Controller](https://www.amitph.com/spring-rest-http-header/)
- [YAML to Map with Spring Boot](https://www.amitph.com/spring-boot-yaml-to-map/)
- [YAML to Java List of Objects in Spring Boot](https://www.amitph.com/spring-boot-yaml-to-list/)
- [Validations with @ConfigurationProperties in Spring Boot](https://www.amitph.com/spring-boot-configuration-properties-validation/)
- [Parallel Requests with Spring WebClient](https://www.amitph.com/spring-webclient-concurrent-calls/)
- [Custom Banners with Spring Boot](https://www.amitph.com/spring-boot-custom-banner/)
| 0 |
gujc71/board_sample | Spring 4 + MyBatis 3 + MariaDB : board sample | null | null | 1 |
odrotbohm/repositories-deepdive | Sample code for the Spring Data JPA repositories deep dive talk | null | null | 1 |
mohanmanu484/RibbonView | Ribbon view sample | null | # RibbonView
Ribbon view sample
# Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url "https://jitpack.io" }
}
}
# Step 2. Add the dependency
dependencies {
compile 'com.github.mohanmanu484:RibbonView:1.2''
}
![alt text](https://github.com/mohanmanu484/RibbonView/blob/master/screenshots/sc1.png?raw=true "ScreenShot 1")
![alt text](https://github.com/mohanmanu484/RibbonView/blob/master/screenshots/sc3.png?raw=true "ScreenShot 2")
| 1 |
aws-samples/aws-sdk-js-tests | Code Sample for testing AWS SDK for JavaScript | aws aws-sdk-js browser javascript nodejs react-native sdk typescript | # aws-sdk-js-tests
Code Samples for testing AWS SDK for JavaScript.
## Steps to test:
- Fork this repo, and clone your fork.
- Create a local branch in your workspace.
- Update the code for testing AWS SDK for JavaScript.
- The SDK clients are created and API calls are made in [`packages/utils/src/utils.js`](./packages/utils/src/utils.js).
- Push code to remote branch on your fork, and share the code for reproducing the issue.
## Pre-requisites
- Update REGION in [`packages/utils/src/config.js`](./packages/utils/src/config.js).
- For browser and react-native, IDENTITY_POOL_ID also needs to be updated.
- [Create a Amazon Cognito Identity pool for testing](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-browser.html#getting-started-browser-create-identity-pool)
- Note down IDENTITY_POOL_ID
- [Add a Policy to the test Unauthenticated IAM Role](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/getting-started-browser.html#getting-started-browser-iam-role)
- The policy should be specific to the operations you want to test
- Update the IDENTITY_POOL_ID in [`packages/utils/src/config.js`](./packages/utils/src/config.js).
## Example test for data returned by DynamoDB client:
- Checkout main branch: `git checkout main`
- Run `yarn` to install dependencies.
### Node.js:
- Run `yarn start:node` to run both v2 and v3 clients in Node.js
- The responses returned by clients will be printed in console, and will re-run when code is updated.
- The file being run is at [`packages/node/src/index.js`](./packages/node/src/index.js).
### Browser:
- Run `yarn start:web` to start vite server with HMR.
- The bundle will be opened in default browser, and get refreshed when code is updated.
- The file being run is at [`packages/web/src/index.js`](./packages/web/src/index.js).
### React Native:
#### iOS
- Run `yarn start:ios` to start local development server with iOS using React Native CLI.
#### Android
- Run `yarn start:android` to start local development server with Android using React Native CLI.
The react-native app in simulator/emulator will refresh when code is updated.
The file being run is at [`packages/react-native/App.js`](./packages/react-native/App.js).
## License
This library is licensed under the MIT-0 License. See the LICENSE file.
| 1 |
cstettler/ddd-to-the-code-workshop-sample | Sample project for DDD to the Code" workshop" | null | # DDD-To-The-Code Workshop: Sample Code
Sample project for "DDD to the Code" workshop.
## Disclaimer
:warning: please do not practice Cargo Cult - when using this sample code in your projects, make sure you understand
that code, and know why you are using it.
This sample project is for educational purposes only. It does not contain production-ready code. Specifically, the
following aspects are not considered real-world like:
- shared code in 'ddd-to-the-code-workshop-support'
- in-memory database for persistence of aggregates
- prototypical domain event infrastructure implementation (non-durable subscriptions, no dead letter handling, ...)
- low test coverage in accounting and rental bounded contexts
- no handling of dependencies between domain events (e.g. in case booking is ended and should be billed
based on the 'booking completed' domain event before the wallet has been initialized based on the 'user registration
completed' domain event - currently, handling the 'booking completed' domain event would fail, the domain event would
be redelivered and eventually moved to dead letter queue)
... and a lot more
## Overview
![Bounded Contexts and Use Cases](docs/bounded-context-and-use-cases.png)
### Use Cases
- register new user
- initialize wallet for user with welcome amount
- book and return bike
- bill booking fee on wallet
## Demo
Use the following script to walk through the implemented use cases:
### Preparation
*Note*: due to compatibility issues with AspectJ and Java 11, this project has to be compiled and executed using Java 8.
- build project:
`./mvnw clean package`
- start registration bounded context:
`java -jar ddd-to-the-code-workshop-registration/target/ddd-to-the-code-workshop-registration-0.0.1-SNAPSHOT.jar`
- start rental bounded context:
`java -jar ddd-to-the-code-workshop-rental/target/ddd-to-the-code-workshop-rental-0.0.1-SNAPSHOT.jar`
- start accounting bounded context:
`java -jar ddd-to-the-code-workshop-accounting/target/ddd-to-the-code-workshop-accounting-0.0.1-SNAPSHOT.jar`
### Initial State
- list of existing bikes (<http://localhost:8083/rental/bikes>): all bikes available
- list of wallets (<http://localhost:8082/accounting/wallets>): no wallets existing
- list of bookings (<http://localhost:8083/rental/bookings>): no bookings existing
### Register New User
- start user registration (<http://localhost:8081/user-registration/>)
- enter user handle (e.g. "peter")
- click "Next >" button
- read verification code from console of registration bounded context (6 digits code)
- enter verification code
- click "Next >" button
- enter first and last name (e.g. "Peter" and "Meier")
- click "Complete" button
- check for new wallet (<http://localhost:8082/accounting/wallets>) with initial amount
### Book Bike
- choose bike (<http://localhost:8083/rental/bikes>)
- enter user handle (e.g. "peter")
- click "Book" button
- check list of booking (<http://localhost:8083/rental/bookings>): new booking (still running)
- check list of bikes (<http://localhost:8083/rental/bikes>): chosen bike not available for booking
- wait some time
### Return Bike
- list bookings (<http://localhost:8083/rental/bookings>)
- click "Return Bike" button
- check list of booking (<http://localhost:8083/rental/bookings>): booking is ended
- check list of bikes (<http://localhost:8083/rental/bikes>): previously chosen bike again available
- check list of wallets (<http://localhost:8082/accounting/wallets>): booking fee deducted from wallet
| 1 |
yevheniyJ/springboot | Sample(Spring Boot + Spring MVC + Spring Security + Thymeleaf + Web jars) | java spring spring-boot | # springboot
Project where you can see how to configure spring security (via UserDetailsService implementation) and thymeleaf template engine in spring boot application and use spring security name spaces on web pages.
| 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:
![](https://raw.githubusercontent.com/ServiceStack/Assets/master/img/wikis/java/linq-examples-screenshot.png)
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 |
dmadunic/clidemo | Sample SpringShell CLI demo | null | # SpringShell CLI Demo
![](https://img.shields.io/badge/Java-ED8B00?style=for-the-badge&logo=java&logoColor=white&style=flat)
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
Sample Command line interpreter (CLI) demo app developed with Spring Shell library.
![Banner](./assets/images/0-banner.png)
## How to use this repository?
Master branch contains current/final state of the the CLI demo, while particular branches,
for example **part1** contain code relevant for specific part of the tutorial (ie. Part 1).
Happy coding!
### Setup (First time)
1. Clone the repository: `git clone git@github.com:dmadunic/clidemo.git`
2. Build project with: `./gradlew clean build `
Now you can run it by executing the following command:
```bash
./run-cli.sh
```
## (Manual) Release new version
Make sure that file gradle.properties in the folder ${USER_HOME}/.gradle/ contains the following two variables defined:
* github_username
* github_password : personal github token (PAT) to be used to install/update packages
For more on creating personal github token (PAT) see this [link](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token)
1) Commit and push everything
2) `./gradlew release`
And simply follow the instructions on the console
## Changelog
### Contributors
- Domagoj Madunić
(c) AG04 Innovative Solutions d.o.o. (2022)
| 1 |
AdamBien/followme.fx | Sample afterburner.fx project | null | followme.fx
===========
A better name would be "cloneme.fx". Follow me is the simplest possible afterburner.fx
application demonstrating:
1. A MVP architecture with FXML and CSS
2. Integration with [http://afterburner.adam-bien.com](http://afterburner.adam-bien.com)
3. Dependency Injection of models / services
4. Conventional configuration with DI
5. Maven 3 Build
How to use
1. git clone https://github.com/AdamBien/followme.fx
2. cd followme.fx
3. mvn
4. [JAVA_8_HOME]/java -jar target/followme-app.jar
A followme.fx can be automatically created with:
`mvn archetype:generate -Dfilter=com.airhacks:igniter`
See also: [http://afterburner.adam-bien.com](http://afterburner.adam-bien.com)
and [https://github.com/AdamBien/igniter.fx](https://github.com/AdamBien/igniter.fx)
| 1 |
yfain/java24hourtrainer2ndedition | This repository has code samples for the 2-nd edition of my upcoming book Java 24-Hour Trainer | null | Java 24 Hour Trainer 2nd Edition
===========================
This repository has code samples for the 2-nd edition of my upcoming book Java 24-Hour Trainer (Wiley/Wrox).
The print version will be available in March 2015.
Table of Contents
=======
1. Introducing Java<br>
2. Integrated Development Environment<br>
3. Object-Oriented Programming with Java<br>
4. Class Methods and Constructors<br>
5. Java Syntax: Bits and Pieces
6. Packages, Interfaces, and Encapsulation
7. Programming with Abstract Classes and Interfaces
8. GUI Basics with Swing
9. Event Handling in Swing GUI
10. Error Handling
11. Collections
12. Generics
13. Lambda Expressions and Functional Programming
14. Working with I/O Streams
15. Java Serialization
16. Network Programming Basics
17. Introduction to Concurrency
18. GUI Basics with JavaFX
19. Developing a game with JavaFX
20. The Stream API
21. Working with Databases Using JDBC
22. Rendering Table Data to GUI
23. Annotations and Reflection
24. Remote Method Invocation
25. Java EE 7 Overview
26. Programming with Servlets
27. JavaServer Pages
28. Web Applications with WebSockets
29. Java Naming and Directory Interface
30. Java Messaging Service
31. Enterprise JavaBeans
32. Java Persistence API
33. RESTful Web Services With JAX-RS
34. Introduction to Spring MVC Framework
35. Introduction to Spring Security
36. Build Automation with Gradle
37. Java Technical Interviews
| 0 |
BijanVan/Spring-Boot-Websocket-Sample | Spring Boot Websocket Sample | null | Spring-Boot-Websocket-Sample
============================
This application is based on "spring-websocket-portfolio" (https://github.com/rstoyanchev/spring-websocket-portfolio).
Here are the main differences:
1) Using Spring Boot
2) Using AngularJS
3) Using embedded ActiveMQ
4) Using SSL
| 1 |
IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java | Time Tracking & Invoicing Sample App using OAuth1.0 | null | [![Sample Banner](views/Callout.png)][ss1]
Time Tracking and Invoicing Java Sample App
=====================================
## Note : This sample uses OAuth1.0
<p>Welcome to the Intuit Developer's Time Tracking and Invoicing Java Sample App.</p>
<p>This sample app is meant to provide working examples of how to integrate your app with the Intuit Small Business ecosystem. Specifically, this sample application demonstrates the following:</p>
<ul>
<li>Implementing OAuth to connect an application to a customer's QuickBooks Online company.</li>
<li>Syncing employee, customer, and service item data from the app's local database to the QuickBooks Online company.</li>
<li>Using the QuickBooks Online SDK to create TimeActivity and Invoice objects in the QuickBooks Online company.</li>
</ul>
<p>Please note that while these examples work, features not called out above are not intended to be taken and used in production business applications. In other words, this is not a seed project to be taken cart blanche and deployed to your production environment.</p>
<p>For example, certain concerns are not addressed at all in our samples (e.g. security, privacy, scalability). In our sample apps, we strive to strike a balance between clarity, maintainability, and performance where we can. However, clarity is ultimately the most important quality in a sample app.</p>
<p>Therefore there are certain instances where we might forgo a more complicated implementation (e.g. caching a frequently used value, robust error handling, more generic domain model structure) in favor of code that is easier to read. In that light, we welcome any feedback that makes our samples apps easier to learn from.</p>
## Table of Contents
* [Requirements](#requirements)
* [First Use Instructions](#first-use-instructions)
* [Running the code](#running-the-code)
* [High Level Workflow](#high-level-workflow)
* [Importing into IntelliJ IDEA & Eclipse](#importing-into-intellij-idea--eclipse)
* [IntelliJ IDEA](#intellij-idea)
* [Eclipse](#eclipse)
* [Project Structure](#project-structure)
* [How To Guides](#how-to-guides)
* [Testing the code](#testing-the-code)
* [Java Junit Tests](#java-junit-tests)
* [Javascript Karma tests](#javascript-karma-tests)
* [Reset the App](#reset-the-app)
* [Watch & Learn](#watch--learn)
* [More Information](#more-information)
## Requirements
In order to successfully run this sample app you need a few things:
1. Java 1.7
2. A [developer.intuit.com](http://developer.intuit.com) account
3. An app on [developer.intuit.com](http://developer.intuit.com) and the associated app token, consumer key, and consumer secret.
4. QuickBooks Java SDK (already included in the [`libs`](libs) folder)
## First Use Instructions
1. Clone the GitHub repo to your computer
2. Fill in your [`oauth.json`](oauth.json) file values (app token, consumer key, consumer secret) by copying over from the keys section for your app.
## Running the code
Once the sample app code is on your computer, you can do the following steps to run the app:
1. cd to the project directory</li>
2. Run the command:`./gradlew bootRun` (Mac OS) or `gradlew.bat bootRun` (Windows)</li>
3. Wait until the terminal output displays the **READY** message.
<p align="center"><img src="https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/images/App-Ready.png" alt="App Ready" height="200" width="1000"/>
4. Open your browser and go to `http://localhost:9001/app/index.html`</li>
If you happen to be behind an http proxy you will need to create a file called gradle.properties in the root of the project and follow instructions on this [page](http://www.gradle.org/docs/current/userguide/build_environment.html) for configuring gradle to use a proxy.
## High Level Workflow
<ol>
<li>Connect to a QuickBooks Online company.
<p align="center"><img src="https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/images/timetrackingstep1a.png" alt="Connect to Quickbooks" height="250" width="250"/></p>
</li>
<li>Setup—sync the following from the local database to the QuickBooks Online company.
<ul>
<li>employees—so time can be recorded against a specific service,</li>
<li>customers—so time can be recorded as billable to a specific customer, </li>
<li>items—the list of billable services.</li>
</ul>
<p align="center"><img src="https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/images/timetrackingstep1b.png" alt="Sync Entities" height="168" width="250"></p>
</li>
<li>Create and push approved time activity objects to QuickBooks Online company for payroll and billing purposes.
<p align="center"><img src="https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/images/timetrackingstep2.png" alt="Sync Entities" height="243" width="250"></p>
</li>
<li>Create and push invoice objects to QuickBooks Online company for billing purposes.
<p align="center"><img src="https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/images/timetrackingstep3.png" alt="Sync Entities" height="84" width="500"></p>
</li>
</ol>
## Importing into IntelliJ IDEA & Eclipse
To edit the code you will need to open it in an IDE. Currently we support both IntelliJ IDEA and Eclipse.
### IntelliJ IDEA
* The project is maintained with IntelliJ IDEA and as such an .ipr file is checked into the GitHub repo.
### Eclipse
* [Importing Project into Eclipse IDE](https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/Importing-Project-into-Eclipse-IDE)
## Project Structure
* **The Java code for integrating with the QuickBooks Online Accounting is located in the [`src`](src) directory.**
* For OAuth implementation see:
- [`OAuthController.java`](src/main/java/com/intuit/developer/sampleapp/timetracking/oauth/controllers/OAuthController.java)
- [`OAuthInfoProvider.java`](src/main/java/com/intuit/developer/sampleapp/timetracking/oauth/OAuthInfoProvider.java)
- [`OAuthInfoProviderImpl.java`](src/main/java/com/intuit/developer/sampleapp/timetracking/oauth/controllers/OAuthInfoProviderImpl.java)
* For QBO V3 Java SDK usage see:
- [`QBOGateway.java`](src/main/java/com/intuit/developer/sampleapp/timetracking/qbo/QBOGateway.java)
- [`DataServiceFactory.java`](src/main/java/com/intuit/developer/sampleapp/timetracking/qbo/DataServiceFactory.java)
* The Java code for the rest of the application is located in the [`src-general`](src-general) directory
* The HTML, CSS and JavaScript code for the web-based client are is located in the [`public`](public) directory
## How To Guides
The following How-To guides related to implementation tasks necessary to produce a production-ready Intuit Partner Platform app (e.g. OAuth, OpenId, etc) are available:
* [OAuth How To Guide (Java)](https://github.com/IntuitDeveloper/SampleApp-TimeTracking_Invoicing-Java/wiki/OAuth-How-To-Guide-(Java))
## Testing the code
The two types of tests in the project (and how to run them) are listed below.
### Java JUnit tests
1. _./gradlew test_
### Javascript Karma tests
To run the Javascript Karma tests you must have NodeJs v0.10.28 or later (http://nodejs.org/) installed and have npm on the path.
1. _cd public_
2. _npm test_
## Reset the App
This app uses a file-based HSQL database that is stored in the _database_ folder in the root of the project. Deleting
this folder will delete all data persisted in the database. The next time you start your app a clean database will be created
with no data.
## Watch & Learn
<a href="http://www.youtube.com/watch?feature=player_embedded&v=I_KgAmtMtLk
" target="_blank"><img src="http://img.youtube.com/vi/I_KgAmtMtLk/0.jpg"
alt="IMAGE ALT TEXT HERE" width="240" height="180" border="10" /></a>
## More Information
More detailed information for this sample app can be found here [here](https://developer.intuit.com/sampleapps/timetracking).
[ss1]: https://help.developer.intuit.com/s/samplefeedback?cid=9010&repoName=SampleApp-TimeTracking_Invoicing-Java
| 1 |
piomin/sample-spring-microservices-advanced | More advanced samples of spring boot and spring cloud microservices showing usage of such tools like api Swagger2 on Zuul, integraction with MongoDB, configuration server, testing with Spring Cloud Contract or Hoverfly | api-gateway hoverfly microservices mongodb spring-boot spring-cloud spring-cloud-config spring-cloud-contract swagger2 testing zuul | null | 0 |
srecon/the-apache-ignite-book | All code samples, scripts and more in-depth examples for The Apache Ignite Book. Include Apache Ignite 2.6 or above | bigdata distributed-database gridgain hadoop hibernate hibernate-ogm hive ignite in-memory-caching in-memory-computations in-memory-database java memoization nosql-database spark spring-data sql streaming streaming-data | # The Apache Ignite Book
<a href="http://leanpub.com/ignitebook"><img src="https://github.com/srecon/the-apache-ignite-book/blob/master/3D_mini.png" alt="he Apache Ignite Book" height="256px" align="right"></a>
This is the code repository (code samples, scripts and more in-depth examples) for [The Apache Ignite Book](https://leanpub.com/ignitebook).
> [!IMPORTANT]
> Note that, updated examples with Apache Ignite version 2.14.x are located on **chapters-java11x** folder.
> Folder **chapters** supports older Ignite version like 2.6.0.
> Use the following JVM options to run the examples on JVM 17 or later, for instance,
>
> java --add-opens=jdk.management/com.sun.management.internal=ALL-UNNAMED --add-opens=java.base/jdk.internal.misc=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.management/com.sun.jmx.mbeanserver=ALL-UNNAMED --add-opens=jdk.internal.jvmstat/sun.jvmstat.monitor=ALL-UNNAMED --add-opens=java.base/sun.reflect.generics.reflectiveObjects=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED -jar ./target/HelloIgnite-runnable.jar
## Naming conventions
Each chapter in the book has a corresponding folder within the repository. Each folder contains a set of files or folders related to each section of the chapter. For an example, the listing of the _memoization_ section is placed in the folder _chapters/chapter-5/memoization_.
## What is this book about?
Apache Ignite is one of the most widely used open source memory-centric distributed, caching, and processing platform. This allows the users to use the platform as an in- memory computing framework or a full functional persistence data stores with SQL and ACID transaction support. On the other hand, Apache Ignite can be used for accelerating existing Relational and NoSQL databases, processing events & streaming data or developing Microservices in fault-tolerant fashion.
This book addressed anyone interested in learning in-memory computing and distributed database. This book intends to provide someone with little to no experience of Apache Ignite with an opportunity to learn how to use this platform effectively from scratch taking a practical hands-on approach to learning.
This book covers the following exciting features:
* Apache Ignite architecture in depth such as data distributing technics (DHT), Rendezvous hashing, durable memory architecture, various cluster topologies, Ignite native persistence, Baseline topology and much more.
* Apache Ignite proven use cases as a memory-centric distributed database, caching and computing platforms.
* Getting started with Apache Ignite by using different tools and technics.
* Caching strategies by examples and how to use Apache Ignite for improving application performance including Hibernate L2 cache, MyBatis, memoization and web session cluster.
* Using Spring Data with Apache Ignite for developing high-performance web applications.
* Ignite query (SQL, API, Text and Scan queries) capabilities in depth.
* Using Spark RDD and Data frames for improving performance on processing fast data.
* Developing and executing distributed computations in a parallel fashion to gain high performance, low latency, and linear scalability.
* Developing distributed Microservices in fault-tolerant fashion.
* Processing events & streaming data for IoT projects, integrate Apache Ignite with other frameworks like Kafka, Storm, Camel, etc.
* Configuring, management and monitoring Ignite cluster with built-in and 3rd party tools such.
If you feel this book is for you, get your [copy](https://leanpub.com/ignitebook) today!
> [!TIP]
> If you are not sure if this book is for you, I suggest you read the sample chapter of the book. The sample chapter is available in different formats including [HTML](https://leanpub.com/ignitebook/read_sample). Anyway, I encourage you to try it out, and if you don't like the book, you can always ask a 100% refund within 45 days.
## build and install
Run the following command from the **chapters-java11x** directory
```
mvn clean install
```
We recommend a workstation with the following configurations for working with the repository:
| № | Name | Value |
|---|--------------|--------------------------------------------------------------|
| 1 | JDK | Oracle/Open JDK 11.x and above. |
| 2 | OS | Linux, MacOS (10.8.3 and above), Windows Vista SP2 and above |
| 3 | Network | No restriction |
| 4 | RAM | Minimum 4GB of RAM |
| 5 | CPU | Minimum 2 core |
| 5 | IDE | Eclipse, IntelliJ Idea, NetBeans or JDeveloper |
| 6 | Apache Maven | Version 3.6.3 or above |
## Conventions
The code will look like the following:
```
public class MySuperExtractor implements StreamSingleTupleExtractor<SinkRecord, String, String> {
@Override public Map.Entry<String, String> extract(SinkRecord msg) {
String[] parts = ((String)msg.value()).split("_");
return new AbstractMap.SimpleEntry<String, String>(parts[1], parts[2]+":"+parts[3]);
}
}
```
Any command-line input or output is written as follows:
```
[2018-12-30 15:39:04,479] INFO Kafka version : 2.0.0 (org.apache.kafka.common.utils.AppInfoParser)
[2018-12-30 15:39:04,479] INFO Kafka commitId : 3402a8361b734732 (org.apache.kafka.common.utils.AppInfoParser)
[2018-12-30 15:39:04,480] INFO [KafkaServer id=0] started (kafka.server.KafkaServer)
```
## This Github repository contains the following examples:
- Ignite example in pure Java
- Ignite example in Spring
- Ignite thinclient example
- Ignite isolated cluster example
- Ignite with Hibernate example
- Ignite with MyBatis example
- Memoization example in Ignite
- Ignite web session clustering example
- Ignite SQL examples
- Ignite QueryApI example
- Ignite text query example
- Ignite distributed SQL JOINs example
- Ignite Spring data example
- Ignite compute grid examples
- Microservices with Ignite examples
- Ignite camel integration example
- Ignite flume integration example
- Ignite kafka integration example
- Ignite Storm integration example
- Ignite Spark RDD example
- Ignite Spark Data frame example
- Ignite Zookeeper discovery example
- Ignite Baseline by examples
- Ignite monitoring by VisualVM/Grafana example
- and much more ...
| 0 |
royrusso/spring-mvc-rest-mockito | Sample Spring-MVC, REST, Mockito project | null | RESTful Services with SpringMVC (tested with Mockito)
=====================================================
Sample project that covers the following concepts:
* Spring-MVC
* REST responses on Spring Controllers
* Testing for REST endpoints using Mockito
REST Endpoints
==============
We try to follow well-accepted REST principles with these examples. All operations performed on this user entity are through the same
endpoint and use the request method as a determiner for the service to call...
* Retrieve user with ID=3: <code>GET http://localhost:8080/user/3</code>
* Save a new User: <code>POST http://localhost:8080/user</code>
* Update User: <code>PUT http://localhost:8080/user</code>
* Delete use with ID=3: <code>DELETE http://localhost:8080/user/3</code>
If an endpoint is triggered that does not have a mapping, the <code>DefaultController</code> will respond with an error.
Usage
=====
* Clone the repository
* To run the tests: <code>mvn clean test</code>
* If deploying to a servlet container: <code>http://localhost:8080/user</code> will return an initial response.
See <code>org.royrusso.mvc.controller.UserController</code> for more REST endpoints. | 1 |
Medisana/vitadock-api | VitaDock Online API library, samples and wiki | null | VitaDock Online API
============
Projects
- java-client-standalone
Available soon:
- java-library
- Android (sample code)
- ObjectiveC (sample code)
- PHP (sample code)
- Python (sample code)
Also check out the projects of our community:
- C#
- https://github.com/karstenols
- https://github.com/karstenols/VitaDock-DNOA-Sample
- https://groups.google.com/forum/#!topic/vitadock-online-api/KcOMlZNRKLg
Servers:
- https://cloud.vitadock.com
- https://cloud.vitadock.com/webclient (generate sample data)
- https://test-cloud.vitadock.online (for testing)
- https://test-cloud.vitadock.online/webclient (generate sample data for test server)
Please see the [wiki](https://github.com/Medisana/vitadock-api/wiki) for a full documentation of the API.
-----
For current status and API updates, please subscribe to our google groups:
https://groups.google.com/d/forum/vitadock-online
https://groups.google.com/d/forum/vitadock-online-api
There, we will announce current open issues, planned down times and planned API changes. Feel free to use these new groups to post your general or API questions.
-----
In case you have any questions, feel free to contact us at [developer@medisanaspace.com](mailto:developer@medisanaspace.com)!
Please note that we only provide support for access via the API. Currently, we cannot provide support for direct access of individual devices via USB / Bluetooth.
Best regards,
Jan Krause,
Senior Software Developer VitaDock® Online
| 0 |
FISCO-BCOS/evidenceSample | A sample of using FISCO BCOS to build an evidence application | null | <center> <h1>区块链存证案例使用说明</h1> </center>
**全新适配FISCO-BCOS 2.0+版本,如果使用FISCO-BCOS 1.2或1.3版本请用[v1.0.0版本](https://github.com/FISCO-BCOS/evidenceSample/releases/tag/v1.0.0)。**
# 一、 背景介绍
* FISCO-BCOS区块链存证是聚焦于企业级应用服务的区块链技术平台,从电子数据的全生命周期介入,实现区块链存证、取证、维权、核证,让司法机构参与到业务过程中,实时见证,为后续的证据核实、纠纷解决、裁决送达提供了可信、可追溯、可证明的技术保障。适用场景:金融行业网络信贷、消费金融、理财等,重点解决可信和司法认可。 <br><br>
* 区块链存证示例是基于FISCO-BCOS区块链开发的应用案例。示例使用智能合约对存证进行管理,使用分层的智能合约结构: <br>
1)工厂合约(EvidenceSignersData.sol),由存证各方事前约定,存储存证生效条件,并管理存证的生成。 <br>
2)存证合约(Evidence.sol),由工厂合约生成,存储存证id,hash和各方签名(每张存证一个合约)。 <br>
两层智能合约的设计,可以使系统获得更好的扩展性。示例使用三个角色(用户、存证机构、仲裁机构)来说明一个典型的电子存证场景。关键业务为证据上链,多方签署,链上取证。 <br>
* 本存证样例展示的业务流程主要是:1、收集区块链上机构公钥信息(用户的公钥信息,存证机构的公钥信息,仲裁机构的公钥信息),部署工厂合约。2、用户发送签名存证信息,并发送存证请求。3、存证机构收到存证请求,取出存证内容校验(样例中没有展示),并签名确认。4、仲裁机构收到存证请求,取出存证内容校验(样例中没有展示),并签名确认。5、取证
* 本文档旨在帮助开发者快速入门区块链存证应用开发。
# 二、存证案例运行环境搭建
1. 本文档使用4个区块链节点来模拟区块链环境,请参考 [安装文档](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/installation.html) 完成FISCO BCOS区块链的搭建和控制台的下载工作,本教程中的操作假设在该文档搭建的环境下进行。
2. 更新签名机构公私钥(**示例演示可以直接使用sample提供公私钥,jks文件**),公钥在applicationContext.xml文件中配置,私钥需替换/evidence/src/main/resources下的.jks文件,配置和生成公私钥参照下一节中角色公钥配置说明。
3. SDK证书
```
# 进入~目录
# 拷贝节点证书到项目的资源目录
$ cd ~
$ cp fisco/nodes/127.0.0.1/sdk/* evidence/src/main/resources
```
4. applicationContext关于节点的配置请参考:下面的存证案例配置文件说明。
# 三、 存证案例配置文件说明
```
evidence/src/main/resources/applicationContext.xml文件配置说明
```
1、角色公钥配置说明:
<bean id="addressConf" class="org.bcos.evidence.sample.PublicAddressConf">
<property name="allPublicAddress">
<map>
<entry key="User" value="0x33674063c4618f4773fac75dc2f07e55f6f391ce">
</entry>
<entry key="Arbitrator" value="0x6bc952a2e4db9c0c86a368d83e9df0c6ab481102">
</entry>
<entry key="Depositor" value="0x5a6c7ccf9efa702f4e8888ff7e8a3310abcf8c51">
</entry>
</map>
</property>
</bean>
配置解释:
* 配置中key=User代表用户角色,对应的私钥文件为user.jks;key=Arbitrator代表仲裁机构,对应的私钥文件为arbitrator.jks;key=Depositor代表存证机构,对应的私钥文件为depositor.jks。
* 按照上面的key-value的格式写入3个角色所对应的公钥,在/evidence/src/main/resources文件夹下放入角色所对应的私钥。
私钥是由linux系统下java JDK/bin中的keytool工具生成的(生成命令如下),私钥生成后,可以通过私钥调用接口生成需要的公钥,具体操作可参照<a name="host_node" id="host_node">4.6. 获取公钥</a>
keytool -genkeypair -alias ec -keyalg EC -keysize 256 -sigalg SHA256withECDSA -validity 365 -storetype JKS -
keystore user.jks -storepass 123456
2、区块链节点信息配置,[SDK配置具体请参考](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/sdk/sdk.html)。:
```
<bean id="groupChannelConnectionsConfig" class="org.fisco.bcos.channel.handler.GroupChannelConnectionsConfig">
<property name="allChannelConnections">
<list>
<bean id="group1" class="org.fisco.bcos.channel.handler.ChannelConnections">
<property name="groupId" value="1" />
<property name="connectionsStr"><!-- 配置群组区块链节点列表-->
<list>
<value>127.0.0.1:20200</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
<bean id="channelService" class="org.fisco.bcos.channel.client.Service" depends-on="groupChannelConnectionsConfig">
<property name="groupId" value="1" /><!-- 配置群组ID -->
<property name="orgID" value="fisco" /><!-- 配置机构名称 -->
<property name="allChannelConnections" ref="groupChannelConnectionsConfig"></property>
</bean>
```
# 四、存证案例工具包使用说明
本节提供使用示例工具包,以便开发者能够快速熟悉存证应用。在工具包中,bin文件下为执行脚本,conf文件夹下为工具包配置文件,lib文件下为存证案例依赖包,contracts中存放合约源码(合约java代码生成可以参照[4.7](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/tutorial/sdk_application.html#id7))
#### 存证案例工具包环境初始化
* 存证工具包可以通过存证客户端gradle build生成;或者直接下载,下载链接https://github.com/FISCO-BCOS/evidenceSample/tree/master/evidence_toolkit
* 下载完成之后建议对bin文件夹下的文件执行chmod命令。
* 根据实际需求更新公私钥(需要3组),公钥以key-value的形式在applicationContext.xml中配置,私钥更新需要替换conf文件下的.jks私钥文件。若无特殊需求可以不用更新公私钥,直接使用默认配置即可。
* 替换工具包证书
```
# 进入~目录
# 拷贝节点证书
$ cd ~
$ cp fisco/nodes/127.0.0.1/sdk/* evidence_toolkit/conf
```
* applicationContext.xml配置文件,请参考(上面第三节: 存证案例配置文件说明)
#### 存证案例工具包一键脚本步骤
若想查看完整的执行过程,可执行存证工具包bin文件下runEvidence.sh脚本,runEvidence.sh为存证的一键默认执行脚本,脚本中将存证sample工具包的执行命令进行封装。
#### 存证案例工具包分步操作步骤
1、工厂合约部署
进入到bin文件下,输入以下命令:
```
./evidence deploy keyStoreFileName keyStorePassword keyPassword
例子:./evidence deploy user.jks '123456' '123456'
```
参数说明:
* 在上面的命令中需要传入4个参数,第一个参数固定不可修改。后面三个参数依赖conf中的私钥的文件(直接输入文件名,并非路径)。keyStoreFileName:私钥文件名;keyStorePassword、keyPassword分别为证书生成时输入的keyStore密码和key密码。
控制台显示结果:
deploy factoryContract success, address: deployAddress.(部署工厂合约返回地址)
2、用户创建新证据
进入到bin文件下,在控制台输入命令:
```
./evidence new keyStoreFileName keyStorePassword keyPassword deployAddress evidence_id evidence_hash
例子:./evidence new user.jks '123456' '123456' '0x19e2f046f4fc6a02d732a3ffda6480c34214f57f' '1' '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
```
参数说明:
* 命令中第一个参数不可修改,deployAddress为工厂合约部署之后返回的地址,evidence_id和evidence_hash分别为证据ID和证据的hash值,长度无限制。证据的hash可以是合同的hash值,还款记录的hash等。计算方法可以是md5值,sha1,sha3等。
控制台显示结果:
newEvidence success, newEvidenceAddress: newEvidenceAddress(创建证据返回地址)
3、发送签名上链
进入到bin文件下,在控制台输入命令:
./evidence send keyStoreFileName keyStorePassword keyPassword newEvidenceAddress
例子:./evidence send arbitrator.jks '123456' '123456' '0x4437863afe7c9adce4e658c95666feaab1d996a2'
./evidence send depositor.jks '123456' '123456' '0x4437863afe7c9adce4e658c95666feaab1d996a2'
参数说明:
* 注意:此命令需要执行两次,在newEvidence步骤时,用户已经签名,在这个步骤需要存证机构和仲裁机构双方签名,所以在执行这个命令时传入的keyStoreFileName、keyStorePassword、keyPassword分别为两个机构的私钥及密码。
* 在这个步骤中同样需要用到evidence_hash值,程序中通过newEvidenceAddress查询证据的信息,然后获取evidence_hash值。
* 命令中第一个参数不可修改,newEvidenceAddress为创建证据区块链返回的地址。
控制台显示结果:
sendSignatureToBlockChain success:true
4、获取证据
进入到bin文件下,在控制台输入命令:
```
./evidence get keyStoreFileName keyStorePassword keyPassword newEvidenceAddress
例子:./evidence get user.jks '123456' '123456' '0x4437863afe7c9adce4e658c95666feaab1d996a2'
```
参数说明:
* 命令中第一个参数不可修改,在这个命令中依赖conf中的私钥文件和deploy操作相同,newEvidenceAddress为创建证据后区块链返回的地址。
控制台显示结果:
the evidenceID:evidence_id(创建证据时传入的evidence_id值)
the evidenceHash:evidence_hash( 创建证据时传入的evidence_hash值)
the signature[0-2]:(打印3个角色的签名)
the publicKey[0-2]:(打印3个角色的公钥)
5、校验证据和签名
进入到bin文件下,在控制台输入命令:
```
./evidence verify keyStoreFileName keyStorePassword keyPassword newEvidenceAddress
例子:./evidence verify user.jks '123456' '123456' '0x4437863afe7c9adce4e658c95666feaab1d996a2'
```
参数说明:
* 命令中第一个参数不可修改,在这个命令中依赖conf中的私钥文件和deploy操作相同,newEvidenceAddress为创建证据后区块链返回的地址。
控制台结果显示:
若校验通过显示:verifyEvidence success:true
若校验失败显示:verifyEvidence failed:false
6、获取公钥
进入到bin文件下,在控制台输入命令:
```
./evidence getPublicKey keyStoreFileName keyStorePassword keyPassword
例子:./evidence getPublicKey user.jks '123456' '123456'
```
参数说明:
* 命令中第一个参数不可修改,通过读取对应的私钥文件,获取公钥。
控制台结果显示:
publicKey:公钥
7、合约编译及java Wrap代码生成
* 参考[合约转换](https://fisco-bcos-documentation.readthedocs.io/zh_CN/latest/docs/tutorial/sdk_application.html#id7)
# 五、存证客户端使用
存证客户端用java编写,可将工程导入Eclipse做二次开发。二次开发工程URL为:https://github.com/FISCO-BCOS/evidenceSample/tree/master/evidence。
其入口为org.bcos.evidence.app.Main类,客户端中对合约的调用主要包括:web3j的初始化,合约对象部署,载入已经部署的合约,创建证据,发送签名数据,获取证据信息,以及证据校验。区块链应用程序实际是通过web3j生成的java Wrapper类(详细介绍参看4.7合约编译及java Wrap代码生成),通过jsonRPC调用和FISCO-BCOS客户端节点通信,再由客户端返回jsonRPC请求响应。
1、web3j初始化
注意:客户端调用智能合约首先必须初始化web3j,初始化关键代码如下:
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
web3j = Web3j.build(channelEthereumService);
2、工厂合约部署
使用初始化的web3j对象来部署智能合约,如果工厂合约部署成功,Future对象会返回合约调用对象(即合约地址),合约部署关键代码如下:
```
EvidenceSignersData evidenceSignersData = EvidenceSignersData.deploy(web3j, credentials, new StaticGasProvider(gasPrice, gasLimited), arrayList).send();
```
3、载入已经部署的合约
合约部署成功后,可以获取到已经部署的合约地址:evidenceSignersData.getContractAddress();使用已经部署合约地址,初始化的web3j对象,可以载入智能合约调用对象。
```
EvidenceSignersData evidenceSignersData = EvidenceSignersData.load(address.toString(), web3j, credentials, new StaticGasProvider(gasPrice, gasLimited));
```
注意:部署后可以直接使用返回的智能合约对象,而无需再load载入!
4、创建新证据
发送交易通过直接调用已经部署或载入的智能合约调用对象执行合约对应接口即可,交易执行成功后将返回Receipt,Receipt包含交易hash和其他信息。
```
Receipt receipt = evidenceSignersData.newEvidence(evidence_hash, evidence_id,evidence_id, BigInteger.valueOf(signatureData.getV()),signatureData.getR(),signatureData.getS()).sendAsync().get();
```
注意:调用此方法需要传入参数,参数为string[],长度为3即可。传入的三个参数分别模拟对应evidence_id(证据ID)、evidence_hash(证据hash值)、sign_data(签名数据),客户端将传入的三个参数生成一个完成的证据存入区块链中。
5、发送签名数据上链
在用户角色调用newEvidence()接口创建一个新的证据之后,存证机构和签名机构分别需要对证据进行签名,并且将签名的数据发送到区块链中进行存储,关键代码如下:
```
Evidence evidence = Evidence.load(address, web3j, credentials, gasPrice, gasLimited);
TransactionReceipt receipt = evidence.addSignatures(BigInteger.valueOf(signature.getV()),
signature.getR(),
signature.getS()).sendAsync().get();
```
6、获取证据
创建证据一个,区块链会返回一个交易地址,使用已经部署或载入的智能合约对象调用getEvidence()接口传入交易返回的地址,可返回一个list<Type>,对list<Type>进行解析可以得到一个evidence对象。
```
Evidence evidence = Evidence.load(newEvidenceAddres, web3j, credentials, gasPrice, gasLimited);
Tuple7<String, String, String, List<BigInteger>, List<byte[]>, List<byte[]>, List<String>> result2 = evidence.getEvidence().send();
```
7、校验证据和签名
通过调用步骤6中的接口可以获取到证据的完整信息,并且附带有3个角色对证据的签名信息,通过校验公钥是否相同来确定签名的信息是否准确。关键代码如下:
for (String str : data.getSignatures()) {
try {
addressList.add(verifySignedMessage(data.getEvidenceHash(), str));
} catch (SignatureException e) {
throw e;
}
}
for (String addr : data.getPublicKeys()) {
boolean flag = false;
for (String str : addressList) {
if (str.equals(addr)) {
flag = true;
break;
}
}
if (!flag) {
return false;
}
}
# 六、[web3sdk的使用方式](https://github.com/FISCO-BCOS/web3sdk)
如果您觉得本文不错,欢迎[戳这里](https://github.com/FISCO-BCOS/FISCO-BCOS)给FISCO BCOS打star:star:。
| 1 |