full_name stringlengths 7 104 | description stringlengths 4 725 ⌀ | topics stringlengths 3 468 ⌀ | readme stringlengths 13 565k ⌀ | label int64 0 1 |
|---|---|---|---|---|
spring-petclinic/spring-petclinic-rest | REST version of the Spring Petclinic sample application | hibernate jackson jdbc mysql-database openapi rest rest-api sample spring spring-data spring-data-jpa spring-mvc springfox springframework swagger | null | 1 |
aws-samples/aws-codedeploy-sample-tomcat | A sample Tomcat application integrated with CodeDeploy. | null | # aws-codedeploy-sample-tomcat
A sample Tomcat application integrated with CodeDeploy.
| 1 |
microsoft/project-rome | Code samples and documentation of Microsoft's Project Rome SDK | null | # Project Rome
[Project Rome](https://developer.microsoft.com/en-us/windows/project-rome) is Microsoft's cross-device experiences platform. Project Rome frees your app from running on a specific device, enabling a cross-device, user centric experience.
On this site you will find samples of Project Rome.
Visit the [Project Rome landing page](https://developer.microsoft.com/en-us/windows/project-rome) for more general information about Project Rome.
See the [Project Rome developer docs](https://docs.microsoft.com/windows/project-rome/) for how-to guides and API reference docs that will help you get started integrating Project Rome features into your app.
See the [Cross-Device Experience docs](https://developer.microsoft.com/en-us/graph/docs/concepts/cross-device-concept-overview) under Microsoft Graph node to find out more about how Project Rome feature capabilities are exposed via Microsoft Graph REST API endpoint.
## Privacy
See [Microsoft's privacy statement](https://privacy.microsoft.com/en-us/privacystatement/) for more information.
## Microsoft Open Source Code of Conduct
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.
## Give feedback
|[UserVoice](https://wpdev.uservoice.com/forums/110705-universal-windows-platform/category/183208-connected-apps-and-devices-project-rome)|[Feedback Hub](https://support.microsoft.com/en-us/help/4021566/windows-10-send-feedback-to-microsoft-with-feedback-hub-app)|[Contact Us](mailto:projectrometeam@microsoft.com)|
|-----|-----|-----| | 0 |
akka/alpakka-samples | Example projects building Reactive Integrations using Alpakka | akka akka-streams alpakka reactive-streams | # Alpakka samples
[Alpakka documentation](https://docs.akka.io/docs/alpakka/)
Akka is licensed under the Business Source License 1.1, please see the [Akka License FAQ](https://www.lightbend.com/akka/license-faq). | 1 |
mp911de/spring-cloud-vault-config-samples | Examples for Spring Vault and Spring Cloud Vault Config | samples spring spring-cloud-vault spring-vault vault | null | 0 |
kenfinnigan/ejm-samples | null | null | null | 0 |
digitalsonic/learning-spring-samples | 《学透Spring: 从入门到项目实战》代码示例 | java spring-boot spring-cloud spring-framework | # 《学透Spring: 从入门到项目实战》代码示例
本仓库内容为图书《学透Spring: 从入门到项目实战》的随书代码示例。更多关于本书的信息可以访问图灵社区的[图书详情页](https://www.ituring.com.cn/book/2910)。

## 本书介绍
本书的目标是让大家又快又好地打包学透 Spring 技术栈,内容将涉及 Spring Framework、Spring Boot、 Spring Cloud 等 Spring 家族成员。 本书分为四部分:
* 第一部分“Spring 入门”,先学习基本的 Spring IoC、AOP,随后过渡到当下热门的 Spring Boot ;
* 第二部分“Spring 中的数据操作”,其中既有常规的 SQL、NoSQL 数据操作,也有进阶的数据源配置和缓存抽象;
* 第三部分“使用 Spring 开发 Web 应用”,讲述 Spring MVC 细节的同时,也不放过 Web 安全与 REST ;
* 第四部分“使用 Spring 开发微服务”,除了常规的 Spring Cloud 模块,也会讲解 Spring Cloud Alibaba。
在讲解具体内容的基本示例之外,书中还设计了一个贯穿主要章节的实战案例,带大家一步步从零开始实现一个灵活运用全书内容的项目“二进制奶茶店”。 本书重实战、重工程现实,是业内专家丁雪丰亲历的高效学习路径,汇集了作者多年的实战经验。跟着兔子书,只要具备 Java 基础知识,就可以迅速上手 Spring,并落地实战项目和生产环境。
| 0 |
ddd-by-examples/event-source-cqrs-sample | Sample ES/CQRS application | cqrs domain-driven-design event-driven event-sourcing hexagonal-architecture springboot | [](https://devternity.com)
# Sample event sourced application with Command Query Responsibility Segregation
** Event sourcing **
Shop item can be bought, paid, and marked as payment timeout. Aggregate root (ShopItem) emits 3 different types of domain events: ItemBought, ItemPaid, ItemPaymentMissing. All of them are consequences of commands.
Event store is constructed in database as EventStream table with collection of EventDescriptors. EventStream is fetched by unique aggregate root uuid.
** CQRS **
Read model is constructed by listening to domain events mentioned before. This task is performed by ReadModelOnDomainEventUpdater
| 1 |
keets2012/Spring-Boot-Samples | Spring-Boot-Samples(Spring Cloud) | null | # Spring-Boot-Samples(Spring Cloud)
**网关、auth权限服务和backend服务的整合项目地址为:
GitHub:https://github.com/keets2012/microservice-integration
或者 码云:https://gitee.com/keets/microservice-integration**
### 2018/11/16
增加Actuator 1.x和2.x的模块
### modules
该项目包含以下samples模块(更新中);
- demo-jersey-starter
- zipkin-server-stream
- ...
#### 我的博客
http://blueskykong.com
github地址:https://github.com/keets2012/Spring-Boot-Samples
git ee: https://gitee.com/keets/spring-boot-samples
**你的star是对我最好的鼓励^_^**
### 订阅最新文章,欢迎关注我的公众号

| 0 |
esteban-aliverti/JBPM-Samples | Simple Samples for JBPM | null | null | 0 |
DickChesterwood/istio-fleetman | A sample project to demonstrate Istio's features | null | ***January 2023: should now support arm64 (Apple silicon) properly ***
For support, please visit the support service on the platform you're following the course on (Udemy or VPP). I generally check every day.
Now available at VirtualPairProgrammers.com and Udemy!
Udemy: https://www.udemy.com/course/istio-hands-on-for-kubernetes/?referralCode=36E4FA521FB5D6124156
VirtualPairProgrammers: https://virtualpairprogrammers.com/training-courses/Istio-training.html
Aim: make Istio understandable - it's not that hard. I don't mention TCP/IP stack levels once. Or the CNCF.
| 1 |
jboss-developer/jboss-jdg-quickstarts | Quickstarts (or examples, or samples) for Infinispan. | null | [](https://travis-ci.org/jboss-developer/jboss-jdg-quickstarts)
Red Hat Data Grid Quickstarts
=============================
Red Hat Data Grid (RHDG) is an elastically scalable in-memory data store built on the open source Infinispan project.
## RHDG Modes
You can use Red Hat Data Grid in two modes:
* _Library Mode_ provides binaries to build and deploy custom runtime environments. RHDG runs alongside your application in the same JVM. Your application has local access to a single node in a distributed cluster.
* _Remote Client-Server Mode_ provides a self-contained process in a container based on JBoss EAP. RHDG runs remotely and provides access to data through `Hot Rod`, `REST`, or `Memcached` interfaces.
## About the Quickstarts
These quickstarts demonstrate Red Hat Data Grid features and capabilities with specific, working examples that you can reference in your own projects.
If you are using _Remote Client-Server Mode_, you should start with the **helloworld-jdg** quickstart to ensure that your server configuration is valid and you can start it successfully.
Quickstarts have **Beginner**, **Intermediate**, and **Advanced** levels. You should start with a level that is comfortable for you and move on to the next level as you gain expertise.
Some quickstarts are prerequisites for others that expand on certain capabilities or functionality. You should always deploy and run any prerequisite quickstarts first.
## Available Quickstarts
This distribution contains the following quickstarts:
| **Quickstart Name** | **Demonstrated Technologies** | **Shows you how to...** |
|:-----------|:-----------|:-----------|
| [carmart](carmart/README.md) | Data Grid, CDI | Use Data Grid instead of a relational database. |
| [carmart-tx](carmart-tx/README.md) | Data Grid, CDI, Transactions | Use Data Grid instead of a relational database with transactions enabled.|
| [eap-cluster-app](eap-cluster-app/README.md) | Data Grid, CDI, EJB | Access an Data Grid cache from a JBoss EAP application using JDG modules for EAP.|
| [helloworld-jdg](helloworld-jdg/README.md) | Data Grid, CDI | Use Data Grid in clustered mode with expiration.|
| [hotrod-endpoint](hotrod-endpoint/README.md) | Data Grid, Hot Rod | Access Data Grid remotely through the Hot Rod protocol. |
| [hotrod-secured](hotrod-secured/README.md) | Data Grid, Hot Rod | Securely access Data Grid remotely through the Hot Rod protocol. |
| [memcached-endpoint](memcached-endpoint/README.md) | Data Grid, Memcached | Access Data Grid remotely through the Memcached protocol. |
| [openshift](openshift/README.md) | Data Grid, OpenShift | Complete tutorials for Data Grid on OpenShift that range from simple "Hello World" demonstrations to more advanced use cases. |
| [rapid-stock-market](rapid-stock-market/README.md) | Data Grid, Hot Rod, REST | Use compatibility mode to access data with multiple protocols. |
| [spring 4](spring4/README.md) | Data Grid, Spring | Use Spring 4 integration modules. |
| [spring 5](spring5/README.md) | Data Grid, Spring | Use Spring 5 integration modules. |
| [spring 4 session](spring4-session/README.md) | Data Grid, Spring Boot, Spring Session | Use of Spring Boot and Spring Session with RHDG. |
| [spring 5 session](spring5-session/README.md) | Data Grid, Spring Boot, Spring Session | Use of Spring Boot and Spring Session with RHDG. |
| [remote-query](remote-query/README.md) | Data Grid, Hot Rod, Remote Query | Query Data Grid remotely through the Hot Rod protocol. |
| [rest-endpoint](rest-endpoint/README.md) | Data Grid, REST | Access Data Grid remotely through the REST protocol. |
| [secure-embedded-cache](secure-embedded-cache/README.md) | Data Grid, CDI, REST | Secure Data Grid in Library (embedded) mode. |
| [cdi](cdi-jdg/README.md) | Data Grid, CDI | Use Data Grid CDI and JCache extensions. |
| [camel-jbossdatagrid-fuse](camel-jbossdatagrid-fuse/README.md) | Camel, Data Grid, REST | Use the Camel component camel-jbossdatagrid in JBoss Fuse. |
| [spark](spark/README.md) | Data Grid, Apache Spark | Read and write data to Data Grid and use streaming to react to data changes in real time. |
## System Requirements
You need the following to build and run the quickstarts:
* Java 8.0 (Java SDK 1.8) or later.
* Maven 3.0 or later. See the [Maven Getting Started Guide](http://maven.apache.org/guides/getting-started/index.html).
* JBoss EAP server distribution. Available from the [Red Hat Customer Portal](https://access.redhat.com/downloads).
* RHDG server distribution for _Remote Client-Server Mode_. Available from the [Red Hat Customer Portal](https://access.redhat.com/downloads).
You can also run the quickstarts with [JBoss Developer Studio or Eclipse](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/USE_JBDS.md#use-jboss-developer-studio-or-eclipse-to-run-the-quickstarts).
### Configuring Maven
If you have not yet done so, you must [Configure Maven](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/CONFIGURE_MAVEN.md#configure-maven-to-build-and-deploy-the-quickstarts).
If you do not configure Maven, you must pass settings with every Maven command as follows: ` -s QUICKSTART_HOME/settings.xml`
### Setting Environment Variables
RHDG quickstarts use the following environment variables:
* `JBOSS_HOME` denotes the path to your RHDG server installation.
* `EAP_HOME` denotes the path to your JBoss EAP installation.
`EAP_HOME` is a *replaceable* value. When you encounter it in a RHDG quickstart, change the value as appropriate.
| Installation method | Installation directory |
|:-----------|:-----------|
| ZIP archive | Custom directory |
| RPM | `/var/lib/jbossas/` |
| Installer | `{USER_HOME}/EAP-6.3.0` |
| JBoss Developer Studio installer | `{USER_HOME}/jbdevstudio/runtimes/jboss-eap` |
Where `{USER_HOME}` is one of the following:
* Linux: `/home/USER_NAME/`
* Windows: `"C:\Users\USER_NAME\"`
## Running the Quickstarts
Refer to the `README` file in each quickstart directory for instructions on building and running the quickstart.
### Building Quickstart Archives
You can build archives without deploying the quickstarts to check for compilation errors and view the contents of the quickstart.
From the root directory of the quickstart, run `$ mvn clean install` to build the archive.
## Contributing the Quickstarts
Refer to [JBoss Developer Contributing Guide](https://github.com/jboss-developer/jboss-developer-shared-resources/blob/master/guides/CONTRIBUTING.md)
| 0 |
hiwepy/spring-boot-starter-samples | spring-boot-starter-samples | axis cas cxf disruptor druid ehcache3 flyway httpclient kaptcha log4j2 mina mybatis netty pf4j rocketmq spring-boot spring-boot-starter starter swagger2 xfire | # spring-boot-starter-samples
spring-boot-starter-samples
| 0 |
mohitsinha/tutorials | Code samples for tutorials blog | java reactor-core spring-boot springdata springframework webflux | # Code Samples for my personal blog
You can read them [here](http://sinhamohit.com).
| 0 |
dandelion/dandelion-samples | [DEPRECATED] All Dandelion sample applications | null | [DEPRECATED] Dandelion Samples
=================================================================
This repository is now deprecated.
It has been splitted up into several repos, one per component. For example: https://github.com/dandelion/dandelion-datatables-samples for Dandelion-Datatables.
=
The [Dandelion team](http://dandelion.github.io/team/).
| 1 |
fangjian0423/deep-in-spring-cloud-samples | 《深入理解 Spring Cloud 与实战》配套示例代码 | null | # 《深入理解 Spring Cloud 与实战》
## 目录
第 1 章 Spring Cloud生态
第 2 章 服务注册与服务发现
第 3 章 负载均衡与服务调用
第 4 章 配置管理
第 5 章 熔断器
第 6 章 Spring生态消息驱动
第 7 章 消息总线
第 8 章 Spring Cloud Data Flow
第 9 章 网关
第 10 章 Spring Cloud 与 Serverless
## 覆盖技术栈
- Spring Boot
- Alibaba Nacos
- Netflix Eureka
- Spring Cloud LoadBalancer
- Netflix Ribbon
- OpenFeign
- Dubbo Spring Cloud
- Spring Cloud Config Client/Server
- Spring Cloud Circuit Breaker
- Alibaba Sentinel
- Netflix Hystrix
- Resilience4J
- Spring Messaing
- Spring Integration
- Spring Cloud Stream
- Spring Cloud Bus
- Spring Cloud Data Flow
- Spring Cloud Task
- Spring Cloud Skipper
- Spring Cloud Deployer
- Spring Batch
- Spring Cloud Gateway
- Spring Cloud Function
## 案例讲解
- Spring Cloud 双注册/双订阅完成服务平滑迁移
- Netflix Ribbon 流量控制完成灰度发布
- Netflix Ribbon 流量控制条件动态生效
- Sentinel 保护应用防止服务雪崩
- Spring Messaging 处理 WebSocket 请求
- Spring Cloud Bus 配置 Spring Cloud Config 完成配置动态刷新
- 流处理案例:Spring Cloud Stream 完成信用卡反欺诈系统
- 批处理案例:Spring Cloud Task 完成统计GitHub仓库的各项指标数据
- Spring Cloud Function & GCP Cloud Functions 体验 Serverless
售卖地址: https://item.jd.com/13043028.html 。 感谢支持
| 0 |
samaddico/spring-boot-samples | null | null | # spring-boot-samples
This contain sample spring boot applications using maven or gradle as build tools
| 0 |
kabutz/dynamic-proxies-samples | null | null | # Dynamic Proxies Samples
This repository is a companion to the book
[Dynamic Proxies in Java](https://www.infoq.com/minibooks/java-dynamic-proxies/)
by Dr Heinz M. Kabutz.
It contains several modules.
1. The `core` module is a library of dynamic proxy helper
classes. The `Proxies` class is a façade that makes it
easy to use the common configurations. The classes in this
library are described in the book and used in the other modules.
The core is published in the
[Maven Central Repository](https://search.maven.org/artifact/eu.javaspecialists.books.dynamicproxies/core)
and you may use it in your projects under the
[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).
The coordinates are `eu.javaspecialists.books.dynamicproxies:core:2.0.0`,
or add this dependency to your pom.xml:
```
<dependency>
<groupId>eu.javaspecialists.books.dynamicproxies</groupId>
<artifactId>core</artifactId>
<version>2.0.0</version>
</dependency>
```
2. The `samples` module is a collection of the sample code used
in the book.
3. The `benchmarks` module is a set of benchmarks using the
[Java Microbenchmark Harness](https://openjdk.java.net/projects/code-tools/jmh/)
(JMH) to test the performance of dynamic proxies. The results
of the benchmarks are summarized in the book.
## Benchmarks
To exercise the benchmarks, run the following in a terminal, or use your IDE to do the equivalent:
`mvn verify -P run-benchmarks`
## Java Platform Module System (JPMS)
The `core` and `samples` modules use JPMS so that we can show the
effects of JPMS modules on dynamic proxies, and avoid the illegal
access warnings from the JRE when running the code.
For the `benchmarks` module, however, there is a package clash
in JMH v1.21 which blocks JPMS from loading the components of
JMH as automatic modules.
In particular, the package `org.openjdk.jmh.generators.core` in
`jmh-core` clashes with the package `org.openjdk.jmh.generators`
in `jmh-generator-annprocess`.
| 0 |
Azure-Samples/azure-functions-samples-java | The Java sample code for Microsoft Azure Functions | null | ---
page_type: sample
languages:
- java
products:
- azure-functions
- azure
description: "This repository contains sample for Azure Functions in Java"
urlFragment: "azure-functions-java"
---
# Azure functions samples in Java
This repository contains samples which show the usage of [Azure Functions](https://docs.microsoft.com/en-us/azure/azure-functions/) in Java for the below scenarios.
| Scenario | Description |
|-------------------|--------------------------------------------|
| [HttpTrigger](./triggers-bindings/src/main/java/com/functions/Function.java) | Basic HttpTrigger and FixedDelayRetry with HttpTrigger. |
| [BlobTrigger](./triggers-bindings/src/main/java/com/functions/BlobTriggerFunction.java) | BlobTrigger, read blob using BlobInput binding and output to blob using BlobOutput binding. |
| [CosmosDBTrigger](./triggers-bindings/src/main/java/com/functions/CosmosDBTriggerFunction.java) | CosmosDBTrigger, read cosmos DB entries with CosmosDBInput binding and output to cosmos DB CosmosDBOutput binding. |
| [TimerTrigger](./triggers-bindings/src/main/java/com/functions/TimerTriggerFunction.java) | Basic periodic TimerTrigger. |
| [EventGridTrigger](./triggers-bindings/src/main/java/com/functions/EventGridTriggerFunction.java) | EventGridTrigger and send event to Event Grid using EventGridOutput binding. |
| [EventHubTrigger](./triggers-bindings/src/main/java/com/functions/EventHubTriggerFunction.java) | EventHubTrigger for message received in event grid and output to event grid using EventHubOutput binding. |
| [KafkaTrigger](./triggers-bindings/src/main/java/com/functions/KafkaTriggerFunction.java) | KafkaTrigger with KafkaOutput and QueueOutput example. |
| [QueueTrigger](./triggers-bindings/src/main/java/com/functions/QueueTriggerFunction.java) | QueueTrigger to read content from queue and output to queue using QueueOutput binding. |
| [ServiceBusQueueTrigger](./triggers-bindings/src/main/java/com/functions/ServiceBusQueueTriggerFunction.java) | ServiceBusQueueTrigger to read message from a queue in service bus and output to service bus queue using ServiceBusQueueOutput binding. |
| [ServiceBusTopicTrigger](./triggers-bindings/src/main/java/com/functions/ServiceBusTopicTriggerFunction.java) | ServiceBusTopicTrigger to read message from a topic in service bus and output to service bus topic using ServiceBusTopicOutput binding. |
| [Table function](./triggers-bindings/src/main/java/com/functions/TableFunction.java) | Basic example to read and write to table in Azure Storage using TableInput and TableOutput binding. |
| [Durable function](./durable-function/src/main/java/com/azfs/example/DurableFunction.java) | Durable function example to start an orchestration and follow activity chaining. |
| [Distributed tracing](./distributed-tracing/src/main/java/com/azfs/example/DistributedTracingFunction.java) | Distributed tracing example that adds entries to a MYSQL database via JDBC, adds custom metrics to the Application Insights and outputs to cosmos DB CosmosDBOutput binding. |
| [Dependency injection - Dagger](./dependency-injection/dagger-function/src/main/java/com/azfs/Function.java) | Dagger example that shows the usage of dependency injection with azure functions. |
| [Dependency injection - Guice](./dependency-injection/guice-function/src/main/java/com/azfs/Function.java) | Google guice example that shows the usage of dependency injection with azure functions. |
| [Spring cloud](./spring-cloud/src/main/java/example/uppercase/UppercaseHandler.java) | Usage of Spring cloud to develop a function. |
## Contents
Outlines the contents of this repository. It helps users navigate the codebase, build configuration and any related assets.
| File/folder | Description |
|-------------------|--------------------------------------------|
| `triggers-bindings` | Triggers and bindings available in Azure functions. |
| `dependency-injection` | Integration of Google Guice and Dagger with Azure Functions. |
| `spring-cloud` | Usage of Spring cloud to develop a Java function. |
| `distributed-tracing` | Sample that shows the usage of distributed tracing coupled with azure functions. |
| `durable-function` | Durable function example to run orchestrations and activities. |
| `.gitignore` | Define what to ignore at commit time. |
| `CHANGELOG.md` | List of changes to the sample. |
| `CONTRIBUTING.md` | Guidelines for contributing to the sample. |
| `README.md` | This README file. |
| `LICENSE.txt` | The license for the sample. |
## Prerequisites
- Gradle 4.10+
- Latest [Function Core Tools](https://aka.ms/azfunc-install)
- Azure CLI. This plugin use Azure CLI for authentication, please make sure you have Azure CLI installed and logged in.
## Setup
- Please refer individual directories for sample specific setup. Some common setup instructions are provided below.
- ```cmd
az login
az account set -s <your subscription id>
```
- Update the Application settings in Azure portal with the required parameters as below
- AzureWebJobsStorage: Connection string to your storage account
- CosmosDBDatabaseName: Cosmos database name. Example: ItemCollectionIn
- CosmosDBCollectionName:Cosmos database collection name. Example: ItemDb
- AzureWebJobsCosmosDBConnectionString: Connection string to your Cosmos database
- AzureWebJobsEventGridOutputBindingTopicUriString: Event Grid URI
- AzureWebJobsEventGridOutputBindingTopicKeyString: Event Grid string
- AzureWebJobsEventHubSender, AzureWebJobsEventHubSender_2 : Event hub connection string
- AzureWebJobsServiceBus: Service bus connection string
- SBQueueName: Service bus queue name. Example: test-input-java
- SBTopicName: Service bus topic name. Example: javaworkercitopic2
- SBTopicSubName: Service bus topic name. Example: javaworkercisub
- Documentation on how to [manage connection strings](https://docs.microsoft.com/en-gb/azure/storage/common/storage-account-keys-manage?tabs=azure-portal) and [access keys](https://docs.microsoft.com/en-gb/azure/storage/common/storage-configure-connection-string#create-a-connection-string-for-an-azure-storage-account)
- Update `host.json` with the right extension bundle version. `V3 - [1.*, 2.0.0) and V4 - [2.*, 3.0.0)`
## Running the sample
```cmd
./mvnw clean package azure-functions:run
```
```cmd
./gradlew clean azureFunctionsRun
```
## Deploy the sample on Azure
```cmd
./mvnw clean package azure-functions:deploy
```
```cmd
./gradlew clean azureFunctionsDeploy
```
> NOTE: please replace '/' with '\\' when you are running on windows.
## 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.opensource.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., status check, 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.
## Telemetry
This project collects usage data and sends it to Microsoft to help improve our products and services.
Read Microsoft's [privacy statement](https://privacy.microsoft.com/en-us/privacystatement) to learn more.
If you would like to opt out of sending telemetry data to Microsoft, you can set `allowTelemetry` to false in the plugin configuration.
Please read our [document](https://github.com/microsoft/azure-gradle-plugins/wiki/Configuration) to find more details about *allowTelemetry*.
| 1 |
aws-samples/serverless-java-frameworks-samples | null | null | ## Lambda demo with common Java application frameworks

This is a simple serverless application built in Java using popular frameworks — [Micronaut](https://micronaut.io/),
[Quarkus](https://quarkus.io/), and [Spring Boot](https://spring.io/projects/spring-boot)
It consists of an [Amazon API Gateway](https://aws.amazon.com/api-gateway/) backed by four [AWS Lambda](https://aws.amazon.com/lambda/)
functions and an [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) table for storage.
## Requirements
- [AWS CLI](https://aws.amazon.com/cli/)
- [AWS SAM](https://aws.amazon.com/serverless/sam/)
- Java:
- v17 — Micronaut, Quarkus, and Spring Boot
- v11 — Dagger
- [GraalVM](https://www.graalvm.org/) for Native builds
- Maven
- [Artillery](https://www.artillery.io/) for load-testing application
- Docker (at least 8GB memory and 4 CPUs)
## Software
Each of the sub folders contains a Product Maven project.
Each Maven project contains all the code for all four Lambda functions.
It uses the hexagonal architecture pattern to decouple the entry points from the main domain logic
and the storage logic.
## Infrastructure
The sample application can be deployed in three different ways:
1. Managed Java Runtime (without SnapStart) — This mode uses zip packaging style and runs on the JVM inside the Lambda environment.
2. Managed Java Runtime (with SnapStart) — This mode enables SnapStart on the Lambda functions.
Current examples only include Spring Boot and Quarkus versions of the application.
Stay tuned for other framework examples with SnapStart.
Learn more about SnapStart [here](https://docs.aws.amazon.com/lambda/latest/dg/snapstart.html).
3. Custom Runtime — This mode uses GraalVM native image and uses Custom Runtime to run on Lambda.
GraalVM native image is a stand-alone execution binary and does not require a JVM to run.
## Deployment and Testing
[Micronaut](micronaut)
[Quarkus](quarkus)
[Spring Boot](springboot)
[Dagger](dagger)
## Summary
Below is the cold start and warm start latencies observed.
Please refer to the "Load Test" section of each subproject for more details.
All latencies listed below are in milliseconds.
[Artillery](https://www.artillery.io/) is used to make **100 requests / second for 10 minutes to our API endpoints**.
### Results from Managed Java Runtime without SnapStart
<table class="table-bordered">
<tr>
<th colspan="1" style="text-align:center;"></th>
<th colspan="4" style="text-align:center;">Cold Start (ms)</th>
<th colspan="4" style="text-align:center;">Warm Start (ms)</th>
</tr>
<tr>
<th></th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
</tr>
<tr>
<th>Micronaut (Java 17)</th>
<td>4609.07</td>
<td>4943.09</td>
<td>5501.05</td>
<td>6657.94</td>
<td>8.52</td>
<td>14.31</td>
<td>32.52</td>
<td>314.99</td>
</tr>
<tr>
<th>Quarkus (Java 17)</th>
<td><b style="color: green">2525.22</b></td>
<td><b style="color: green">3146.27</b></td>
<td><b style="color: green">4055.57</b></td>
<td><b style="color: green">6343.83</b></td>
<td><b style="color: green">7.50</b></td>
<td><b style="color: green">12.28</b></td>
<td><b style="color: green">29.87</b></td>
<td><b style="color: green">231.52</b></td>
</tr>
<tr>
<th>Spring Boot (Java 17)</th>
<td>5311.93</td>
<td>5645.88</td>
<td>6183.47</td>
<td>7027.66</td>
<td>8.13</td>
<td>13.01</td>
<td>30.03</td>
<td>251.27</td>
</tr>
<tr>
<th>Dagger *</th>
<td>3213.00</td>
<td>3629.68</td>
<td>4850.11</td>
<td>6896.54</td>
<td>8.94</td>
<td>16.34</td>
<td>40.38</td>
<td>292.20</td>
</tr>
</table>
*: Dagger is not fully comparable to other frameworks as it only provides dependency injection, and thus is much lighter than the others, which explains these results.
When choosing a framework, be conscious of the features available. Dagger was initially done with Android in mind, to provide a lightweight dependency injection framework, without introspection (like Spring).
It fits particularly well with Lambda to reduce the initialization time, but does not provide the breadth of the others.
### Results from Managed Java Runtime with SnapStart enabled Lambda functions
<table class="table-bordered">
<tr>
<th colspan="1" style="text-align:center;"></th>
<th colspan="4" style="text-align:center;">Cold Start (ms)</th>
<th colspan="4" style="text-align:center;">Warm Start (ms)</th>
</tr>
<tr>
<th></th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
</tr>
<tr>
<th>Micronaut (Java 17)</th>
<td>726.11</td>
<td>815.37</td>
<td>931.30</td>
<td>1047.49</td>
<td>7.68</td>
<td>12.30</td>
<td>28.18</td>
<td>244.82</td>
</tr>
<tr>
<th>Quarkus (Java 17)</th>
<td><b style="color: green">487.31</b></td>
<td><b style="color: green">586.87</b></td>
<td><b style="color: green">732.67</b></td>
<td><b style="color: green">932.17</b></td>
<td><b style="color: green">7.38</b></td>
<td><b style="color: green">11.91</b></td>
<td><b style="color: green">25.20</b></td>
<td><b style="color: green">147.26</b></td>
</tr>
<tr>
<th>Spring Boot (Java 17)</th>
<td>1047.87</td>
<td>1200.45</td>
<td>1597.68</td>
<td>1779.53</td>
<td>7.62</td>
<td>13.01</td>
<td>27.73</td>
<td>262.25</td>
</tr>
</table>
### Results from GraalVM Native images running in custom runtime
<table class="table-bordered">
<tr>
<th colspan="1" style="text-align:center;"></th>
<th colspan="4" style="text-align:center;">Cold Start (ms)</th>
<th colspan="4" style="text-align:center;">Warm Start (ms)</th>
</tr>
<tr>
<th></th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
<th scope="col">p50</th>
<th scope="col">p90</th>
<th scope="col">p99</th>
<th scope="col">max</th>
</tr>
<tr>
<th>Micronaut (22.3.r17)</th>
<td>638.27</td>
<td>722.49</td>
<td>960.60</td>
<td>1416.85</td>
<td>7.56</td>
<td>12.11</td>
<td>23.46</td>
<td>1029.55</td>
</tr>
<tr>
<th>Quarkus (22.3.r17)</th>
<td>467.27</td>
<td>599.77</td>
<td>802.43</td>
<td>1348.78</td>
<td>6.7</td>
<td>11.63</td>
<td>24.03</td>
<td>168.47</td>
</tr>
<tr>
<th>Spring Boot</th>
<td>620.66</td>
<td>684.53</td>
<td>721.77</td>
<td>751.98</td>
<td>9.10</td>
<td>14.22</td>
<td>23.61</td>
<td>259.16</td>
</tr>
</table>
## 👀 With other languages
You can find implementations of this project in other languages here:
* [☕ Java (GraalVM)](https://github.com/aws-samples/serverless-graalvm-demo)
* [🦀 Rust](https://github.com/aws-samples/serverless-rust-demo)
* [🏗️ TypeScript](https://github.com/aws-samples/serverless-typescript-demo)
* [🐿️ Go](https://github.com/aws-samples/serverless-go-demo)
* [⭐ Groovy](https://github.com/aws-samples/serverless-groovy-demo)
* [🤖 Kotlin](https://github.com/aws-samples/serverless-kotlin-demo)
* [🥅 .NET](https://github.com/aws-samples/serverless-dotnet-demo)
## Security
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
## License
This library is licensed under the MIT-0 License. See the LICENSE file.
| 0 |
jcuda/jcuda-samples | JCuda samples | null | # jcuda-samples
This repository contains samples for the JCuda libraries.
**Note:** Some of the samples require third-party libraries, JCuda
libraries that are not part of the [`jcuda-main`](https://github.com/jcuda/jcuda-main)
package (for example, [`JCudaVec`](https://github.com/jcuda/jcuda-vec) or
[`JCudnn`](https://github.com/jcuda/jcudnn)), or utility libraries
that are not available in Maven Central. In order to compile these
samples, additional setup steps may be necessary. The main goal
of this repository is to collect and maintain the samples in a
form that allows them to serve as a collection of snippets that
can easily be copied and pasted into own projects to get started.
| 0 |
CyberSource/cybersource-rest-samples-java | Java sample code for the CyberSource REST API | null | # Java Sample Code for the CyberSource SDK
[](https://app.travis-ci.com/CyberSource/cybersource-rest-samples-java)
This repository contains working code samples which demonstrate Java integration with the CyberSource REST APIs through the [CyberSource Java SDK](https://github.com/CyberSource/cybersource-rest-client-java).
The samples are organized into categories and common usage examples.
## Using the Sample Code
The samples are all completely independent and self-contained. You can analyze them to get an understanding of how a particular method works, or you can use the snippets as a starting point for your own project.
### Clone (or download) this repository
```bash
git clone https://github.com/CyberSource/cybersource-rest-samples-java
```
### Running the Samples using IntelliJ IDE
* Open the project/folder (rather than import or new).
* Build the project:
* From the Build menu, select Rebuild Project.
* Run any sample:
* For example, select `SimpleAuthorizationInternet` class from the class Explorer
* Right-click and select Run `SimpleAuthorizationInternet.Main()`
### Running the Samples using Eclipse IDE
* Import the project:
* From File menu, select Import.
* Expand Maven menu.
* And click Existing Maven Projects
* Click next and browse the location where you have the Maven project source code.
* Click next, Eclipse will recognize the Maven project and it will show you a list of all possible Maven projects located there.
* Just select the project and click next.
* Eclipse will show you a Maven Build message. Just click finish.
* The Maven project is successfully imported into Eclipse IDE.
* Run the project:
* Right-click the project folder.
* Select Run as Maven Build.
* In the Goals field, enter "clean install"
* Select the JRE tab and make sure it is pointing at a JRE associated with a JDK.
* Click Run.
## Setting Your API Credentials
To set your API credentials for an API request, configure the following information in `src/main/java/data/Configuration.java` file:
* Http Signature
```java
authenticationType = http_Signature
merchantID = your_merchant_id
merchantKeyId = your_key_serial_number
merchantsecretKey = your_key_shared_secret
useMetaKey = false
enableClientCert = false
```
* Jwt
```java
authenticationType = jwt
merchantID = your_merchant_id
keyAlias = your_merchant_id
keyPass = your_merchant_id
keyFileName = your_merchant_id
keysDirectory = resources
useMetaKey = false
enableClientCert = false
```
* MetaKey Http
```java
authenticationType = http_Signature
merchantID = your_child_merchant_id
merchantKeyId = your_metakey_serial_number
merchantsecretKey = your_metakey_shared_secret
portfolioId = your_portfolio_id
useMetaKey = true
enableClientCert = false
```
* MetaKey JWT
```java
authenticationType = jwt
merchantID = your_child_merchant_id
keyAlias = your_child_merchant_id
keyPass = your_portfolio_id
keyFileName = your_portfolio_id
portfolioId = your_portfolio_id
keysDirectory = resources
useMetaKey = true
enableClientCert = false
```
* OAuth
CyberSource OAuth uses mutual authentication. A Client Certificate is required to authenticate against the OAuth API.
Refer to [Supporting Mutual Authentication](https://developer.cybersource.com/api/developer-guides/OAuth/cybs_extend_intro/Supporting-Mutual-Authentication.html) to get information on how to generate Client certificate.
If the certificate (Public Key) and Private Key are in 2 different files, merge them into a single .p12 file using `openssl`.
```bash
openssl pkcs12 -export -out certificate.p12 -inkey privateKey.key -in certificate.crt
```
Set the run environment to OAuth enabled URLs. OAuth only works in these run environments.
```java
// For TESTING use
runEnvironment = api-matest.cybersource.com
// For PRODUCTION use
// runEnvironment = api-ma.cybersource.com
```
To generate tokens, an Auth Code is required. The Auth Code can be generated by following the instructions given in [Integrating OAuth](https://developer.cybersource.com/api/developer-guides/OAuth/cybs_extend_intro/integrating_OAuth.html).
This generated Auth Code can then be used to create the Access Token and Refresh Token.
In `src/main/java/data/Configuration.java` file, set the following properties.
Note that `authenticationType` is set to `MutualAuth` only to generate the Access Token and the Refresh Token.
```java
authenticationType = MutualAuth
enableClientCert = true
clientCertDirectory = resources
clientCertFile = your_client_cert in .p12 format
clientCertPassword = password_for_client_cert
clientId = your_client_id
clientSecret = your_client_secret
```
Once the tokens are obtained, the `authenticationType` can then be set to `OAuth` to use the generated Access Token to send requests to other APIs.
```java
authenticationType = OAuth
enableClientCert = true
clientCertDirectory = resources
clientCertFile = your_client_cert - .p12 format
clientCertPassword = password_for_client_cert
clientId = your_client_id
clientSecret = your_client_secret
accessToken = generated_access_token
refreshToken = generated_refresh_token
```
The Access Token is valid for 15 mins, whereas the Refresh Token is valid for 1 year.
Once the Access Token expires, use the Refresh Token to generate another Access Token.
Refer to [StandAloneOAuth.java](https://github.com/CyberSource/cybersource-rest-samples-java/blob/master/src/main/java/samples/authentication/AuthSampleCode/StandaloneOAuth.java) to understand how to consume OAuth.
For further information, refer to the documentation at [Cybersource OAuth 2.0](https://developer.cybersource.com/api/developer-guides/OAuth/cybs_extend_intro.html).
## Run Environments
The run environments that were supported in CyberSource Java SDK have been deprecated.
Moving forward, the SDKs will only support the direct hostname as the run environment.
For the old run environments previously used, they should be replaced by the following hostnames:
| Old Run Environment | New Hostname Value |
|-----------------------------------------------|------------------------------------------------|
|`cybersource.environment.sandbox` |`apitest.cybersource.com` |
|`cybersource.environment.production` |`api.cybersource.com` |
|`cybersource.environment.mutualauth.sandbox` |`api-matest.cybersource.com` |
|`cybersource.environment.mutualauth.production`|`api-ma.cybersource.com` |
|`cybersource.in.environment.sandbox` |`apitest.cybersource.com` |
|`cybersource.in.environment.production` |`api.in.cybersource.com` |
For example, replace the following code in the Configuration file:
```java
// For TESTING use
runEnvironment = CyberSource.Environment.SANDBOX
// For PRODUCTION use
// runEnvironment = CyberSource.Environment.PRODUCTION
```
with the following code:
```java
// For TESTING use
runEnvironment = apitest.cybersource.com
// For PRODUCTION use
// runEnvironment = api.cybersource.com
```
## Switching between the sandbox environment and the production environment
CyberSource maintains a complete sandbox environment for testing and development purposes. This sandbox environment is an exact duplicate of our production environment with the transaction authorization and settlement process simulated. By default, this SDK is configured to communicate with the sandbox environment. To switch to the production environment, set the appropriate environment constant in resources/cybersource.properties file. For example:
```java
// For TESTING use
runEnvironment = apitest.cybersource.com
// For PRODUCTION use
// runEnvironment = api.cybersource.com
```
To use OAuth, switch to OAuth enabled URLs
```java
// For TESTING use
runEnvironment = api-matest.cybersource.com
// For PRODUCTION use
// runEnvironment = api-ma.cybersource.com
```
The [API Reference Guide](https://developer.cybersource.com/api/reference/api-reference.html) provides examples of what information is needed for a particular request and how that information would be formatted. Using those examples, you can easily determine what methods would be necessary to include that information in a request
using this SDK.
| 1 |
SolaceSamples/solace-samples-java-jcsmp | Getting Started Samples for the Solace JCSMP Java API. | java solace solace-samples | # Getting Started Examples
## Solace Messaging API for Java JCSMP
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://console.solace.cloud/login/new-account?product=tutorials) 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 five different basic Solace messaging patterns. For a nice introduction to the Solace API and associated tutorials, check out the [tutorials home page](https://tutorials.solace.dev/jcsmp/).
See the individual tutorials for details:
- [Publish/Subscribe](https://tutorials.solace.dev/jcsmp/publish-subscribe): Learn how to set up pub/sub messaging on a Solace VMR.
- [Persistence](https://tutorials.solace.dev/jcsmp/persistence-with-queues): Learn how to set up persistence for guaranteed delivery.
- [Request/Reply](https://tutorials.solace.dev/jcsmp/request-reply): Learn how to set up request/reply messaging.
- [Confirmed Delivery](https://tutorials.solace.dev/jcsmp/confirmed-delivery): Learn how to confirm that your messages are received by a Solace message router.
- [Topic to Queue Mapping](https://tutorials.solace.dev/jcsmp/topic-to-queue-mapping): Learn how to map existing topics to Solace queues.
## Prerequisites
This tutorial requires the Solace Java API library. Download the Java API library to your computer from [here](solace.com/downloads/).
## Build the Samples
Just clone and build. For example:
1. clone this GitHub repository
```
git clone https://github.com/SolaceSamples/solace-samples-java-jcsmp
cd solace-samples-java-jcsmp
```
2. Build samples
```
./gradlew assemble
```
## Running the Samples
To try individual samples, build the project from source and then run samples like the following:
```
cd build/staged
bin/DirectSubscriber <host:port> <message-vpn> <client-username> [password]
bin/DirectPublisher <host:port> <message-vpn> <client-username> [password]
```
The individual tutorials linked above provide full details which can walk you through the samples, what they do, and how to correctly run them to explore Solace messaging.
## 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-jcsmp'* 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
## JCSMP API Logging and log4j2
The Solace JCSMP API uses Apache Commons Logging (JCL) (formerly _Jarkarta_ Commons Logging), and is therefore compatible to use with logging frameworks like log4j2.
Specifically, these samples use the [Commons Logging Bridge](https://logging.apache.org/log4j/log4j-2.4/log4j-jcl/index.html) to bridge logging data from JCL to log4j2.
You can see the required log4j2 dependencies inside the `build.gradle` file, and the configuration file in `src/dist/config/`. Log4j2 easily allows you to configure various outputs such
as console, file, and many others (e.g. JMS!) for all of the JCSMP API logs.
It is best practice to ensure whatever logging implementation you use, that it is configurable at runtime without having to recompile and redeploy.
In the included log configuration file `src/dist/config/log4j2.xml` there are various logging levels that can be configured using JVM system variables. For example,
use `-Djcsmp_api_log_level=debug` to set the API logging to debug. If using the Gradle run scripts, use the convinience environment variable `JAVA_OPTS`. E.g.:
```
export JAVA_OPTS=-Djcsmp_api_log_level=debug
```
## 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-java-jcsmp/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://solace.com/blog/) for other interesting discussions around Solace technology
- Ask the [Solace community.](https://solace.community)
| 0 |
cwensel/cascading.samples | Sample applications using Cascading | null | null | 1 |
opennetworkinglab/onos-app-samples | Sample applications for onos | null | ONOS : Open Network Operating System
====================================
### Sample Applications
This repository contains sample and testing applications for ONOS.
### What is ONOS?
ONOS is a new SDN network operating system designed for high availability,
performance, scale-out.
You can find the main project repository here:
https://github.com/opennetworkinglab/onos
### Where can I learn more about ONOS?
Checkout out our [website](http://www.onosproject.org) and our
[tools](http://www.onosproject.org/software/#tools)
| 1 |
yavijava/yavijava-samples | pulled the vijava samples into its own stand alone project | null | null | 0 |
sofastack/spring-cloud-sofastack-samples | Spring Cloud ❤️ SOFAStack | null | # Samples of Spring Cloud & SOFAStack
spring-cloud-sofastack-samples 是基于 SOFAStack 和 SpringCloud 构建的一套微服务系统,希望通过此案例工程,能够用于提供一个完整的基于 SOFA 和 SpringCloud 体系构建的基础的工程模型,帮助用于更好的理解和使用 SOFAStack 开源生态提供的一系列基础框架和组件。
本案例工程主要包括以下几个核心应用:
* sofastack-cloud-api-gateway:服务网关系统,所有的业务请求都会经过此系统,主要包括限流、鉴权功能
* sofastack-cloud-biz-web:核心业务系统,用于处理经过网关路由过来的请求,然后再由此系统进行业务功能处理
* sofastack-cloud-sys-auth:注册、登录、权限认证系统
* sofastack-cloud-sys-user:用户中心系统,用于提供用户相关服务
* sofastack-cloud-sys-accounting:用户账户系统,用于提供账户相关服务和定时生成账单
* sofastack-cloud-sys-trading:交易系统,用于处理用户交易逻辑、订单处理等
* sofastack-cloud-sys-mq-server:kafka 消息消费端应用,用于消费消息并且发送邮件
* sofastack-cloud-sys-static:静态资源系统
## 应用架构图

## 快速开始
```bash
git clone https://github.com/sofastack/spring-cloud-sofastack-samples.git
cd spring-cloud-sofastack-samples/script/bin && sh deploy.sh
```
运行示例参考:[操作手册](https://github.com/sofastack/spring-cloud-sofastack-samples/wiki/%E5%B7%A5%E7%A8%8B%E8%BF%90%E8%A1%8C#%E6%93%8D%E4%BD%9C%E7%A4%BA%E4%BE%8B)
## 工程共建
为了能够让更多对 SOFAStack 和 SpringCloud 体系有兴趣的同学参与,本案例工程希望通过内外部共建的方式进行开发。欢迎各路大神基于此工程,使用 SOFAStack 和 SpringCloud 大展身手。
* 如果您对此工程或者技术栈感兴趣,欢迎 Star & Watch
* 如果您希望参与此工程开发共建,欢迎 Fork & PR
| 0 |
shipilev/jdk8-lambda-samples | JDK8 Lambda Samples | null | null | 0 |
chrishantha/sample-java-programs | Sample Java programs to demonstrate performance issues | allocations flight-recording highcpu hotmethods java latencies memory-leak samples | [](https://travis-ci.org/chrishantha/sample-java-programs)
Sample Java Programs
====================
This repository contains some sample programs. All are Maven projects and can be run directly using "java -jar"
## How to build
Run `mvn clean install` to build all sample programs
## License
Copyright (C) 2015 M. Isuru Tharanga Chrishantha Perera
Licensed under the Apache License, Version 2.0
| 1 |
Azure-Samples/ms-identity-msal-java-samples | null | null | ---
languages:
- java
products:
- msal-java
- azure
- entra
page_type: sample
urlFragment: introduction-msal-java
description: "Securing Java apps using the Microsoft Identity platform and MSAL Java"
---
# Securing Java apps using the Microsoft Identity platform and MSAL Java
## About these samples
### Scenarios
The Microsoft Authentication Library (MSAL) enables developers to acquire tokens from the Microsoft identity platform, allowing applications to authenticate users and access secured web APIs. It can be used to provide secure access to Microsoft Graph, other Microsoft APIs, third-party web APIs, or your own web API.
This collection of samples covers a number of scenarios where MSAL Java can be used to secure Java applications, and is meant to build an understanding of [MSAL Java](https://learn.microsoft.com/entra/msal/java/) and demonstrate how to integrate the library into your applications.
### Prerequisites
- [JDK Version 8](https://jdk.java.net/8/)
- [Maven 3](https://maven.apache.org/download.cgi)
These are the basic prerequisites for each sample, though each sample may specify more in their own `README`.
### Structure of the repository
This repository contains scenario-specific samples and comprehensive tutorials. We recommend starting with the [MSAL Java documentation](https://learn.microsoft.com/entra/msal/java/) to get familiar with MSAL Java, and then try out the samples that best fit your use case.
Chapters 1 and 2 are collections of samples covering specific use cases which demonstrate how to integrate MSAL Java into your application, and chapters 3 and 4 are more comprehensive tutorials demonstrating how to create simple and secure web apps from scratch.
## Samples and Documentation
### [1. Server-Side Scenarios](1-server-side/README.md)
This chapter offers samples covering server-side scenarios, in which the app runs on a server and serves multiple users. These samples demonstrate securing web apps and accessing web APIs, and creating secure daemon services that can access resources on behalf of your users.
### [2. Client-Side Scenarios](2-client-side/README.md)
This chapter offers samples covering client-side scenarios where the app runs on a user's device, such as with desktop or mobile apps.
### [3. Java Servlet Web App Tutorial](3-java-servlet-web-app/README.md)
A tutorial demonstrating how to create a web app using MSAL Java and Java servlets.
### [4. Spring Framework Web App Tutorial](4-spring-web-app/README.md)
A tutorial demonstrating how to create an MVC web app using MSAL Java alongside the Spring framework.
## Community Help and Support
Use [Stack Overflow](http://stackoverflow.com/questions/tagged/msal) to get support from the community. Ask your questions on Stack Overflow first and browse [existing issues](https://github.com/Azure-Samples/ms-identity-msal-java-samples/issues) to see if someone has asked your question before. Tag your questions or comments with `msal` and `java`.
If you find a bug in the sample, please [open an issue](https://github.com/Azure-Samples/ms-identity-msal-java-samples/issues).
## Contributing
Thank you for your interest in contributing to Azure samples!
You can contribute to [Azure samples](https://azure.microsoft.com/documentation/samples/) in a few different ways:
- Submit issues through [issue tracker](https://github.com/Azure-Samples/ms-identity-msal-java-samples/issues) on GitHub. We are actively monitoring the issues and improving our samples.
- If you wish to make code changes to samples or contribute something new, please follow the [GitHub forks/pull request model](https://help.github.com/articles/fork-a-repo/) - fork the sample repo, make the change, and propose it back by submitting a pull request.
## Code of Conduct
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.
| 0 |
spring-cloud-samples/spring-cloud-circuitbreaker-demo | Samples demonstrating how to using Spring Cloud Circuitbreaker | circuit-breaker samples spring spring-cloud spring-cloud-circuitbreaker | # About
This repo contains a collection of apps that demonstrate how to using Spring Cloud CircuitBreaker
with various circuit breaker implementations.
# Non-Reactive Samples
The non-reactive example can be found in `spring-cloud-circuitbreaker-resilience4j`.
When these apps are running there are two endpoints available for testing
1. `/get` - This endpoint makes a request to [httpbin's `/get` endpoint](http://httpbin.org/#/HTTP_Methods/get_get) and returns the data
2. `/delay/{seconds}` - This endpoint makes a request to [httpbin's `/delay` endpoint](http://httpbin.org/#/Dynamic_data/get_delay__delay_) passing
the delay in the response in seconds. Since this request can take a significant amount
of time it is wrapped in a circuit breaker. If the `seconds` parameter is greater than or
equal to 3 the circuit breaker will time out and return the response `{"hello": "world"}`.
# Reactive Samples
There are two reactive samples in this repo, `spring-cloud-circuitbreaker-demo-reactive` and `spring-cloud-circuibreaker-demo-reactive-resilience4j`.
## Resilience4J Reactive Samples
Both of these samples contain the same two endpoints as the non-reactive samples
(which in this case return a `Mono`), but also
contain an additional endpoint to demonstrate the use of `Flux`. This endpoint can be
accessed by calling `/fluxdelay/{seconds}`. It has the same functionality as `/delay/{seconds}`
but the fallback returns a `Flux`.
## spring-cloud-circuitbreaker-demo-reactive
This sample demonstrates how to using Spring Cloud CircuitBreaker with reactive types from
RxJava2 and CompletableFuture. There are four endpoints available for testing in this app
1. `/rxjava2/get`
2. `/rxjava2/delay/{seconds}`
3. `/completablefuture/get`
4. `/completablefuture/delay/{seconds}`
Each of these have the same functionality as the other endpoints in the other apps.
# Resilience4J and Metrics
With Spring Cloud CircuitBreaker and Resilience4J you can easily collect metrics about
the circuit breakers in your app. This is demoed in both `spring-cloud-circuitbreaker-demo-resilience4j`
and `spring-cloud-circuitbreaker-demo-reactive-resilience4j`. You can see the metrics available
by hitting `/actuator/metrics`.
NOTE: The code wrapped by the circuit breaker needs to be executed before any metrics appear
You can also have these metrics collected by Prometheus and visualized in Grafana. To demonstrate
this, the repo contains a Docker Compose file that will start Prometheus and Grafana locally
and scrape the metrics being surfaces at `/actuator/prometheus`. To see it in action
1. Start either `spring-cloud-circuitbreaker-demo-resilience4j` or `spring-cloud-circuitbreaker-demo-reactive-resilience4j`.
2. `cd` into the `grafana` directory in the root of the repo
3. Run `docker-compose up`
4. Go to http://localhost:3000 and login with the username `admin` and the password `admin`
5. There will be a datasource pointing to the docker container running Prometheus and dashboard already configured to visualize the Resilience4J metrics
6. Make some requests to the `/delay` endpoint. You can easily do this with a tool like `watch`.
For example `watch -n 1 http :8080/delay/5`.
7. If you refresh the Grafana dashboard or set its automatic refresh you should see the graphs begin to change
as requests are made.
| 0 |
seomoz/SEOmozAPISamples | Mozscape API sample code | null | Mozscape API Sample Code
========================
Welcome to the Mozscape API sample code. Please let us know if you
have any questions and send along any examples you'd like to
contribute.
| 1 |
Bukkit/SamplePlugin | Bukkit Sample Plugin | null | null | 1 |
AuthorizeNet/sample-code-java | This repository contains working code samples which demonstrate java integration with the Authorize.Net API | null | # Java Sample Code for the Authorize.Net SDK
[](https://travis-ci.org/AuthorizeNet/sample-code-java)
This repository contains working code samples which demonstrate Java integration with the [Authorize.Net Java SDK](https://www.github.com/AuthorizeNet/sdk-java).
The samples are organized into categories and common usage examples, just like our [API Reference Guide](http://developer.authorize.net/api/reference). Our API Reference Guide is an interactive reference for the Authorize.Net API. It explains the request and response parameters for each API method and has embedded code windows to allow you to send actual requests right within the API Reference Guide.
## Using the Sample Code
The samples are all completely independent and self-contained. You can analyze them to get an understanding of how a particular method works, or you can use the snippets as a starting point for your own project.
You can also run each sample directly from the command line.
## Running the Samples From the Command Line
* Clone this repository:
```
$ git clone https://github.com/AuthorizeNet/sample-code-java.git
```
* Run "mvn package" in the root directory to create the SampleCode console app.
* Run the individual samples by name. For example:
```
> java -jar target/SampleCode.jar [CodeSampleName]
```
e.g.
```
> java -jar target/SampleCode.jar ChargeCreditCard
```
Running SampleCode without a parameter will give you the list of sample names.
**NOTE : You can update to your Sandbox credentials in SampleCode.java**
**For using behind proxy**
Please set the JAVA environment proxy using a similar code :
```
System.setProperty(Constants.HTTPS_USE_PROXY, "true");
System.setProperty(Constants.HTTPS_PROXY_HOST, "127.0.0.1");
System.setProperty(Constants.HTTPS_PROXY_PORT, "8888");
```
**For using proxy authentication**
Please set the JAVA environment proxy credentials using a similar code :
```
System.setProperty(Constants.HTTPS_PROXY_USERNAME, "exampleUsername");
System.setProperty(Constants.HTTPS_PROXY_PASSWORD, "examplePassword");
```
| 0 |
Watson-Explorer/wex-wdc-integration-samples | Sample code and tutorials for integrating Watson Explorer with Watson Developer Cloud services on Bluemix | null | All future sample code, including updates to the samples originall provided here, are maintained in the [IBM Watson repos on GitHub](https://github.com/ibm-watson). This includes the following repositories of interest, originally from this project:
* [WEX Application Builder Samples](https://github.com/IBM-Watson/wex-appbuilder-samples)
* [WEX with Personality Insights Example](https://github.com/IBM-Watson/wex-appbuilder-samples/tree/master/personality_insights)
* [Application Builder Sample Proxy](https://github.com/IBM-Watson/wex-appbuilder-sample-proxy)
* [And many other interesting Watson Explorer samples, examples, and applications](https://github.com/ibm-watson?utf8=%E2%9C%93&query=wex)
For help getting started with using [Watson Explorer and Bluemix, there is an introduction guide available](https://github.com/IBM-Watson/wex-appbuilder-samples/blob/master/intro-to-bluemix-for-app-builder.md).
## Licensing
All sample code contained within this project repository or any subdirectories is licensed according to the terms of the MIT license, which can be viewed in the file license.txt.
## Open Source @ IBM
[Find more open source projects on the IBM Github Page](http://ibm.github.io/)
| 1 |
nitsanw/jmh-samples | JMH examples with my own examples + jar etc | null | jmh-samples
===========
<b>NOTE: As of 15/06/2013 the jar/samples were up to date. JMH has come a long way since and is much easier to play with.<br/>
I have now removed the old jar/samples and use the maven hosted dependency instead.<br/></b>
JMH samples.<br/>
This was setup to support my 2 blog posts about JMH:<br/>
http://psy-lob-saw.blogspot.com/2013/05/using-jmh-to-benchmark-multi-threaded.html<br/>
http://psy-lob-saw.blogspot.com/2013/04/writing-java-micro-benchmarks-with-jmh.html<br/>
And contains the examples discussed under the psy.lob.saw package.<br/>
The JMH framework is hosted here: http://openjdk.java.net/projects/code-tools/jmh/<br/>
The JMH samples are a MUST read (and are always up to date): http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/<br/>
| 0 |
web3j/sample-project-gradle | Sample web3j project using Gradle | blockchain ethereum gradle java web3j | # web3j Sample Project
This project provides a very simple starter application for working with web3j and the test
Ethereum network (testnet) known as Rinkeby.
The demo deploys a *hello world* smart contract which contains a greeting message. The current
greeting message can be read and modified in the smart contract.
In order to run this demo, three pieces of information are required:
1. Ethereum client (or node) endpoint. The simplest thing to do is
[request a free access token](https://infura.io/register) from Infura.
1. A wallet file. This can be generated using the [Epirus CLI](https://docs.epirus.io/sdk/cli/).
1. Some Ether. This can be requested from the [Rinkeby Faucet](https://www.rinkeby.io/#faucet).
Once these details have been added to the main Application class, you'll be good to go.
## Functionality
This application demonstrates a number of core features of web3j and Ethereum:
- Connecting to a node on the Ethereum network
- Loading an Ethereum wallet file
- Sending Ether from one address to another
- Deploying a smart contract to the network
- Reading a value from the deployed smart contract
- Updating a value in the deployed smart contract
- Viewing an event logged by the smart contract
## Background
This application has purposefully been kept as simple as possible with the aim of demonstrating
how to deploy and work with a smart contract on the decentralised Ethereum network.
If you require further background information about the above configuration items for the project
you can refer to the below.
For a more comprehensive overview, I recommend you read the
[Java Magazine Article](https://web3j.io/articles/web3j%20article%20-%20Java%20Magazine%20JanuaryFebruary%202017.pdf), watch
the
[YouTube](https://youtube.com/watch?v=ea3miXs_P6Y) talk, and read all of the
[documentation](https://docs.web3j.io).
### Smart contracts
The contained smart contract is based on the
[Greeter contract example](https://www.ethereum.org/greeter), with the addition that the value
stored in the Greeter can be modified.
The associated Java smart contract wrapper is named Greeter.
For more background on smart contracts, refer to the
[smart contracts](https://docs.web3j.io/smart_contracts/) section of the docs.
### Infura
If you don't want to sign up to Infura, and would like to run a node yourself, there are
instructions in the [getting started](https://docs.web3j.io/getting_started/#start-a-client)
section of the docs.
### Testnets
For more information on the different Ethereum test networks (or testnets), refer
to the
[testnet overview](https://docs.web3j.io/transactions/#ethereum-testnets) in the docs.
### Ether
For background on Ether, refer to the transactions
[overview](https://docs.web3j.io/transactions/#transactions) section of the docs.
### Wallets and transaction signing
For a more technical overview of working with wallet files, refer to the
[Offline transaction signing](https://docs.web3j.io/transactions/#offline-transaction-signing)
section of the docs.
## Viewing requests
A logback configuration is included in the project dependencies allowing the logging of protocol
messages if required. To enable, simply change the following line in the [logback configuration](https://github.com/web3j/sample-project-maven/blob/master/src/main/resources/logback.xml)
to read:
```xml
<logger name="org.web3j.protocol" level="DEBUG"/>
```
| 1 |
jenkinsci/simple-build-for-pipeline-plugin | sample Jenkinsfile | null | # Jenkinsfile - making the easy things easy
This plugin aims to build out a DSL for Jenkinfile (pipeline as code) to make the easy things easy, without taking away any of the power of Jenkins Pipeline for when you really need it.
[](https://jenkins.ci.cloudbees.com/job/plugins/job/simple-build-for-pipeline-plugin/)
# Example
This example runs a very simple build with some environment variables. This would work with pipeline-as-code and branch source.
This should be familiar and declarative-ish looking to anyone familiar with tools like .travis.yml, however, it is implemented as a pipeline DSL (so you can do all the other powerful pipeline things).
```
simpleBuild {
env = [
FOO : 42,
BAR : "YASS"
]
before_script = "echo before"
script = 'echo after $FOO'
notifications = [
email : "mneale@cloudbees.com"
]
}
```
It will do the right thing, and send emails when things break.
Optional things: You can specify a machine label, and/or a docker image to run builds under:
```
machine = "hi-speed"
docker_image = "java:1.9"
```
See src/main/resources for the actual DSL used for the details.
To play with this:
`mvn hpi:run`
or build and install it to your Jenkins (it is just a plugin). You can also commit the simpleBuild.groovy to the Jenkins workflowLibs repo (if you know what I mean, if not... then ignore me!).
# Secondary aim
The secondary aim of this plugin is to show how plain pipeline-script can be used easily to make a plugin to allow you to share the DSL.
The only code you need to care about is the `src/main/resources/dslsimpleBuild.groovy` and `SimpleBuildDSL.java` - that is all.
# TODO
- [ ] More scenario tests of the permutations
- [ ] Use named stages (?) if it makes sense.
- [ ] Support all the same _script semantics as https://github.com/jenkinsci/simple-travis-runner-plugin/blob/pure-script-approach/README.md (eg after_failure, after_success etc to happen on the appropriate events and around error handling).
- [ ] Allow execution of all `script` entries even if one fails (?)
- [ ] Time out individual `script` entries.
- [ ] Add in simple matrix (a la travis)
- [ ] Add in branch inclusions/exclusions (what branches to run on or not)
- [ ] Allow parallel scripts (across nodes?? or a whole block of parallel?)
- [ ] Implement auto-generation of `script` and friends for (some) languages? Debatable whether to do this.
- [ ] Decide whether to keep emulating Travis's behavior of ignore `after_*` steps' failures when setting build status.
- [ ] allow block for simple user input
- [ ] More notification types (slack, for example)
- [ ] Change email to only be on failure or return to health (convention, Yo).
- [ ] Retries of scripts if specified
- [ ] May need to configure docker to work under a node() block...
| 1 |
Mike-bel/TbsFileSamples | 基于腾讯浏览服务实现应用内打开 Office 文件功能的使用案例。 | null | # TbsFileSamples
基于腾讯浏览服务实现 Android 应用内打开 Office 文件功能的使用案例。
# 实现效果
<img src="samples.gif" height="300"></img>
# 详细介绍
[http://yifeng.studio](http://yifeng.studio/)
| 0 |
vmware/vsphere-automation-sdk-java | Java samples, language bindings, and API reference documentation for vSphere, VMC, and NSX-T using the VMware REST API | api-client bindings documentation java restful-api samples vmware-vsphere | # VMware vSphere Automation SDK for Java
## Table of Contents
- [Abstract](#abstract)
- [Supported vCenter Releases](#supported-vcenter-releases)
- [Table of Contents](#table-of-contents)
- [Quick Start Guide](#quick-start-guide)
- [Setting up maven](#setting-up-maven)
- [Setting up a vSphere Test Environment](#setting-up-a-vsphere-test-environment)
- [Building the Samples](#building-the-samples)
- [Running the Samples](#running-the-samples)
- [Importing the samples to eclipse](#importing-the-samples-to-eclipse)
- [API Documentation](#api-documentation)
- [Support](#support)
- [Submitting samples](#submitting-samples)
- [Required Information](#required-information)
- [Suggested Information](#suggested-information)
- [Contribution Process](#contribution-process)
- [Code Style](#code-style)
- [Resource Maintenance](#resource-maintenance)
- [Maintenance Ownership](#maintenance-ownership)
- [Filing Issues](#filing-issues)
- [Resolving Issues](#resolving-issues)
- [VMware Sample Exchange](#vmware-sample-exchange)
- [Repository Administrator Resources](#repository-administrator-resources)
- [Board Members](#board-members)
- [Approval of Additions](#approval-of-additions)
- [VMware Resources](#vmware-resources)
## Abstract
This document describes the vSphere Automation Java SDK samples that use the vSphere Automation
java client library. Additionally, some of the samples demonstrate the combined use of the
vSphere Automation and vSphere Web Service APIs. The samples have been developed to work with
JDK 1.8+
## Supported OnPrem vCenter Releases:
vCenter 7.0, 7.0U1, 7.0U2, 7.0U3, 8.0, 8.0U1 and 8.0U2
Please refer to the notes in each sample for detailed compatibility information.
## Supported NSX-T Releases
NSX-T 2.2, 2.3, 3.0, 4.0.0.0, 4.0.1
## Latest VMware Cloud on AWS Release:
VMC M24 (1.24) ([Release Notes](https://docs.vmware.com/en/VMware-Cloud-on-AWS/0/rn/vmc-on-aws-relnotes.html))
## Quick Start Guide
This document will walk you through getting up and running with the Java SDK Samples. Prior to running the samples you will need to setup a vCenter test environment and install maven, the following steps will take you through this process.
Before you can run the SDK samples we'll need to walk you through the following steps:
1. Setting up maven
2. Setting up a vSphere test environment
### Setting up maven
The SDK requires maven to build the samples.
1. Download the latest maven from <https://maven.apache.org/download.cgi> and extract it to your machine.
2. Install JDK 8 and set JAVA_HOME to the directory where JDK is installed.
```` bash
export JAVA_HOME=<jdk-install-dir>
````
3. Update PATH environment variable to include the maven and jdk "bin" directories.
```` bash
export PATH=<maven-bin-dir>:$JAVA_HOME/bin:$PATH
````
### Setting up a vSphere Test Environment
**NOTE:** The samples are intended to be run against a freshly installed **non-Production** vSphere setup as the scripts may make changes to the test environment and in some cases can destroy items when needed.
To run the samples a vSphere test environment is required with the following minimum configuration
* 1 vCenter Server
* 2 ESX hosts
* 1 NFS Datastore with at least 3GB of free capacity
Apart from the above, each individual sample may require additional setup. Please refer to the sample parameters for more information on that.
### Building the Samples
In the root directory of your folder after cloning the repository, run the below maven commands -
```` bash
mvn initialize
mvn clean install
````
### Running the Samples
When running the samples, parameters can be provided either on the command line, in a configuration file (using the --config-file parameter), or a combination of both. The parameter values specified on the command line will override those specified in the configuration file. When using a configuration file, each required parameter for the sample must be specified either in the configuration file or as a command line parameter. Each parameter specified in the configuration file should be in the "key=value" format. For example:
`vmname=TestVM`
`cluster=Cluster1`
**Note:** Please specify the fully qualified “hostname” of the server for running the samples to avoid hostname verification errors.
Use a command like the following to display usage information for a particular sample.
```` bash
$java -ea -cp target/vsphere-samples-8.0.2.1.jar vmware.samples.vcenter.vm.list.ListVMs
java -cp target/vsphere-samples-8.0.2.1.jar vmware.samples.vcenter.vm.list.ListVMs [--config-file <CONFIGURATION FILE>]
--server <SERVER> --username <USERNAME> --password <PASSWORD> --cluster <CLUSTER> [--truststorepath <ABSOLUTE PATH OF JAVA TRUSTSTORE FILE>]
[--truststorepassword <JAVA TRUSTSTORE PASSWORD>] [--cleardata] [--skip-server-verification]
Sample Options:
--config-file <CONFIGURATION FILE> OPTIONAL: Absolute path to the configuration file containing the sample options.
NOTE: Parameters can be specified either in the configuration file or on the command
line. Command line parameters will override values specified in the configuration file.
--server <SERVER> hostname of vCenter Server
--username <USERNAME> username to login to the vCenter Server
--password <PASSWORD> password to login to the vCenter Server
--truststorepath <ABSOLUTE PATH OF JAVA TRUSTSTORE FILE> Specify the absolute path to the file containing the trusted server certificates. This
option can be skipped if the parameter skip-server-verification is specified.
--truststorepassword <JAVA TRUSTSTORE PASSWORD> Specify the password for the java truststore. This option can be skipped if the
parameter skip-server-verification is specified.
--cleardata OPTIONAL: Specify this option to undo all persistent results of running the sample.
--skip-server-verification OPTIONAL: Specify this option if you do not want to perform SSL certificate
verification.
NOTE: Circumventing SSL trust in this manner is unsafe and should not be used with
production code. This is ONLY FOR THE PURPOSE OF DEVELOPMENT ENVIRONMENT.
````
Use a command like the following to run a sample using only command line parameters:
```` bash
$java -ea -cp target/vsphere-samples-8.0.2.1.jar vmware.samples.vcenter.vm.list.ListVMs --server servername --username administrator@vsphere.local --password password --skip-server-verification
````
Use a command like the following to run a sample using only a configuration file:
```` bash
$java -ea -cp target/vsphere-samples-8.0.2.1.jar vmware.samples.vcenter.vm.list.ListVMs --config-file sample.properties
````
Use the following command to run the sample using a combination of configuration file and command line parameters:
```` bash
$java -ea -cp target/vsphere-samples-8.0.2.1.jar vmware.samples.vcenter.vm.list.ListVMs --config-file sample.properties --server servername
````
### Connect to VMware Cloud on AWS
#### using csp api_token (also called refresh_token)
```java
import com.vmware.vmc.Orgs;
import com.vmware.vmc.model.Organization;
import com.vmware.vapi.vmc.client.VmcClients;
ApiClient apiClient = VmcClients.createDefault("<refresh_token>");
Orgs orgsStub = apiClient.createStub(Orgs.class);
Organization orgDetails = orgsStub.get("<org_id>");
System.out.println(orgDetails);
```
Output in console:
```shell
Organization (com.vmware.vmc.model.organization) => {
updated = 8/18/22 20:41:34 +0000,
userId = xxxx-xxxx-xxxx,
updatedByUserId = xxxx-xxxx-xxxx,
created = 10/3/17 22:19:31 +0000,
version = 4,
updatedByUserName = xxxx-xxxx-xxxx,
userName = xxxx-xxxx-xxxx,
id = xxxx-xxxx-xxxx,
orgType = INTERNAL_NON_CORE,
displayName = xxxx/xxxx/xxxx,
name = xxxx,
projectState = CREATED,
properties = OrgProperties (com.vmware.vmc.model.org_properties) => {
values = {...}
}
[dynamic fields]: {
org_seller_info = <unset>
}
}
```
#### using client_credentials (Server to Server OAuth app's id and secret)
```java
import com.vmware.vmc.Orgs;
import com.vmware.vmc.model.Organization;
import com.vmware.vapi.vmc.client.VmcClients;
ApiClient apiClient = VmcClients.createDefault("<client_id>", "<client_secret>", "<org_id>");
orgsStub = apiClient.createStub(Orgs.class);
Organization orgDetails = orgsStub.get("<org_id>");
System.out.println(orgDetails);
```
Output in console:
```shell
Organization (com.vmware.vmc.model.organization) => {
updated = 8/18/22 20:41:34 +0000,
userId = xxxx-xxxx-xxxx,
updatedByUserId = xxxx-xxxx-xxxx,
created = 10/3/17 22:19:31 +0000,
version = 4,
updatedByUserName = xxxx-xxxx-xxxx,
userName = xxxx-xxxx-xxxx,
id = xxxx-xxxx-xxxx,
orgType = INTERNAL_NON_CORE,
displayName = xxxx/xxxx/xxxx,
name = xxxx,
projectState = CREATED,
properties = OrgProperties (com.vmware.vmc.model.org_properties) => {
values = {...}
}
[dynamic fields]: {
org_seller_info = <unset>
}
}
```
### Importing the samples to eclipse
To generate the eclipse project files for the samples run the below command
```` bash
mvn eclipse:clean eclipse:eclipse
````
Once generated, follow below steps to import the project to eclipse:
1. Go to File -> Import.
2. Select Existing Projects into Workspace.
3. Select the root directory as the directory where the samples are located.
4. Click Finish
### Adding a new sample
Once the eclipse project is imported, follow below steps to add a new sample using the sample template:
1. Right click on the project and select New -> Package. Specify a package name in the wizard and click Finish.
2. Right click on the newly created package and click Import -> General -> File System. In the dialog box, click "Browse" and select the "sample-template" folder in the root directory.
3. Select the "SampleClass" in the dialog box and click finish.
This will import a basic sample class to your package, which you can then customize according to your needs.
## API Documentation
### vSphere API Documentation
* [VMware vSphere REST API Reference documentation](https://developer.vmware.com/docs/vsphere-automation/latest/).
* [VMware vSphere JAVA APIs 8.0 U2 (latest version)](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/8.0.2.0/vcenter-bindings/index.html).
* Previous releases: VMware vSphere JAVA APIs [8.0 U1](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/8.0.1.0/vcenter-bindings/index.html),
[8.0 GA](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/8.0.0.1/vsphereautomation-client-sdk/index.html),
[8.0.0.0](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/8.0.0.0/vsphereautomation-client-sdk/index.html),
[7.0 U3](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/7.0.3.0/vsphereautomation-client-sdk/index.html),
[7.0 U2](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/7.0.2.0/vsphereautomation-client-sdk/index.html),
[7.0 U1](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/7.0.1.0/vsphereautomation-client-sdk/index.html),
[7.0 GA](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/7.0.0.1/vsphereautomation-client-sdk/index.html)
### VMware Cloud on AWS API Documentation
* [VMware Cloud on AWS REST APIs](http://developers.eng.vmware.com/docs/vmc/latest/).
* [VMware Cloud on AWS JAVA APIs](https://vmware.github.io/vsphere-automation-sdk-java/vmc/index.html).
* [VMware Cloud on AWS Disaster Recovery as a Service (DRaaS) JAVA APIs](https://vmware.github.io/vsphere-automation-sdk-java/vmc-draas/index.html).
### NSX API Documentation
* [VMware NSX-T Data Center REST API](https://developer.vmware.com/apis/1248)
* [VMware NSX-T Manager APIs (for on-prem customers)](https://vmware.github.io/vsphere-automation-sdk-java/nsx/nsx/index.html).
* [VMware NSX-T Policy APIs (for on-prem customers)](https://vmware.github.io/vsphere-automation-sdk-java/nsx/nsx-policy/index.html).
* [VMware NSX-T Policy APIs (for VMC customers)](https://vmware.github.io/vsphere-automation-sdk-java/nsx/nsx-vmc-policy/index.html).
* [VMware NSX-T VMC AWS Integration APIs (for VMC customers)](https://vmware.github.io/vsphere-automation-sdk-java/nsx/nsx-vmc-aws-integration/index.html).
* [VMware NSX-T VMC Common APIs (for VMC customers)](https://vmware.github.io/vsphere-automation-sdk-java/nsx/nsx-vmc-sdk-common/index.html).
## Support
For official support, users with Active - Premium SDK Support, Standard SDK Support, Premier/Success 360, and [VMware Select Support](https://www.vmware.com/content/dam/digitalmarketing/vmware/en/pdf/docs/vmware-select-support-specific-program-document.pdf) can reach out to [VMware Global Support](https://kb.vmware.com/s/article/87265?lang=en_US) for any issues in line with our [SDK and API Support policy](https://www.vmware.com/support/services/sdk.html). For community support, please open a [Github issue](https://github.com/vmware/vsphere-automation-sdk-java/issues) or start a [Discussion](https://github.com/vmware/vsphere-automation-sdk-java/discussions).
## Submitting samples
### Developer Certificate of Origin
Before you start working with this project, please read our [Developer Certificate of Origin](https://cla.vmware.com/dco). All contributions to this repository must be signed as described on that page. Your signature certifies that you wrote the patch or have the right to pass it on as an open-source patch.
### Required Information
The following information must be included in the README.md for the sample.
* Author Name
* This can include full name, email address or other identifiable piece of information that would allow interested parties to contact author with questions.
* Date
* Date the sample was originally written
* Minimal/High Level Description
* What does the sample do ?
* Any KNOWN limitations or dependencies
### Versioning
vSphere Automation Java SDK - X.Y.Z.U.P
vCenter-related: X.Y - (Major release), Z - (Update release), U - (Patch)
vSphere Automation Java SDK - related: P - (vSphere Automation Java SDK Maintenance patches)
### Suggested Information
The following information should be included when possible. Inclusion of information provides valuable information to consumers of the resource.
* vSphere version against which the sample was developed/tested
* SDK version against which the sample was developed/tested
* Java version against which the sample was developed/tested
### Contribution Process
* Follow the [GitHub process](https://help.github.com/articles/fork-a-repo)
* Please use one branch per sample or change-set
* Please use one commit and pull request per sample
* Please post the sample output along with the pull request
* If you include a license with your sample, use the project license
### Code Style
Please conform to oracle java coding standards.
http://www.oracle.com/technetwork/articles/javase/codeconvtoc-136057.html
## Resource Maintenance
### Maintenance Ownership
Ownership of any and all submitted samples are maintained by the submitter.
### Filing Issues
Any bugs or other issues should be filed within GitHub by way of the repository’s Issue Tracker.
### Resolving Issues
Any community member can resolve issues within the repository, however only the board member can approve the update. Once approved, assuming the resolution involves a pull request, only a board member will be able to merge and close the request.
### VMware Sample Exchange
It is highly recommended to add any and all submitted samples to the VMware Sample Exchange: <https://code.vmware.com/samples>
Sample Exchange can be allowed to access your GitHub resources, by way of a linking process, where they can be indexed and searched by the community. There are VMware social media accounts which will advertise resources posted to the site and there's no additional accounts needed, as the VMware Sample Exchange uses MyVMware credentials.
## Repository Administrator Resources
### Board Members
Board members are volunteers from the SDK community and VMware staff members, board members are not held responsible for any issues which may occur from running of samples from this repository.
Members:
* Ankit Agrawal (VMware)
* Martin Cvetanov (VMware)
* Shweta Purohit (VMware)
* Jobin George (VMware)
* Kunal Singh (VMware)
### Approval of Additions
Items added to the repository, including items from the Board members, require 2 votes from the board members before being added to the repository. The approving members will have ideally downloaded and tested the item. When two “Approved for Merge” comments are added from board members, the pull can then be committed to the repository.
## VMware Resources
* [VMware Developers Site](http://developers.eng.vmware.com/)
* [vSphere Automation SDK Overview](https://code.vmware.com/web/sdk/7.0/vsphere-automation-java)
* [VMware Code](https://code.vmware.com/home)
* [VMware Developer Community](https://communities.vmware.com/community/vmtn/developer)
* VMware vSphere [Java API Reference documentation](https://vmware.github.io/vsphere-automation-sdk-java/vsphere/8.0.1.0/vcenter-bindings/index.html).
* [VMware Java forum](https://code.vmware.com/forums/7508/vsphere-automation-sdk-for-java)
| 0 |
symisc/pixlab | PixLab Resources & Code Samples | computer-vision deep-learning image-analysis image-processing java javascript php python rest-api | # [PixLab](https://pixlab.io) & [FACEIO](https://faceio.net) Guides, Announcments & Tutorials
* [Face Authentication with HTMX](https://itnext.io/face-authentication-with-htmx-a1dffb9247e0)
* [PixLab’s New Single Shot Livesness, Face Anti-Spoof & Deep-Fake Detector Model: Revolutionizing Face Authentication](https://www.biometricupdate.com/202404/pixlab-introduces-single-frame-biometric-face-authentication-to-faceio-platform)
* [Unveiling the Future of Generative Image Editing: AI Photo Editor Reloaded](https://blog.pixlab.io/2024/02/unveiling-the-future-of-generative-image-editing-pixlab-ai-photo-editor-reloaded)
* [Unlocking the Potential of Facial Recognition with FACEIO](https://javascript.plainenglish.io/unlocking-the-potential-of-facial-recognition-with-faceio-d8a63c5e1cf6)
* [Detect And Blur Human Faces using the PixLab AI APIs](https://dev.to/random_ti/detect-and-blur-human-faces-with-ai-in-nextjs-hg6)
* [FACEIO for Password-less Web Authentication](https://dev.to/dev_kiran/faceio-for-password-less-web-authentication-4k2i)
* [The Evolution of Photo Editing and the Power of Generative AI using PixLab AI Photo Editor](https://levelup.gitconnected.com/the-evolution-of-photo-editing-and-the-power-of-generative-ai-e607d6e9ac1a)
* [Build a Face Recognition & Authentication System for Your Website using Next.js & FACEIO](https://dev.to/random_ti/a-demo-of-face-recognition-authentication-in-nextjs-54g4)
* [In the Eyes of Security: ReactJS, FaceIO, and the Future of Authentication](https://blog.stackademic.com/in-the-eyes-of-security-reactjs-faceio-and-the-future-of-authentication-62d093520f08)
* [A Beginner's Guide to Online Image Labeling & Annotation Using PixLab Annotate](https://dev.to/unqlite_db/a-beginners-guide-to-online-image-labeling-annotation-using-pixlab-annotate-52l4)
* [PixLab Annotate 1.79 Released - Online Image Annotation, Labeling and Segmentation Tool](https://pixlab.io/annotate)
* [How to Implement Facial Authentication with FaceIO and Tailwind CSS](https://javascript.plainenglish.io/how-to-implement-facial-authentication-with-faceio-and-tailwind-css-1989e938e5bf)
* [Automate Your KYC Document Verification with the PixLab DOCSCAN REST API Endpoint](https://javascript.plainenglish.io/automate-your-kyc-document-verification-with-this-api-71a9d4215867)
* [Implement a Facial Recognition Authentication System Using Fio.js, React.js and Tailwind CSS](https://blog.stackademic.com/implement-a-facial-recognition-authentication-using-react-js-and-tailwind-css-cac428639367)
* [Scanning Passport Machine Readable Zone (MRZ) using PixLab's DOCSCAN API endpoint](https://blog.stackademic.com/from-mrz-to-docscan-16ab5fbf57f4)
* [PixLab adds passive deepfake detection to FACEIO biometric authentication framework](https://www.biometricupdate.com/202308/pixlab-adds-passive-deepfake-detection-to-biometric-authentication-framework) - [**PDF Press Release**](https://faceio.net/pixlab-faceio-deep-fakes-prevention.pdf)
* [Integrating FACEIO into a React Web Application with Tailwind CSS](https://levelup.gitconnected.com/integrating-faceio-into-a-react-web-application-with-tailwind-css-208904a394c2)
* [Secure your Web Applications with Facial Authentication](https://dev.to/0ruko002/secure-your-web-applications-with-facial-authentication-3gof)
* [Safeguarding User Content: Blur Faces and Censor NSFW Content with the PixLab APIs](https://levelup.gitconnected.com/safeguarding-user-content-blur-faces-and-censor-nsfw-content-with-pixlab-api-222564b3109)
* [Press Release - PixLab Introduces Groundbreaking Document Scanning API for KYC and ID Verification](https://blog.pixlab.io/2023/07/press-release-pixlab-introduces-groundbreaking-document-scanning-api-for-kyc-and-id-verification)
* [Streamline KYC with PixLab’s Document Scanning (Passports, ID Cards & US Drivers License) APIs](https://levelup.gitconnected.com/streamlining-kyc-with-pixlabs-document-scanner-api-c26836fb372e?gi=9dad0fc8084e)
* [Modern Image Processing Algorithms Overview & Implementation in C/C++](https://sod.pixlab.io/articles/modern-image-processing-algorithms-implementation.html)
* [Building Face Authentication in React with FaceIO and Bootstrap 5](https://levelup.gitconnected.com/building-face-authentication-in-react-with-faceio-and-bootstrap-5-ba619d804e13)
* [Facial Recognition Made Easy: How to Implement FaceIO in 5 Minutes](https://levelup.gitconnected.com/facial-recognition-made-easy-how-to-implement-faceio-in-5-minutes-c3a80e920a36)
* [Streamlining User Experience with Facial Recognition: A Guide to FaceIO and ReactJS Integration](https://levelup.gitconnected.com/streamlining-user-experience-with-facial-recognition-a-guide-to-faceio-and-reactjs-integration-6059723913fa)
* [Learn how to authenticate users via face recognition on your favorite no-code site builder platform](https://levelup.gitconnected.com/learn-how-to-authenticate-users-via-face-recognition-on-your-favorite-no-code-site-builder-platform-6bc1316be985)
* [How To Use Face Recognition for Authentication on a Web Application](https://dzone.com/articles/how-to-use-face-recognition-for-authentication-in)
* [Facial Authentication using FACEIO and Vue.Js](https://levelup.gitconnected.com/face-authentication-using-faceio-and-vue-js-319671a67d5b)
* [Livneness Detection & Face Anti-Spoofing Security Feature Available for FACEIO](https://blog.pixlab.io/2023/02/face-spoofing-livneness-detection-and-presentation-attacks-prevention-security-feature-available-for-faceio)
* [FACEIO - New Age for Face Authentication](https://www.analyticsvidhya.com/blog/2023/02/faceio-app-new-age-face-authentication/)
* [Implement a Facial Recognition Authentication Using React.js and TailwindCSS](https://betterprogramming.pub/replace-your-auth-system-with-facial-recognition-using-reactjs-and-tailwindcss-9af4898ab5a2)
* [NPM Package for FACEIO's fio.js Released](https://www.npmjs.com/package/@faceio/fiojs)
* [Implementing Web based Facial Authentication with FACEIO's NPM Package](https://dev.to/face/integrating-facial-authentication-with-fiojs-1jie)
* [A gentle introduction to FACEIO](https://dev.to/ahmedqureshi54/what-is-faceio-facial-recognition-face-recognition-software-and-face-analysis-explained-3e7m)
* [Learn How To Scan US Driver’s Licenses and Passports via Pixlab’s “Docscan” API endpoint](https://betterprogramming.pub/how-to-scan-us-drivers-license-and-passport-using-ai-361fc3e0803d)
* [FACEIO's fio.js V1.9 Released with Face Duplication Prevention](https://blog.pixlab.io/2022/10/fiojs-190-released-with-face-duplication-prevention)
* [Filter Image Uploads According to their NSFW Score using the PixLab API](https://itnext.io/how-to-filter-nsfw-images-and-programmatically-blur-them-2806f275daac)
* [Using React-Typescript With FaceIO for User Face Authentication](https://hackernoon.com/using-react-typescript-with-faceio-for-user-face-authentication)
* [How to Filter NSFW Images and Programmatically Blur Them](https://hackernoon.com/how-to-filter-nsfw-images-and-programmatically-blur-them)
* [Log in/Sign up form using FaceIO, Next.js and Tailwind CSS](https://medium.com/@thiongojohn91/ng-log-in-sign-up-form-using-faceio-next-js-and-tailwind-css-e463a56aa814)
* [How to use Facial Recognition to Enhance user Experience on your Website using FaceIO](https://sosha.hashnode.dev/how-to-use-facial-recognition-to-enhance-user-experience)
* [How to Authenticate a User with Face Recognition in React.js](https://www.freecodecamp.org/news/authenticate-with-face-recognition-reactjs/)
* [How to Authenticate a User via Face Recognition in Your Web Application](https://hackernoon.com/how-to-authenticate-a-user-via-face-recognition-in-your-web-application)
* [Detect and Blur Human Faces on Your Website Using JavaScript via the PixLab API](https://betterprogramming.pub/detect-and-blur-human-faces-on-your-website-8c4a2d69a538)
* [Introducing FACEIO - Facial Authentication for the Web](https://dev.to/unqlite_db/introducing-faceio-facial-authentication-for-the-web-3i71)
* [PixLab’s Document Scanner now able to scan Driving License issued by any U.S. state](https://blog.pixlab.io/2022/06/pixlabs-docscan-now-able-to-scan-us-drivers-licenses-issued-by-jurisdictions-from-all-the-50-us-states)
* [Step-by-step guide to do e-KYC in your app](https://medium.com/@hrishikeshb2pathak/step-by-step-guide-to-do-e-kyc-in-your-app-c3b4e240617)
* [Generate funny memes programmatically with the PixLab API](https://codewithkrishna.hashnode.dev/generate-funny-memes-programmatically)
* [Detect & Blur Faces on a Flutter Mobile App using the PixLab API](https://dev.to/hrishiksh/detect-and-blur-faces-in-flutter-using-pixlab-api-m5a)
* [Full Scan Support for Emirates (UAE) ID/Residence Cards with PP-OCR Algorithm Overview](https://blog.pixlab.io/2021/10/document-scan-support-for-united-arab-emirates-uae-id-residence-cards)
* [New Gender/Age Classification Model Deployed for the PixLab API](https://blog.pixlab.io/2021/09/new-gender-age-detection-model-deployed)
* [PixLab Annotate - Online batch image annotation, labeling and segmentation tool](https://annotate.pixlab.io/)
* [Introducing the Pixel Generate API Endpoint](https://blog.pixlab.io/2021/02/introducing-the-pixel-generate-api-endpoint)
* [Implement a Minimalistic KYC Form & Identify Verification Check](https://dev.to/unqlite_db/implement-a-minimalistic-kyc-form-identify-verification-check-36f5)
* [Modern Passport Structure & Bulk Scan APIs](https://blog.pixlab.io/2020/11/modern-passports-structure-bulk-scan-apis)
* [PixLab API 1.9.72 Released](https://blog.pixlab.io/2020/08/pixlab-api-1972-released)
* [Detect & Blur Faces Programmatically](https://dzone.com/articles/detect-and-blur-faces-programmatically)
* [Talkie OCR - iOS app based on PixLab OCR Released](https://blog.pixlab.io/2020/10/talkie-ocr-image-to-speech-now-on-the-app-store)
* [Filter Image Uploads According to their NSFW Score ](https://dev.to/unqlite_db/filter-image-uploads-according-to-their-nsfw-score-15be)
* [Passports, Travel Documents & ID Cards Scan Available through the PixLab API](https://blog.pixlab.io/2020/06/passport-docscan-api-endpoint)
* [ASCII ART Camera Effect Model Now Available on the Unity Asset Store](https://blog.pixlab.io/2020/05/ascii-art-camera-effect-model-now-available-in-the-unity-asset-store)
* [Full Scan Support for India Aadhar ID Card](https://blog.pixlab.io/2020/03/full-scan-support-for-india-aadhar-id-card)
* [Full Scan Support for Malaysia and Singapore ID Cards](https://blog.pixlab.io/2019/11/docscan-api-endpoint-support-id-cards-passports)
* [The DOCSCAN API Endpoint](https://pixlab.io/cmd?id=docscan)
* [List of Face Detection & Recognition API Endpoints](https://blog.pixlab.io/2018/01/face-detection-landmarks-recognition-endpoints)
# PixLab Resources & Code Samples
PixLab Resources & Sample Set - https://pixlab.io/examples
The Sample Set are practical usage, working code available in various programming languages intended to familiarize the reader with the PixLab API.
For an introduction course, please refer to:
* [The PixLab API in 5 minutes or less](https://pixlab.io/start).
* [List of API endpoints](https://pixlab.io/api).
* [The PixLab API Reference Guide](https://pixlab.io/cmdls).
* [The PixLab Sample Set](https://pixlab.io/examples).
You’re welcome to copy/paste and run these examples to see the API in action.
| 0 |
dockersamples/wordsmith | Sample project with Docker containers running under Kubernetes | demo docker docker-compose example kubernetes sample swarm | # Wordsmith App
Wordsmith is the demo project originally shown at DockerCon EU 2017 and 2018.
The demo app runs across three containers:
- **[api](api/Dockerfile)** - a Java REST API which serves words read from the database
- **[web](web/Dockerfile)** - a Go web application that calls the API and builds words into sentences
- **db** - a Postgres database that stores words
## Architecture

## Build and run in Docker Compose
The only requirement to build and run the app from source is Docker. Clone this repo and use Docker Compose to build all the images. You can use the new V2 Compose with `docker compose` or the classic `docker-compose` CLI:
```shell
docker compose up --build
```
Or you can pull pre-built images from Docker Hub using `docker compose pull`.
## Deploy using Kubernetes manifests
You can deploy the same app to Kubernetes using the [Kustomize configuration](./kustomization.yaml). It will define all of the necessary Deployment and Service objects and a ConfigMap to provide the database schema.
Apply the manifest using `kubectl` while at the root of the project:
```shell
kubectl apply -k .
```
Once the pods are running, browse to http://localhost:8080 and you will see the site.
Docker Desktop includes Kubernetes and the [kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) command line, so you can work directly with the cluster. Check the services are up, and you should see output like this:
```text
kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
db ClusterIP None <none> 55555/TCP 2m
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 38d
web LoadBalancer 10.107.215.211 <pending> 8080:30220/TCP 2m
words ClusterIP None <none> 55555/TCP 2m
```
Check the pods are running and you should see one pod each for the database and web components and five pods for the words API:
```text
kubectl get pods
NAME READY STATUS RESTARTS AGE
db-8678676c79-h2d99 1/1 Running 0 1m
web-5d6bfbbd8b-6zbl8 1/1 Running 0 1m
api-858f6678-6c8kk 1/1 Running 0 1m
api-858f6678-7bqbv 1/1 Running 0 1m
api-858f6678-fjdws 1/1 Running 0 1m
api-858f6678-rrr8c 1/1 Running 0 1m
api-858f6678-x9zqh 1/1 Running 0 1m
```
| 1 |
SpringDataElasticsearchDevs/spring-data-elasticsearch-sample-application | Spring Data Elasticsearch Sample Application | null | spring-data-elasticsearch-sample-application
============================================
Spring Data Elasticsearch Sample Application | 1 |
Azure-Samples/azure-cosmos-java-sql-api-samples | Sample code for Azure Cosmos DB Java SDK for SQL API | null | ---
page_type: sample
languages:
- java
products:
- java sdk
description: "Sample code repo for Azure Cosmos DB Java SDK for SQL API"
urlFragment: ""
---
# Azure Cosmos DB Java SQL API Samples
<!--
Guidelines on README format: https://review.docs.microsoft.com/help/onboard/admin/samples/concepts/readme-template?branch=master
Guidance on onboarding samples to docs.microsoft.com/samples: https://review.docs.microsoft.com/help/onboard/admin/samples/process/onboarding?branch=master
Taxonomies for products and languages: https://review.docs.microsoft.com/new-hope/information-architecture/metadata/taxonomies?branch=master
-->
Sample code repo for Azure Cosmos DB Java SDK for SQL API. By cloning and running these samples, and then studying their implementations, you will have an example for sending various requests to Azure Cosmos DB from Java SDK via the SQL API.
## Contents
| File/folder | Description |
|-------------------|--------------------------------------------|
| `src` | Java sample source code. Many samples have 'sync' and 'async' variants |
| `.gitignore` | Define what to ignore at commit time. |
| `CHANGELOG.md` | List of changes to the sample. |
| `CONTRIBUTING.md` | Guidelines for contributing to the sample. |
| `README.md` | This README file. |
| `LICENSE` | The license for the sample. |
| `pom.xml` | Maven Project Object Model File
## Prerequisites
* Maven
* Java SE JRE 8
* Setting up an Azure Cosmos DB account through the Azure Portal. The **Create a database account** section of [this guide](https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-java) walks you through account creation.
* The hostname and master key for your Azure Cosmos DB account
## Setup
Clone the sample to your PC. Using your Java IDE, open pom.xml as a Maven project.
## Running the sample
These environment variables must be set
```
ACCOUNT_HOST=your account hostname;ACCOUNT_KEY=your account master key
```
in order to give the samples read/write access to your account.
To run a sample, specify its Main Class
```
com.azure.cosmos.examples.sample.synchronicity.MainClass
```
where *sample.synchronicity.MainClass* can be
* crudquickstart.sync.SampleCRUDQuickstart
* crudquickstart.async.SampleCRUDQuickstartAsync
* indexmanagement.sync.SampleIndexManagement
* indexmanagement.async.SampleIndexManagementAsync
* storedprocedure.sync.SampleStoredProcedure
* storedprocedure.async.SampleStoredProcedureAsync
* changefeed.SampleChangeFeedProcessor *(Changefeed has only an async sample, no sync sample.)*
*Build and execute from command line without an IDE:* From top-level directory of repo:
```
mvn clean package
mvn exec:java -Dexec.mainClass="com.azure.cosmos.examples.sample.synchronicity.MainClass" -DACCOUNT_HOST=your account hostname -DACCOUNT_KEY=your account master key
```
where *sample.synchronicity.MainClass*, *your account hostname*, and *your account master key* are to be filled in as above. This will rebuild and run the selected sample.
## Key concepts
These samples cover a range of Azure Cosmos DB usage topics from more to less basic:
* Basic management of databases, containers and items
* Indexing, stored procedures
* Change Feed
## 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.opensource.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., status check, 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.
| 1 |
romainguy/filthy-rich-clients | Samples for the book Filthy Rich Clients | null | # Filthy Rich Clients
This repository hosts all the code examples from the
book called Filthy Rich Clients, written by Chet Haase
and Romain Guy.
You can find more information about the book here:
http://filthyrichclients.org/

All the examples are licensed under a 3-clause BSD
license.
| 0 |
blazegraph/blazegraph-samples | Blazegraph Samples with Sesame, Blueprints, and RDR | null | #Welcome to the Blazegraph Samples Project#
The Blazegraph™ Database is our ultra high-performance graph database supporting Blueprints and RDF/SPARQL APIs. It supports up to 50 Billion edges on a single machine and has available enterprise features such as High Availability and Scale-out. It is in production use for Fortune 500 customers such as EMC, Autodesk, and many others. It powers the Wikimedia Foundation's Wiki Data Query Service. See the latest [Feature Matrix](http://www.blazegraph.com/product/).
[Sign up](http://eepurl.com/VLpUj) to get the latest news on Blazegraph.
Please also visit us at our: [website](http://www.blazegraph.com), [wiki](https://wiki.blazegraph.com), and [blog](https://wiki.blazegraph.com/).
Find an issue? Need help? See [JIRA](https://jira.blazegraph.com) or purchase [Support](https://www.blazegraph.com/buy).

# blazegraph-samples
Samples for using Blazegraph™
Link to the [Javadoc](https://blazegraph.github.io/blazegraph-samples/apidocs/index.html)
To build everything run:
```
mvn package
```
Simple applications demonstrating using Blazegraph for loading/querying data in different modes:
To build a sample, cd in the directory and run:
```
cd sample-sesame-first
mvn package
```
1. sample-sesame-first - Sesame API in emmbedded mode
https://wiki.blazegraph.com/wiki/index.php/First_Application_Tutorial
2. 'sample-sesame-embedded' - Sesame API in emmbedded mode
https://wiki.blazegraph.com/wiki/index.php/Sesame_API_embedded_mode
3. 'sample-sesame-remote' - Sesame API in remote mode
https://wiki.blazegraph.com/wiki/index.php/Sesame_API_remote_mode
4. 'sample-blueprints-embedded' - Blueprints API in embedded mode
https://wiki.blazegraph.com/wiki/index.php/Blueprints_API_embedded_mode
5. 'sample-blueprints-remote' - Blueprints API in remote mode
https://wiki.blazegraph.com/wiki/index.php/Blueprints_API_remote_mode
6. 'sample-rdr' - using RDF* and SPARQL* with Blazegraph™
https://wiki.blazegraph.com/wiki/index.php/RDR
7. 'sample-customFunction-embedded'- Custom Embedded Function
https://wiki.blazegraph.com/wiki/index.php/Custom_Function_embedded_mode
8. 'sample-test' - Sample Unit Tests <br>
technical project created for CI system
| 0 |
adobe/aem-test-samples | Adobe Experience Manager Test Samples | aem testing | # AEM Test Samples
This is a collection of test modules that can be run to validate an AEM cloud-based deployment.
Tests are written according to [Best practices](https://github.com/adobe/aem-testing-clients/wiki/Best-practices).
## Modules
* [smoke](./smoke) - generic smoke tests
## How to use
Clone the repository and use maven for running each of the test modules.
The build also produces a `jar-with-dependencies` that can be run as a self-contained test module
(using java directly or a small maven pom with failsafe configured).
### Run the tests against localhost
```bash
mvn clean verify -Ptest-all
```
### Run the test against your AEM Cloud Service author and publish tiers
The `eaas-local` profile has been added for convenience to allow to run the test locally against an AEM Cloud Service.
The same test client configuration is used when the test module is executed in the Cloud Service
```bash
mvn -Peaas-local clean verify \
-Dcloud.author.url=<your-aem-author-url> \
-Dcloud.author.user=admin \
-Dcloud.author.password=<your-admin-password> \
-Dcloud.publish.url=<your-aem-publish-url \
-Dcloud.publish.user=admin \
-Dcloud.publish.password=<your-admin-password> \
```
## Requirements
##### User
The test modules require the `admin` user or an admin-like user with enough privileges to create content, new users,
groups and replicate content.
##### Replication
The tests also verify author-publish replication therefore for them to work correctly replication needs be be
configured correctly.
Note that `ReplicationIT` will create and delete a randomized page in path like: `/content/test-site/testpage_632460d4-361c-4b9b-9eef-d2446f79ec9c`
### Sling properties
The `eaas-local` profile facilitates the definition of sling properties expected by the aem-testing-clients
(and the underlying Sling Testing Clients) in a convenient way.
The system properties are as follows:
* sling.it.instances - should be set to 2
* sling.it.instance.url.1 - should be set to the author URL, for example, http://localhost:4502
* sling.it.instance.runmode.1 - should be set to author
* sling.it.instance.adminUser.1 - should be set to the author admin user, e.g. admin
* sling.it.instance.adminPassword.1 - should be set to the author admin password
* sling.it.instance.url.2 - should be set to the author URL, for example, http://localhost:4503
* sling.it.instance.runmode.2 - should be set to publish
* sling.it.instance.adminUser.2 - should be set to the publish admin user, for example, admin
* sling.it.instance.adminPassword.2 - should be set to the publish admin password
* sling.it.configure.default.replication.agents - should be set to false
## UI Tests
Custom UI testing is an optional feature that enables you to create and automatically run UI tests for your applications.
The [UI Testing](https://experienceleague.adobe.com/docs/experience-manager-cloud-service/content/implementing/using-cloud-manager/test-results/ui-testing.html) section of the documentation provides in-depth information of their structure and usage.
- `/ui-cypress` provides a sample Custom UI test module driven by Cypress.
- `/ui-selenium-webdriver` provides a sample Custom UI test module driven by Selenium WebDriver.
- The [aem-project-archetype](https://github.com/adobe/aem-project-archetype/tree/develop/src/main/archetype/ui.tests) can be used as reference for Custom UI test modules driven by Selenium + WebdriverIO
## Notable Examples
* [Creating a page with the admin user](./smoke/src/main/java/com/adobe/cq/cloud/testing/it/smoke/CreatePageAdminIT.java)
* [Creating a page with a transient author user](./smoke/src/main/java/com/adobe/cq/cloud/testing/it/smoke/CreatePageAsAuthorUserIT.java)
| 0 |
hantsy/spring-microservice-sample | Spring Boot based Mircoservice sample | docker docker-machine docker-swarm docker-toolbox microservice ngnix rest spring spring-boot spring-data-jpa spring-data-redis spring-security spring-session | <!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)*
- [Building a Microservices application with Spring Boot](#building-a-microservices--application-with-spring-boot)
- [What is Microservices ?](#what-is-microservices-)
- [Migrating to Microservices architecture](#migrating-to--microservices--architecture)
- [Cooking your first service](#cooking-your-first-service)
- [Prerequisites](#prerequisites)
- [Setup local development environment](#setup-local-development-environment)
- [Docker Toolbox Notes](#docker-toolbox-notes)
- [Generate project skeleton](#generate-project-skeleton)
- [REST API Overview](#rest-api-overview)
- [Create a new Entity](#create-a-new-entity)
- [Create `Repository` for Entities](#create-repository-for-entities)
- [Create a Domain Service](#create-a-domain-service)
- [Expose RESTful APIs](#expose-restful-apis)
- [Exception Handling](#exception-handling)
- [Miscellaneous](#miscellaneous)
- [Secures Microservices](#secures-microservices)
- [Running Microservices application](#running-microservices-application)
- [Running application via Maven plugin](#running-application-via-maven-plugin)
- [Running application via Docker Compose](#running-application-via-docker-compose)
- [Testing Microservices](#testing-microservices)
- [Testing Single Service](#testing-single-service)
- [Testing POJOs](#testing-pojos)
- [Testing Repository](#testing-repository)
- [Testing PostService](#testing-postservice)
- [Testing web facilities](#testing-web-facilities)
- [Integration Tests](#integration-tests)
- [Testing against External Service](#testing-against-external-service)
- [MockRestServiceServer](#mockrestserviceserver)
- [WireMock](#wiremock)
- [Testing Service-to-Service Communication](#testing-service-to-service-communication)
- [Spring Cloud Contracts](#spring-cloud-contracts)
- [Pact](#pact)
- [Deploying Microservices application](#deploying-microservices-application)
- [Publishing Docker Images to Docker Hub](#publishing-docker-images-to-docker-hub)
- [Deploying to Docker Swarm](#deploying-to-docker-swarm)
- [Deploying to Kubernetes](#deploying-to-kubernetes)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
# Building a Microservices application with Spring Boot
**Microservices** is a very hot topic in these years, you can see it everywhere, there are a lots of books, blog entries, conference sessions, training courses etc. are talking about it.
## What is Microservices ?
Microservices is not a standard specification, so there is no official definition. Here I listed some well-known explanation from the communities.
[Martin Fowler](https://martinfowler.com/) described it as the following in his article [Microservices](https://martinfowler.com/microservices/):
>In short, the Microservices architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.
On the [Wikipedia Microservices page](https://en.wikipedia.org/wiki/Microservices), Microservices was defined as:
>Microservices is a variant of the service-oriented architecture (SOA) architectural style that structures an application as a collection of loosely coupled services. In a Microservices architecture, services should be fine-grained and the protocols should be lightweight. The benefit of decomposing an application into different smaller services is that it improves modularity and makes the application easier to understand, develop and test. It also parallelizes development by enabling small autonomous teams to develop, deploy and scale their respective services independently.[1] It also allows the architecture of an individual service to emerge through continuous refactoring. Microservices-based architectures enable continuous delivery and deployment.
Chris Richardson, the author of *POJOs in Action* and the creator of the original CloudFoundry.com, and also an advocator of Microservices , summarized Microservices as the following in the home page of [Microservices.io](http://Microservices.io/index.html).
>Microservices - also known as the Microservices architecture - is an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities. The Microservices architecture enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.
There are some common characteristics can be used to describe a Microservices based application.
* A Microservices application should be consisted of a collection of small services. One single service is not Microservices . Every service is fine-grained, and target to perform a small functionality. So Microservices was described as *fine-grained SOA* or *SOA done right* in some articles. So This is the main difference from traditional monolithic applications.
* Every service should have its own independent life cycle. Every service can be developed and deployed independently, if you are using a CI/CD automation service, every service should be delivered through a standard DevOps pipeline, but not affect others.
* Service-to-service communication is based on light-weight protocols, eg. HTTP based REST APIs for synchronous communication, WebSocket for asynchronous messages, MQTT/AMQP protocol for varied messaging from client or devices(eg. IOT applications).
* The organization or team structures should be changed simultaneously when you are embracing Microservices architecture. In the traditional application development, especially your organization follows the waterfall development prototype, your teams are organized by roles, eg architects, database administrators, developers, testers, operators etc. You have to break your traditional organization tree. In the development stage of a Microservices based application, a small team should be responsible for the whole DevOps lifecycle (design, develop, test, deploy, etc.) of one or more services.
Microservices componentizes your application into small services(componentized applications), and make it more maintainable and scalable. In this demo application, I will show you building a Microservices application via Spring Boot.
## Migrating to Microservices architecture
Contrast with Microservices applications, traditional layered enterprise applications were called **monolithic** applications.
In the past years, I have created some samples to demonstrate different technology stack, such as [REST APIs sample with Spring MVC](https://github.com/hantsy/angularjs-springmvc-sample), [REST APIs sample with Spring Boot](https://github.com/hantsy/angularjs-springmvc-sample-boot). In these code samples, the backends are monolithic applications and they are based on the same model prototype, **a blog application**.
* A user can log in with an existed account, or sign up a new account.
* An authenticated user can create a new post.
* An authenticated user can update his/her posts.
* An authenticated user who has **ADMIN** role can delete a post directly.
* All users(who are authenticated or anonymous) can view posts.
* An authenticated user can add comments to an existed post.
* ...
No doubt these monolithic backend applications are easy to develop and deploy, but as time goes by, when the application becomes more complex, the backend will be problematic, you maybe face some barriers which block you to the next stages.
* When applying a change, you have to redeploy the whole backend application even it is just a small fix. The application may be stopped to work for some minutes or some hours.
* When scaling your applications and deploying multiple copies of the backend applications behinds a load balance server, the transactional consistence will be a new challenge.
* The database itself will be a huge performance bottleneck when the concurrency of incoming requests are increasing.
Microservices architecture addresses these problems, including:
1. Smaller services are easier to maintain in a complex application, when you upgrade one service, you do not need to shut down all services in the production environment.
2. ACID can not satisfy the scenario of those long run workflows which across several services, although it is still a good option in a single service, but for these long run **transactions**, a stateful *Saga* or workflow solution fills this field.
3. A service can has its own database, and only responsible for storing data of this service itself. Traditional complex queries will become a big challenge, in Microservices architecture, it could need to query multi independent database and aggregate the query results. CQRS, Event Store can save these. Perform commands in standalone services, and execute queries in another service which has marshal view of the data and was synced with messaging from events triggered by other services.
Follow the **Bounded Context** concept of DDD(Domain Driven Design), we break the backend monolithic application into three small services, including:
* An **auth-service** is serving the operations of signin, signup and signout.
* A **user-service** is responsible for user management.
* A **post-service** exposes APIs for a simple CMS, including posts and comments.
* An **API Gateway** which is just responsible for routing the incoming requests to downstream services.
* The databases are also aligned to Microservices architecture, and **user-service** and **post-service** have their own databases, a **Redis** is used for sharing session between services, and to simplify the security.

As mentioned, if there is a [legacy application](https://github.com/hantsy/angularjs-springmvc-sample) planned to migrate to Microservices architecture, you can follow the following steps to extract some domain into a standalone service.
1. Find the domains which are easiest to separate from the main application, eg, posts and comments in our application.
2. Use an identifier object in the entity links instead of the hard relations of entities outside of this domain. eg. use a `Username` which stands for a unique username of a `User` entity, and erase the direct connection to `User` entity.
3. Move the related data to a standalone database, and connect to this new database in your service.
When I start a new project, should I embrace Microservices architecture right now?
Although we are talking about Microservices in this post, I still suggest you start building your application in a monolithic architecture if you know little about the complexity of Microservices , it could be consisted of a RESTful backend and an SPA based frontend UI. In the initial development stage, either monolithic architecture or Microservices , you have to spend lots of time on clarifying the problem domains, defining the bounded context etc. Starting a monolithic application is still valuable when you are ready for migrating to Microservices architecture.
## Cooking your first service
This sample application is built on the newest Spring technology stack, including Spring Boot, Spring Data, Spring Security, etc.
* Every small service is a Spring Boot application. Every service will be packaged as a **jar** file and use the embedded Tomcat as target runtime to serve the services.
* Every small service owns its database, eg. we use MySQL as the backing database for **auth-service**, and PostgreSQL for the **post-service**.
* Spring Data is used for simplifying data operations.
* Spring Session provides a simple strategy to generate and validate header based authentication token via sharing sessions in a backing session repository, in this sample we use Redis as session storage.
* Spring Security is responsible for protecting RESTful APIs.
Follow the 12 factors application guide, I suggest you use Docker in both development and production environment to make sure the same code base works well in different environments.
In this section, we will build our first service, **post-service**, which is designated to exposes REST APIs to clients.
### Prerequisites
I assume you have some experience of Spring, and know well about the [REST convention](https://en.wikipedia.org/wiki/Representational_state_transfer), especially the [CHAPTER 5: Representational State Transfer (REST)](https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm) from Roy Fielding's dissertation: [Architectural Styles and
the Design of Network-based Software Architectures](https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm).
And you have also installed the following software.
* JDK 8, eg. [Oracle Java 8 SDK](https://java.oracle.com)
* The latest [Apache Maven](https://maven.apache.org)
* Optional [Gradle](http://www.gradle.org) if you prefer Gradle as build tools
* Your favorite IDE, including :
* [NetBeans IDE](http://www.netbeans.org)
* [Eclipse IDE](http://www.eclipse.org) (or Eclipse based IDE, Spring ToolSuite is highly recommended)
* [Intellij IDEA](http://www.jetbrains.com)
### Setup local development environment
Make sure you have installed the latest Docker, Docker Compose and Docker Machine, more info please refer to the installation guide from [Docker official website](https://www.docker.com).
>NOTE: Under Windows system, you can install Docker Desktop for Windows to simplify the installation.
Docker Compose allows you start up the dependent infrastructural services(such as Database etc) via a single `docker-compose` command.
```
docker-compose up
```
We will use MySQL, PostgreSQL and Redis in this demo, the following is a sample *docker-compose.yml* file.
```yaml
version: '3.3' # specify docker-compose version
services:
userdb:
container_name: userdb
image: mysql
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: mysecret
MYSQL_USER: user
MYSQL_PASSWORD: password
MYSQL_DATABASE: userdb
volumes:
- ./data/userdb:/var/lib/mysql
postdb:
container_name: postdb
image: postgres
ports:
- "5432:5432"
restart: always
environment:
POSTGRES_PASSWORD: password
POSTGRES_DB: postdb
volumes:
- ./data/postdb:/var/lib/postgresql
redis:
container_name: redis
image: redis
ports:
- "6379:6379"
```
#### Docker Toolbox Notes
If you are using the legacy Docker Toolbox, create a new machine for this project.
```
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn springms
```
>NOTE: The `--engine-registry-mirror https://docker.mirrors.ustc.edu.cn` will add a docker registry mirror setting in docker-machine specific *config.json*. For most of Chinese users, using a local mirror will speed up the Docker images downloading.
Then switch to the new created machine **springms**, and set the environment variables.
```
eval "$(docker-machine env springms)"
```
Forward the virtualbox ports to your local system, thus you can access the servers via `localhost` instead of the docker machine IP address.
```d
VBoxManage modifyvm "springms" --natpf1 "tcp-port3306,tcp,,3306,,3306"
VBoxManage modifyvm "springms" --natpf1 "tcp-port5432,tcp,,5432,,5432"
VBoxManage modifyvm "springms" --natpf1 "tcp-port5672,tcp,,5672,,5672"
VBoxManage modifyvm "springms" --natpf1 "tcp-port15672,tcp,,15672,,15672"
VBoxManage modifyvm "springms" --natpf1 "tcp-port6379,tcp,,6379,,6379"
VBoxManage modifyvm "springms" --natpf1 "tcp-port27017,tcp,,27017,,27017"
```
Then run the dependent servers via `docker-compose` command line.
### Generate project skeleton
With [Spring Initializr](https://start.spring.io), you can get a Spring Boot based project skeleton in seconds.
Open your browser, go to [Spring Initializr](https://start.spring.io) page, fill the following essential fields for a project.
1. Choose **Java** as programming language.
2. Select the latest version of Spring Boot, **2.0.0.RELEASE** is the latest milestone at the moment when I wrote this post.
3. Search and select the required facilities will be used in your project, such as **Web**, **Data JPA**, **Data Redis**, **Security**, **Session**, **Lombok** etc.
4. Set project name(maven artifact id) to **post-service**.
Click **Generate Project** button or press **ALT+ENTER** keys to generate the project skeleton for downloading in your browser.
After downloading the generated archive, extract the files into your local disk and import it into your favorite IDE.
### REST API Overview
Following the REST convention and HTTP protocol specification, the REST APIs of post-service are designed as the following table.
| Uri | Http Method | Request | Response | Description |
| ---------------------- | ----------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| /posts | GET | | 200, [{'id':1, 'title'},{}] | Get all posts |
| /posts | POST | {'id':1, 'title':'test title','content':'test content'} | 201 | Create a new post |
| /posts/{postSlug} | GET | | 200, {'id':1, 'title'} | Get a post by postSlug |
| /posts/{postSlug} | PUT | {'title':'test title','content':'test content'} | 204 | Update a post |
| /posts/{postSlug} | DELETE | | 204 | Delete a post by postSlug |
| /posts/{postSlug}/comments | GET | | 200, [{'id':1, 'content':'comment content'},{}] | Get all comments of the certain post |
| /posts/{postSlug}/comments | POST | {'content':'test content'} | 201 | Create a new comment of the certain post |
### Create a new Entity
A domain entity is a persistent object in DDD concept, JPA `@Entity` a is a good match.
Create our first entity `Post`.
```java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
class Post extends AuditableEntity {
@JsonView(View.Summary.class)
@NotEmpty
private String title;
@NotEmpty
private String postSlug;
@JsonView(View.Public.class)
@NotEmpty
private String content;
@Enumerated(EnumType.STRING)
@Builder.Default
@JsonView(View.Summary.class)
private Status status = Status.DRAFT;
static enum Status {
DRAFT,
PUBLISHED
}
@PrePersist
public void slugify(){
this.postSlug = new Slugify().slugify(this.title);
}
}
```
`@Data`, `@Builder`, `@NoArgsConstructor` and `@AllArgsConstructor` are from project **Lombok**, which provides some helper annotations to make your source codes clean. With `@Data`, you can remove the tedious setters, getters of all fields, and the generic `equals`, `hashCode`, `toString` methods. `@Builder` will generate an inner builder class. `@NoArgsConstructor` will create a none-argument constructor, `@AllArgsConstructor` will take all fields as constructor arguments.
These annotations will be handled by JDK **Annotation Processing Tooling**, and generate code fragment in class files at compile time.
`@Entity` indicates `Post` is a standard JPA Entity.
`@PrePersist` is a JPA lifecycle hook. The `@PrePersist` annotated methods will be executed before the entity is persisted. We use post postSlug as the unique identifier of a `Post`, and we use `slugify()` method to generate the post postSlug automatically.
`AuditableEntity` is a helper class to centralize some common fields of a JPA entity in one place.
```java
@Data
@MappedSuperclass
@EntityListeners(value = AuditingEntityListener.class)
public abstract class AuditableEntity extends PersistableEntity {
public AuditableEntity() {
}
@CreatedDate
@JsonView(View.Summary.class)
protected LocalDateTime createdDate;
@Embedded
@AttributeOverrides(value = {
@AttributeOverride(name = "username", column = @Column(name = "author"))
})
@CreatedBy
@JsonView(View.Summary.class)
protected Username author;
}
```
`@CreatedDate` and `@CreatedBy` will fill in the creation date timestamp and the current user if the data auditing feature is enabled.
Use a standalone `@Configuration` bean to configure Spring Data JPA auditing.
```java
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@Slf4j
public class DataJpaConfig {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public AuditorAware<Username> auditorAware() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
log.debug("current authentication:" + authentication);
if (authentication == null || !authentication.isAuthenticated()) {
return () -> Optional.<Username>empty();
}
return () -> Optional.of(
Username.builder()
.username(((UserDetails) authentication.getPrincipal()).getUsername())
.build()
);
}
}
```
`AuditorAware` bean is required when you want to set auditor automatically. The population work is done by JPA `@EntityListener`, note there is a `@EntityListeners(value = AuditingEntityListener.class)` already added on the `AuditableEntity` class.
Have a look at the base `PersistableEntity`, it just defines the identity field of a JPA entity.
```java
@Data
@MappedSuperclass
public abstract class PersistableEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonView(View.Summary.class)
protected Long id;
public PersistableEntity() {
}
}
```
Similarly, create an another entity `Comment`.
```java
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Comment extends AuditableEntity {
@NotEmpty
@Size(min = 10)
private String content;
@Embedded
@AttributeOverrides(
value = {
@AttributeOverride(name = "postSlug", column = @Column(name = "post_slug"))
}
)
@JsonIgnore
private Slug post;
}
```
>NOTE: we do not user a JPA `@OneToMany` or `@ManyToOne` to connect two entities, but use a simple Post `Slug` identifier object instead. If one day this service becomes heavy, we could split comments into another standalone service.
### Create `Repository` for Entities
In DDD, a **Repository** is responsible for retrieving entities from or saving back to a **Repository**. Spring Data `Repository` interface and Spring Data JPA specific `JpaRepository` interface are a good match with **Repository** concept in DDD.
Create a `Repository` for the `Post` Entity.
```java
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
Optional<Post> findBySlug(String postSlug);
}
```
### Create a Domain Service
```java
@Service
@Transactional
public class PostService {
@Inject
private PostRepository postRepository;
public Post createPost(PostForm form) {
Post _post = Post.builder()
.title(form.getTitle())
.content(form.getContent())
.build();
Post saved = this.postRepository.save(_post);
return saved;
}
public Post updatePost(String postSlug, PostForm form) {
Post _post = this.postRepository.findBySlug(postSlug).orElseThrow(
()-> {
return new PostNotFoundException(postSlug);
}
);
_post.setTitle(form.getTitle());
_post.setContent(form.getContent());
Post saved = this.postRepository.save(_post);
return saved;
}
public void deletePost(String postSlug) {
this.postRepository.delete(this.postRepository.findBySlug(postSlug).orElseThrow(
() -> {
return new PostNotFoundException(postSlug);
}
));
}
}
```
In the `PostService`, the main purpose is treating with exceptions when creating or update a post. In a real world application, you could handle domain events in a domain service, eg. Post is published, etc.
### Expose RESTful APIs
Let's expose RESTful APIs for `Post` via `PostController`.
```java
@RestController
@RequestMapping("/posts")
@Slf4j
public class PostController {
private PostService postService;
private PostRepository postRepository;
private CommentRepository commentRepository;
public PostController(PostService postService, PostRepository postRepository, CommentRepository commentRepository) {
this.postService = postService;
this.postRepository = postRepository;
this.commentRepository = commentRepository;
}
@GetMapping()
@JsonView(View.Summary.class)
public ResponseEntity<Page<Post>> getAllPosts(
@RequestParam(value = "q", required = false) String keyword, //
@RequestParam(value = "status", required = false) Post.Status status, //
@PageableDefault(page = 0, size = 10, sort = "createdDate", direction = Direction.DESC) Pageable page) {
log.debug("get all posts of q@" + keyword + ", status @" + status + ", page@" + page);
Page<Post> posts = this.postRepository.findAll(PostSpecifications.filterByKeywordAndStatus(keyword, status), page);
return ok(posts);
}
@GetMapping(value = "/{postSlug}")
@JsonView(View.Public.class)
public ResponseEntity<Post> getPost(@PathVariable("postSlug") String postSlug) {
log.debug("get postsinfo by postSlug @" + postSlug);
Post post = this.postRepository.findBySlug(postSlug).orElseThrow(
() -> {
return new PostNotFoundException(postSlug);
}
);
log.debug("get post @" + post);
return ok(post);
}
@PostMapping()
public ResponseEntity<Void> createPost(@RequestBody @Valid PostForm post, HttpServletRequest request) {
log.debug("create a new post@" + post);
Post saved = this.postService.createPost(post);
log.debug("saved post id is @" + saved.getId());
URI createdUri = ServletUriComponentsBuilder
.fromContextPath(request)
.path("/posts/{postSlug}")
.buildAndExpand(saved.getSlug())
.toUri();
return created(createdUri).build();
}
@PutMapping(value = "/{postSlug}")
public ResponseEntity<Void> updatePost(@PathVariable("postSlug") String postSlug, @RequestBody @Valid PostForm form) {
log.debug("update post by id @" + postSlug + ", form content@" + form);
this.postService.updatePost(postSlug, form);
return noContent().build();
}
@DeleteMapping(value = "/{postSlug}")
public ResponseEntity<Void> deletePostById(@PathVariable("postSlug") String postSlug) {
log.debug("delete post by id @" + postSlug);
this.postService.deletePost(postSlug);
return noContent().build();
}
@GetMapping(value = "/{postSlug}/comments")
public ResponseEntity<Page<Comment>> getCommentsOfPost(
@PathVariable("postSlug") String postSlug,
@PageableDefault(page = 0, size = 10, sort = "createdDate", direction = Direction.DESC) Pageable page) {
log.debug("get comments of post@" + postSlug + ", page@" + page);
Page<Comment> commentsOfPost = this.commentRepository.findByPost(new Slug(postSlug), page);
log.debug("get post comment size @" + commentsOfPost.getTotalElements());
return ok(commentsOfPost);
}
@PostMapping(value = "/{postSlug}/comments")
public ResponseEntity<Void> createComment(
@PathVariable("postSlug") @NotNull String postSlug, @RequestBody CommentForm comment, HttpServletRequest request) {
log.debug("new comment of post@" + postSlug + ", comment" + comment);
Comment _comment = Comment.builder()
.post(new Slug(postSlug))
.content(comment.getContent())
.build();
Comment saved = this.commentRepository.save(_comment);
log.debug("saved comment @" + saved.getId());
URI location = ServletUriComponentsBuilder
.fromContextPath(request)
.path("/posts/{postSlug}/comments/{id}")
.buildAndExpand(postSlug, saved.getId())
.toUri();
return created(location).build();
}
}
```
In the above codes,
* `getAllPosts` method accepts a **q** (keyword) and a **status** (post status) and a `Pageable` as query parameters, it returns a `Page<Post>` result.
* The `postRepository.findAll` method accepts a `Specification` object. `Specification` is a wrapper class of JPA 2.0 criteria APIs, which provides effective type safe query condition building.
```java
public class PostSpecifications {
private PostSpecifications() {
}
public static Specification<Post> filterByKeywordAndStatus(
final String keyword,//
final Post.Status status) {
return (Root<Post> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (StringUtils.hasText(keyword)) {
predicates.add(
cb.or(
cb.like(root.get(Post_.title), "%" + keyword + "%"),
cb.like(root.get(Post_.content), "%" + keyword + "%")
)
);
}
if (status != null) {
predicates.add(cb.equal(root.get(Post_.status), status));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
}
}
```
According to the REST convention and HTTP protocol, a HTTP POST Method is used to create a new resource, it can return a 201 HTTP status code with the new created resource URI as HTTP header **Location**. And for update and delete operations on resource, return a 204 HTTP status. In the above codes, we apply these simple rules.
### Exception Handling
As mentioned above, in our `PostService`, I have added some extra steps to check the existence of a post by id in the `updatePost` and `deletePost` methods. If it is not found throw a `PostNotFoundException`.
```java
public class PostNotFoundException extends RuntimeException {
private String postSlug;
public PostNotFoundException(String postSlug) {
super("post:" + postSlug + " was not found");
this.postSlug = postSlug;
}
public String getSlug() {
return postSlug;
}
}
```
And we will handle this exception in a common class annotated with `@RestControllerAdvice`. When a `PostNotFoundException` is caught, `notFound` method will handle it convert the exception to a friendly message body and return a HTTP 404 status code to the client.
```java
@RestControllerAdvice
public class PostExceptionHandler {
@ExceptionHandler(PostNotFoundException.class)
public ResponseEntity notFound(PostNotFoundException ex, WebRequest req) {
Map<String, String> errors = new HashMap<>();
errors.put("entity", "POST");
errors.put("id", "" + ex.getSlug());
errors.put("code", "not_found");
errors.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errors);
}
}
```
### Miscellaneous
In a real world application, when you fetch post list, you maybe do not want to show all fields of the post. It is easy to control the representation view sent to client by customizing Jackson `JsonView`.
```java
public final class View {
interface Summary {
}
interface Public extends Summary {
}
}
```
In the `Post` class, add the following annotations to its fields.
```java
class Post extends AuditableEntity {
@JsonView(View.Summary.class)
private String title;
@JsonView(View.Public.class)
private String content;
@JsonView(View.Summary.class)
private Status status = Status.DRAFT;
}
```
In the `PostController`, add a `@JsonView` annotation.
```java
@JsonView(View.Summary.class)
public ResponseEntity<Page<Post>> getAllPosts()
```
Thus only the `Summary` labeled fields will be included in the result of `getAllPosts`.
Another small issue you could have found is the `Page` object serialized result looks a little tedious, too much unused fields from `Pageable` are included in the json result.
```json
{
"content" : [ {
"title" : "test post 2",
"postSlug" : "test-post-2",
"status" : "DRAFT",
"id" : 2,
"createdDate" : "2017-05-25T06:53:30",
"author" : {
"username" : "user"
}
}, {
"title" : "test post",
"postSlug" : "test-post",
"status" : "DRAFT",
"id" : 1,
"createdDate" : "2017-05-25T06:52:45",
"author" : {
"username" : "user"
}
} ],
"pageable" : {
"sort" : {
"sorted" : true,
"unsorted" : false
},
"pageSize" : 10,
"pageNumber" : 0,
"offset" : 0,
"paged" : true,
"unpaged" : false
},
"last" : true,
"totalElements" : 2,
"totalPages" : 1,
"sort" : {
"sorted" : true,
"unsorted" : false
},
"numberOfElements" : 2,
"first" : true,
"size" : 10,
"number" : 0
}
```
Create a `@JsonComponent` bean to customize the serialized json result.
```java
@JsonComponent
public class PageJsonSerializer extends JsonSerializer<PageImpl> {
@Override
public void serialize(PageImpl value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
gen.writeStartObject();
gen.writeNumberField("number", value.getNumber());
gen.writeNumberField("numberOfElements", value.getNumberOfElements());
gen.writeNumberField("totalElements", value.getTotalElements());
gen.writeNumberField("totalPages", value.getTotalPages());
gen.writeNumberField("size", value.getSize());
gen.writeFieldName("content");
serializers.defaultSerializeValue(value.getContent(), gen);
gen.writeEndObject();
}
}
```
When this bean is activated, the result cloud look like the following:
```json
{
"content" : [ {
"title" : "test post 2",
"postSlug" : "test-post-2",
"status" : "DRAFT",
"id" : 2,
"createdDate" : "2017-05-25T06:53:30",
"author" : {
"username" : "user"
}
}, {
"title" : "test post",
"postSlug" : "test-post",
"status" : "DRAFT",
"id" : 1,
"createdDate" : "2017-05-25T06:52:45",
"author" : {
"username" : "user"
}
} ],
"numberOfElements" : 2,
"totalElements" : 2,
"totalPages" : 1,
"size" : 10,
"number" : 0
}
```
The details of **auth-service** and **user-service**, please check the [source codes](https://github.com/hantsy/spring-Microservices -sample) and explore them yourself.
## Secures Microservices
Let's have a look at how a user get authentication in this demo.
1. A user try to get authentication from **auth-service** using usename and password.
2. If it is a valid user and it is authenticated successfully, the response header will include a **X-AUTH-TOKEN** header.
3. Extract the value of **X-AUTH-TOKEN** header, and add **X-AUTH-TOKEN** header into the new request to get access permission of the protected resource, such as APIs in **post-service**.
We use Spring Session and Redis to archive this purpose.
In all services, we add the following codes to resolve Session by HTTP header instead of Cookie.
```java
@Configuration
public class RedisSessionConfig {
@Bean
public HttpSessionIdResolver httpSessionStrategy() {
return HeaderHttpSessionIdResolver.xAuthToken();
}
}
```
And add the follow configuration in the *application.yml* to tell Spring to use Redis as session store.
```yml
spring:
session:
store-type: redis
```
In **auth-service**, use a controller to serve user authentication.
```java
@RequestMapping(value = "/auth")
@RestController
public class AuthenticationController {
@PostMapping(value = "/signin")
public AuthenticationResult signin(
@RequestBody @Valid AuthenticationRequest authenticationRequest,
HttpServletRequest request) {
if (log.isDebugEnabled()) {
log.debug("signin form data@" + authenticationRequest);
}
return this.handleAuthentication(
authenticationRequest.getUsername(),
authenticationRequest.getPassword(),
request);
}
private AuthenticationResult handleAuthentication(
String username,
String password,
HttpServletRequest request) {
final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
username,
password
);
final Authentication authentication = this.authenticationManager
.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
final HttpSession session = request.getSession(true);
session.setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
SecurityContextHolder.getContext());
return AuthenticationResult.builder()
.name(authentication.getName())
.roles(authentication.getAuthorities().stream().map(r -> r.getAuthority()).collect(Collectors.toList()))
.token(session.getId())
.build();
}
...
```
When you are authenticated, the `/auth/signin` endpoint will return userinfo and token(session id) in the result.
To protect the resource APIs, just add a `SecurityConfig`. The following is a configuration for post-service. All **GET** methods are permitted, and when **DELETE** a post, you should have a **ADMIN** role.
```java
@Configuration
@Slf4j
public class SecurityConfig {
@Bean
public WebSecurityConfigurerAdapter securityConfigBean(){
return new WebSecurityConfigurerAdapter() {
@Override
protected void configure(HttpSecurity http) throws Exception {
// We need this to prevent the browser from popping up a dialog on a 401
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/posts/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/posts/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().disable();
}
};
}
}
```
Let's try to run the demo in local system.
## Running Microservices application
In your local development environment, it is easy to run the services one by one via Spring Boot maven plugin or build and run them in local Docker container via a predefined *docker compose* file.
### Running application via Maven plugin
Make sure the dependent servers are running by executing `docker-compose up`.
Enter the root folder of every service, execute the following command to start up them one by one.
```
mvn spring-boot:run // run in user-service, auth-service, post-service
```
The following endpoints will be provided.
| Service | Url | Description |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| auth-service | http://localhost:8000/user,http://localhost:8000/auth | Authentication APIs(signin, signup, signout), user info |
| user-service | http://localhost:8001/users | User management APIs |
| post-service | http://localhost:8002/posts | Post and comment APIs |
Follow the authentication flow to have a try.
When all service are running successfully, firstly try to get authentication.
```
curl -v http://localhost:8000/user -u user:test123
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8000 (#0)
* Server auth using Basic with user 'user'
> GET /user HTTP/1.1
> Host: localhost:8000
> Authorization: Basic dXNlcjp0ZXN0MTIz
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200
< 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-Auth-Token: 49090ba7-e641-45e3-935b-894a43b85f62
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Mon, 15 May 2017 09:29:14 GMT
<
{"name":"user","roles":["USER"]}* Connection #0 to host localhost left intact
```
You will see a `X-Auth-Token` header in the response.
Put this header into a new request when you want to access the protected resources in another resource server.
```
curl -v http://localhost:8001/user -H "x-auth-token: 49090ba7-e641-45e3-935b-894a43b85f62"
```
Try to add some posts data:
```
>curl -v http://localhost:8002/posts
-H "x-auth-token: 49090ba7-e641-45e3-935b-894a43b85f62"
-H "Accept: application/json"
-H "Content-Type: application/json;charset=UTF-8"
-X POST
-d "{\"title\": \"test post\", \"content\":\"test content of post\"}"
```
You will see the result. It returns 201 status, and set `Location` header to the new created `Post`.
```
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8002 (#0)
> POST /posts HTTP/1.1
> Host: localhost:8002
> User-Agent: curl/7.54.0
> x-auth-token: 49090ba7-e641-45e3-935b-894a43b85f62
> Accept: application/json
> Content-Type: application/json;charset=UTF-8
> Content-Length: 56
>
* upload completely sent off: 56 out of 56 bytes
< HTTP/1.1 201
< 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
< Location: http://localhost:8002/posts/4
< Content-Length: 0
< Date: Thu, 18 May 2017 06:54:40 GMT
```
Fetch the new created post.
```
curl -v http://localhost:8002/posts/4 -H "Accept: application/json"
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8002 (#0)
> GET /posts/4 HTTP/1.1
> Host: localhost:8002
> User-Agent: curl/7.54.0
> Accept: application/json
>
< HTTP/1.1 200
< 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
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Thu, 18 May 2017 06:59:42 GMT
<
{"id":4,"title":"test post","content":"test content of post","status":"DRAFT","author":null,"createdDate":null}*
```
### Running application via Docker Compose
Firstly build all services into Docker images.
Prepare a *Dockfile* for every service. For example, create a Dockerfile in the root folder of *post-service* project.
```dockerfile
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD ./target/post-service-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
```
The Dockerfile in **auth-service** and **user-service** are similar, just replaced the maven build target **jar** file.
```dockerfile
FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD ./target/auth-service-0.0.1-SNAPSHOT.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
```
Create a *Dockerfile* for ngnix. We will use ngnix as a reverse proxy to unite the entry of the application.
```dockerfile
# Set nginx base image
FROM nginx
#RUN mkdir /etc/nginx/ssl
#COPY ssl /etc/nginx/ssl
# Copy custom configuration file from the current directory
COPY nginx.conf /etc/nginx/nginx.conf
#COPY www /usr/share/nginx/www
#COPY archive /usr/share/nginx/archive
```
And the content of *ngnix.conf*.
```conf
worker_processes 1;
events { worker_connections 1024; }
http {
sendfile on;
server {
listen 80;
server_name localhost;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
location /users {
proxy_pass http://user-service:8001;
}
location /posts {
proxy_pass http://post-service:8002;
}
location / {
proxy_pass http://auth-service:8000;
}
}
}
```
Create a standalone docker-compose.local.yml file to run all services.
```yml
version: '3.1' # specify docker-compose version
services:
nginx-proxy:
image: hantsy/nginx-proxy
container_name: nginx-proxy
build:
context: ./nginx
dockerfile: Dockerfile
depends_on:
- auth-service
- user-service
- post-service
ports:
- "80:80"
auth-service:
image: hantsy/auth-service
container_name: auth-service
build:
context: ./auth-service # specify the directory of the Dockerfile
dockerfile: Dockerfile
environment:
USERDB_URL: jdbc:mysql://userdb:3306/userdb
REDIS_HOST: redis
ports:
- "8000:8000" #specify ports forewarding
depends_on:
- userdb
- redis
user-service:
image: hantsy/user-service
container_name: user-service
build:
context: ./user-service
dockerfile: Dockerfile
environment:
USERDB_URL: jdbc:mysql://userdb:3306/userdb
REDIS_HOST: redis
ports:
- "8001:8001" #specify ports forewarding
depends_on:
- userdb
- redis
post-service:
image: hantsy/post-service
container_name: post-service
build:
context: ./post-service
dockerfile: Dockerfile
environment:
POSTDB_URL: jdbc:mysql://postdb:3306/postdb
REDIS_HOST: redis
ports:
- "8002:8002" #specify ports forewarding
depends_on:
- postdb
- redis
```
Run all services in your local system or a staging server.
Build the project via `mvn` command.
```
mvn clean package -DskipTests
```
Then run the following command to run all services.
```
docker-compose -f docker-compose.yml -f docker-compose.local.yml up --build
```
The `--build` parameter tells Docker build Docker images for all services firstly, then create containers based on the built images.
We have run a Nginx a reverse proxy, all APIs can be accessed through a single entry.
The following services will be provided.
| Service | Url | Description |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| auth-service | http://localhost/user,http://localhost/auth | Authentication APIs(signin, signup, signout), user info |
| user-service | http://localhost/users | User management APIs |
| post-service | http://localhost/posts | Post and comment APIs |
Next, let's try the endpoints by `curl` command.
Get authentication by sending user/password pair via HTTP BASIC header.
```
curl -v http://localhost/user -u user:test123
>
< HTTP/1.1 200
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:49:52 GMT
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< 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-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8
<
{"name":"user","roles":["USER"]}* Connection #0 to host localhost left intact
```
As you see the response headers includes a **X-Auth-Token** item.
Then add this header to the request headers when creating a new post, it return a successful *CREATED* status, and the new created post can be located via *Location* header in the response.
```
curl -v http://localhost/posts -X POST -H "X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8" -H "Content-Type:application/json" -d "{\"title\": \"test post\", \"content\":\"test content of post\"}"
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> POST /posts HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8
> Content-Type:application/json
> Content-Length: 56
>
* upload completely sent off: 56 out of 56 bytes
< HTTP/1.1 201
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:52:46 GMT
< Content-Length: 0
< Connection: keep-alive
< 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
< Location: http://localhost/posts/1
<
* Connection #0 to host localhost left intact
```
Create another new post.
```
curl -v http://localhost/posts -X POST -H "X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8" -H "Content-Type:application/json" -d "{\"title\": \"test post 2\", \"content\":\"test content of post 2\"}"
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> POST /posts HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8
> Content-Type:application/json
> Content-Length: 60
>
* upload completely sent off: 60 out of 60 bytes
< HTTP/1.1 201
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:53:29 GMT
< Content-Length: 0
< Connection: keep-alive
< 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
< Location: http://localhost/posts/test-post-2
<
* Connection #0 to host localhost left intact
```
Get all post, and verify the created posts.
```
curl -v http://localhost/posts -H "Accpet:application/json"
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /posts HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> Accpet:application/json
>
< HTTP/1.1 200
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:53:58 GMT
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< 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
<
{
"content" : [ {
"title" : "test post 2",
"postSlug" : "test-post-2",
"status" : "DRAFT",
"id" : 2,
"createdDate" : "2017-05-25T06:53:30",
"author" : {
"username" : "user"
}
}, {
"title" : "test post",
"postSlug" : "test-post",
"status" : "DRAFT",
"id" : 1,
"createdDate" : "2017-05-25T06:52:45",
"author" : {
"username" : "user"
}
} ],
"pageable" : {
"sort" : {
"sorted" : true,
"unsorted" : false
},
"pageSize" : 10,
"pageNumber" : 0,
"offset" : 0,
"paged" : true,
"unpaged" : false
},
"last" : true,
"totalElements" : 2,
"totalPages" : 1,
"sort" : {
"sorted" : true,
"unsorted" : false
},
"numberOfElements" : 2,
"first" : true,
"size" : 10,
"number" : 0
}* Connection #0 to host localhost left intact
```
Create a comment for "test post 2". Do not forget to add the **X-Auth-Token** header to the request headers.
```
curl -v http://localhost/posts/test-post-2/comments -X POST -H "X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8" -H "Content-Type:application/json" -d "{ \"content\":\"conmment content of post 2\"}"
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> POST /posts/test-post-2/comments HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8
> Content-Type:application/json
> Content-Length: 41
>
* upload completely sent off: 41 out of 41 bytes
< HTTP/1.1 201
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:54:59 GMT
< Content-Length: 0
< Connection: keep-alive
< 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
< Location: http://localhost/posts/test-post-2/comments/3
<
* Connection #0 to host localhost left intact
```
Create another comment.
```
curl -v http://localhost/posts/test-post-2/comments -X POST -H "X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8" -H "Content-Type:application/json" -d "{ \"content\":\"conmment content of post, another comment\"}"
Note: Unnecessary use of -X or --request, POST is already inferred.
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> POST /posts/test-post-2/comments HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> X-Auth-Token: 8b185a90-37db-444a-832b-6cbcd6db6df8
> Content-Type:application/json
> Content-Length: 56
>
* upload completely sent off: 56 out of 56 bytes
< HTTP/1.1 201
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:55:21 GMT
< Content-Length: 0
< Connection: keep-alive
< 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
< Location: http://localhost/posts/test-post-2/comments/4
<
* Connection #0 to host localhost left intact
```
Now get all comments of the post *test-post-2* to verify the comments.
```
curl -v http://localhost/posts/test-post-2/comments -H "Accpet:application/json"
* timeout on name lookup is not supported
* Trying ::1...
* TCP_NODELAY set
* connect to ::1 port 80 failed: Connection refused
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET /posts/test-post-2/comments HTTP/1.1
> Host: localhost
> User-Agent: curl/7.54.0
> Accept: */*
> Accpet:application/json
>
< HTTP/1.1 200
< Server: nginx/1.13.0
< Date: Thu, 25 May 2017 06:55:35 GMT
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< 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
<
{
"content" : [ {
"content" : "conmment content of post, another comment",
"id" : 4,
"createdDate" : "2017-05-25T06:55:22",
"author" : {
"username" : "user"
}
}, {
"content" : "conmment content of post 2",
"id" : 3,
"createdDate" : "2017-05-25T06:54:59",
"author" : {
"username" : "user"
}
} ],
"pageable" : {
"sort" : {
"sorted" : true,
"unsorted" : false
},
"pageSize" : 10,
"pageNumber" : 0,
"offset" : 0,
"paged" : true,
"unpaged" : false
},
"last" : true,
"totalElements" : 2,
"totalPages" : 1,
"sort" : {
"sorted" : true,
"unsorted" : false
},
"numberOfElements" : 2,
"first" : true,
"size" : 10,
"number" : 0
}* Connection #0 to host localhost left intact
```
## Testing Microservices
As stated in the previous sections, every single service is a small Spring Boot application. To test the whole Microservices application, firstly you should fully test the services/components themselves.
### Testing Single Service
Testing a single service is similar to testing a general Spring Boot application, for example, in this application, to test post service, you should test very components in this service.
* Simple POJOs, such as `@Entity` classes, DTOs.
* Database related facilities, such as JPA and `Repository` classes.
* Web layer, such as `Controller` and exception handlers.
* Additionally, integration tests is a must to ensure the application is working well close to a real world deployment environment.
#### Testing POJOs
It is very simple, like testing a single POJO classes in a Java application, no dependent object in it. An example of testing the `Post` entity class.
```java
public class PostTest {
@Test
public void testSlug() {
System.out.println("getSlug");
Post instance = new Post();
instance.setTitle("test post 1");
instance.slugify();
assertEquals("test-post-1", instance.getSlug());
}
}
```
#### Testing Repository
There are some utilities can be used to test a Spring Data `Repository` bean.
For Spring Data JPA, there is a `@DataJpaTest` annotation which will autoconfigure the essential dependencies for testing a `Repository` bean, that means it does not load all beans from the application context when running the tests. And when adding an embedded RDBMS, such as H2 in the test classpath, it will bypass the real database configuration in the application properties and use the embedded database instead when running the tests.
Additionally, Spring Boot provides a `TestEntityManager` bean which is similar to the standard `EntityManager`, but provides more methods for test purpose.
Add H2 to test scope in the *pom.xml* file.
```xml
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
```
Create a test calss to test `PostRepository`.
```java
@RunWith(SpringRunner.class)
@DataJpaTest()
@Slf4j
public class PostRepositoryTest {
@Autowired
private TestEntityManager em;
@Autowired
PostRepository posts;
@Before
public void setup() {
assertNotNull("posts is not null", posts);
posts.deleteAllInBatch();
em.persist(Post.builder().title("test post 1").content("test content of test post 1").build());
}
@Test
public void testGetAllPosts() {
assertTrue(1 == posts.findAll().size());
Post post = posts.findAll().get(0);
assertTrue("test-post-1".equals(post.getSlug()));
}
}
```
#### Testing PostService
The `PostService` depends on `PostRepsoitory` bean. To test the internal logic of `PostService`, we can mock the dependent beans(eg. `PostRepository` bean) and stub the behavior of `PostRepository` bean, and verify the logic in `PostService` works as expected.
```java
@RunWith(SpringRunner.class)
@Slf4j
public class PostServiceTest {
@MockBean
private PostRepository posts;
@Autowired
private PostService postService;
@Test
public void createPost() {
final String TITLE = "test post title";
final String CONTENT = "test post content";
final PostForm input = PostForm.builder().title(TITLE).content(CONTENT).build();
Post expected = Post.builder().title(TITLE).content(CONTENT).build();
expected.setId(1L);
given(posts.save(Post.builder().title(input.getTitle()).content(input.getContent()).build()))
.willReturn(expected);
Post returned = postService.createPost(input);
assertTrue(returned == expected);
verify(posts, times(1)).save(any(Post.class));
verifyNoMoreInteractions(posts);
}
@TestConfiguration
@Import(PostService.class)
static class TestConfig {
}
}
```
#### Testing web facilities
For Spring WebMVC applications, Spring Boot includes a simple `@WebMvcTest` to prepare the test environment for testing controller classes. When running a test annotated with `@WebMvcTest`, a `MockMvc` bean is available in the application context. In the `@WebMvcTest`, use the `controllers` to specify the controllers you wan to tests, and there is a `secure` attribute indicates if enabling Spring Security support in this test.
```java
@RunWith(SpringRunner.class)
@Slf4j
@WebMvcTest(controllers = PostController.class, secure = false)
public class PostControllerTest {
@MockBean
PostRepository posts;
@MockBean
CommentRepository comments;
@MockBean
PostService postService;
@Autowired
ObjectMapper objectMapper;
@Autowired
MockMvc mockMvc;
@Test
public void createPost() throws Exception {
Post _data = Post.builder().slug("test-my-first-post").title("my first post").content("my content of my post").build();
given(this.postService.createPost(any(PostForm.class)))
.willReturn(_data);
this.mockMvc
.perform(
post("/posts")
.content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andExpect(header().exists("Location"));
verify(this.postService, times(1)).createPost(any(PostForm.class));
verifyNoMoreInteractions(this.postService);
}
}
```
> Note: In the latest Spring Boot, the **secure** attribute of `@WebMvcTest` is deprecated. If you want to exclude Spring Security configuration, you have to exclude the Spring Security related Configurations, see [this example](https://github.com/hantsy/spring-webmvc-jwt-sample/blob/master/src/test/java/com/example/demo/VehicleControllerTest.java#L32).
For fine grained configure the `MockMvc`, you can create it through `MockMvcBuilders.standaloneSetup` or `MockMvcBuilders.webAppContextSetup`, the former will choose the controllers to tests, and the later will load all controllers from the application context.
The following is an example test using `MockMvcBuilders.standaloneSetup` to configure a `MockMvc` object.
```java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@RunWith(SpringRunner.class)
@Slf4j
public class ApplicationControllerMockMvcTest {
@Autowired
WebApplicationContext wac;
@MockBean
PostRepository posts;
@MockBean
CommentRepository comments;
@MockBean
PostService postService;
@Autowired
ObjectMapper objectMapper;
@Autowired
FilterChainProxy springSecurityFilterChain;
MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = standaloneSetup(new PostController(postService, posts, comments))
.setCustomArgumentResolvers(
new PageableHandlerMethodArgumentResolver()
)
.setMessageConverters(
new MappingJackson2HttpMessageConverter(objectMapper)
)
.alwaysDo(print())
.apply(springSecurity(springSecurityFilterChain))
.build();
}
@Test
//@Ignore
public void testGetAllPosts() throws Exception {
given(this.posts
.findAll(any(Specification.class), any(Pageable.class)))
.willReturn(
new PageImpl(
Arrays.asList(
Post.builder().title("my first post1").content("my content of my post1").build(),
Post.builder().title("my first post2").content("my content of my post2").build(),
Post.builder().title("my first post3").content("my content of my post3").build()
),
PageRequest.of(0, 10),
3L
)
);
MvcResult result = this.mockMvc
.perform(
get("/posts?q=my")
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andExpect(jsonPath("$.content[*].title", hasItem("my first post1")))
.andReturn();
log.debug("mvc result:::" + result.getResponse().getContentAsString());
verify(this.posts, times(1)).findAll(any(Specification.class), any(Pageable.class));
verifyNoMoreInteractions(this.posts);
}
@Test
public void createPostWithoutAuthentication() throws Exception {
Post _data = Post.builder().title("my first post").content("my content of my post").build();
given(this.postService.createPost(any(PostForm.class)))
.willReturn(_data);
MvcResult result = this.mockMvc
.perform(
post("/posts")
.content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isUnauthorized())
.andReturn();
log.debug("mvc result::" + result.getResponse().getContentAsString());
verify(this.postService, times(0)).createPost(any(PostForm.class));
verifyNoMoreInteractions(this.postService);
}
@Test
@WithMockUser
public void createPostWithMockUser() throws Exception {
Post _data = Post.builder().title("my first post").content("my content of my post").build();
given(this.postService.createPost(any(PostForm.class)))
.willReturn(_data);
MvcResult result = this.mockMvc
.perform(
post("/posts")
.content(objectMapper.writeValueAsString(PostForm.builder().title("my first post").content("my content of my post").build()))
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andExpect(header().string(HttpHeaders.LOCATION, containsString("/posts")))
.andReturn();
log.debug("mvc result::" + result.getResponse().getContentAsString());
verify(this.postService, times(1)).createPost(any(PostForm.class));
}
}
```
Similarly you can build a `MockMvc` object using `MockMvcBuilders.webAppContextSetup`.
```java
this.mockMvc = webAppContextSetup(this.wac)
.alwaysDo(print())
.apply(springSecurity(springSecurityFilterChain))
.build();
```
RestAssured also extends the MockMvc support through `io.rest-assured:spring-mock-mvc` module, explore the [RestAsssured MockMVC integration example](https://github.com/hantsy/spring-microservice-sample/blob/master/post-service/src/test/java/com/example/post/ApplicationRestAssuredMockMvcTest.java) yourself.
Next let's move on a small feature, I've created a `View` class to limit the result in the final JSON view. Let's create a test for verify it. Spring Boot provides a `@JsonTest` and allow you test the JSON serialization and deserialization.
```java
@RunWith(SpringRunner.class)
@JsonTest
@Slf4j
public class JsonViewTest {
@Autowired
private JacksonTester<Post> json;
@Test
public void serializeJson() throws IOException {
Post details = Post.builder().title("test title").content("test content").build();
assertThat(this.json.write(details)).extractingJsonPathStringValue("@.title")
.isEqualTo("test title");
assertThat(this.json.write(details)).extractingJsonPathStringValue("@.content")
.isEqualTo("test content");
}
@Test
public void serializeJsonWithView() throws IOException {
Post details = Post.builder().title("test title").content("test content").build();
ObjectMapper mapper = new ObjectMapper();
String result = mapper
.writerWithView(View.Summary.class)
.writeValueAsString(details);
log.debug("result:::" + result);
assertTrue(result.contains("test title"));
assertTrue(!result.contains("test content"));
}
}
```
#### Integration Tests
Now web run the application with all dependent services, esp. with the real database.
The following is a sample integration tests.
```java
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@Slf4j
public class IntegrationTests {
@LocalServerPort
int port;
@Autowired
PostRepository posts;
@Autowired
CommentRepository comments;
String test_title = "test title";
String test_content = "test content";
String test_comment = "test_comment";
String slug = "";
@Before
public void setup() {
RestAssured.reset();
RestAssured.port = this.port;
this.comments.deleteAllInBatch();
this.posts.deleteAllInBatch();
Post post = posts.save(
Post.builder()
.title(test_title)
.content(test_content)
.build()
);
log.debug("saved post:" + post);
this.slug = post.getSlug();
log.debug("print all posts:");
posts.findAll().forEach(System.out::println);
Comment comment = this.comments.save(
Comment.builder()
.content(test_comment)
.post(new PostSlug(this.slug))
.build()
);
log.debug("saved comment:" + comment);
}
@Test
public void testGetNoneExistingPost_shouldReturn404() throws Exception {
//@formatter:off
when()
.get("/posts/100000")
.then()
.statusCode(HttpStatus.SC_NOT_FOUND);
//@formatter:on
}
@Test
public void testGetAllPosts_shouldBeOK() throws Exception {
//@formatter:off
when()
.get("/posts")
.then()
.body("content[0].title", is(test_title))
.statusCode(HttpStatus.SC_OK);
//@formatter:on
}
@Test
public void testGetPostBySlug_shouldBeOK() throws Exception {
//@formatter:off
when()
.get("/posts/"+ this.slug)
.then()
.body("title", is(test_title))
.body("content", is(test_content))
.statusCode(HttpStatus.SC_OK);
//@formatter:on
}
@Test
public void testGetCommentsOfPostBySlug_shouldBeOK() throws Exception {
//@formatter:off
when()
.get("/posts/"+ this.slug+"/comments")
.then()
.body("content[0].content", is(test_comment))
.statusCode(HttpStatus.SC_OK);
//@formatter:on
}
//-------------- test with auth -----------------------
@Test
public void testCreateAPost_withoutUserAuth_shouldReturn401() throws Exception {
PostForm _data = PostForm.builder().title(test_title).content(test_content).build();
//@formatter:off
given()
//.auth().basic("user", "password")
.body(_data)
.contentType(ContentType.JSON)
.when()
.post("/posts")
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
//@formatter:on
}
@Test
public void testCreateAPost_withUserAuth_shouldBeOK() throws Exception {
PostForm _data = PostForm.builder().title(test_title).content(test_content).build();
//@formatter:off
given()
.auth().basic("user", "password")
.body(_data)
.contentType(ContentType.JSON)
.when()
.post("/posts")
.then()
.header("Location", containsString("/posts"))
.statusCode(HttpStatus.SC_CREATED);
//@formatter:on
}
@Test
public void testUpdateAPost_withoutUserAuth_shouldReturn401() throws Exception {
PostForm _data = PostForm.builder().title(test_title).content(test_content).build();
//@formatter:off
given()
//.auth().basic("user", "password")
.body(_data)
.contentType(ContentType.JSON)
.when()
.put("/posts/"+ this.slug)
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
//@formatter:on
}
@Test
public void testUpdateAPost_withUserAuth_shouldBeOK() throws Exception {
PostForm _data = PostForm.builder().title(test_title).content(test_content).build();
//@formatter:off
given()
.auth().basic("user", "password")
.body(_data)
.contentType(ContentType.JSON)
.when()
.put("/posts/"+ this.slug)
.then()
.statusCode(HttpStatus.SC_NO_CONTENT);
//@formatter:on
}
@Test
public void testDeleteAPost_withoutAuth_shouldReturn401() throws Exception {
//@formatter:off
when()
.delete("/posts/"+ this.slug)
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
//@formatter:on
}
@Test
public void testDeleteAPost_withUserAuth_shouldReturn403() throws Exception {
//@formatter:off
given()
.auth().basic("user", "password")
.when()
.delete("/posts/"+ this.slug)
.then()
.statusCode(HttpStatus.SC_FORBIDDEN);
//@formatter:on
}
@Test
public void testDeleteAPost_withAdminAuth_shouldOK() throws Exception {
//@formatter:off
given()
.auth().basic("admin", "password")
.when()
.delete("/posts/"+ this.slug)
.then()
.statusCode(HttpStatus.SC_NO_CONTENT);
//@formatter:on
}
@Test
public void testCreateACommentsOfPostBySlug_withoutAuth_shouldReturn401() throws Exception {
CommentForm _data = CommentForm.builder().content(test_comment).build();
//@formatter:off
given()
.body(_data)
.contentType(ContentType.JSON)
.when()
.post("/posts/"+ this.slug+"/comments")
.then()
.statusCode(HttpStatus.SC_UNAUTHORIZED);
//@formatter:on
}
@Test
public void testCreateACommentsOfPostBySlug_withUserAuth_shouldBeOk() throws Exception {
CommentForm _data = CommentForm.builder().content(test_comment).build();
//@formatter:off
given()
.auth().basic("user", "password")
.body(_data)
.contentType(ContentType.JSON)
.when()
.post("/posts/"+ this.slug+"/comments")
.then()
.header("Location", containsString("/posts/"+ this.slug+"/comments"))
.statusCode(HttpStatus.SC_CREATED);
//@formatter:on
}
@TestComponent
@Slf4j
static class TestUserDetailsService implements UserDetailsService {
private final PasswordEncoder passwordEncoder;
TestUserDetailsService(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails user = User.withUsername("user")
.password(passwordEncoder.encode("password"))
.roles("USER")
.accountExpired(false)
.accountLocked(false)
.credentialsExpired(false)
.disabled(false)
.build();
UserDetails admin = User.withUsername("admin")
.password(passwordEncoder.encode("password"))
.roles("ADMIN")
.accountExpired(false)
.accountLocked(false)
.credentialsExpired(false)
.disabled(false)
.build();
log.debug("dummy user:" + user);
log.debug("dummy admin:" + admin);
if ("user".equals(username)) {
return user;
} else {
return admin;
}
}
}
@TestConfiguration
@Slf4j
@Import(TestUserDetailsService.class)
@Order(-1)
static class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/posts/**").permitAll()
.antMatchers(HttpMethod.DELETE, "/posts/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
}
```
From the former sections, we have introduced how to get authentication from the **auth-service**. In the above codes, we add some custom Security configuration to override Spring [Security Config](https://github.com/hantsy/spring-microservice-sample/blob/master/post-service/src/main/java/com/example/post/PostServiceApplication.java#L51) to isolate the authentication from **auth-service**. Here we use a simple HTTP Basic authentication instead.
### Testing against External Service
In our application, the auth service depends on user service to complete the authentication process. There is a `UserServiceClient` in the auth service used for signup and authentication.
```java
@Component
public class UserServiceClient {
private RestTemplate restTemplate;
private ObjectMapper objectMapper;
@Value("${services.user-service-url}")
private String userServiceUrl;
public UserServiceClient(RestTemplateBuilder builder, ObjectMapper objectMapper) {
this.restTemplate = builder.build();
this.objectMapper = objectMapper;
}
public void handleSignup(SignupForm form) {
try {
ResponseEntity<Void> response = this.restTemplate.postForEntity(userServiceUrl + "/users", form, Void.class);
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == CONFLICT) {
Map map = null;
try {
map = objectMapper.readValue(e.getResponseBodyAsByteArray(), Map.class);
} catch (IOException e1) {
e1.printStackTrace();
}
throw new SignupConflictException((String) map.get("message"));
}
}
}
public User findByUsername(String username) {
try {
ResponseEntity<User> response = this.restTemplate.getForEntity(userServiceUrl + "/users/{username}", User.class, username);
return response.getBody();
} catch (HttpClientErrorException e) {
if (e.getStatusCode() == NOT_FOUND) {
return null;
}
}
return null;
}
}
```
In the above codes, we use `RestTemplate` to access the remote *user service*. To test `UserServiceClient`, we have to mock a remote rest server to ensure the endpoints is available when running the tests. There are some several approaches to archive this.
* Spring provides a `MockRestServiceServer` to setup a mock rest service easily.
* [WireMock](http://wiremock.org/) is a more common solution for mocking HTTP endpoints.
Next, let's explore them one by one.
#### MockRestServiceServer
The following is an example using `MockRestServiceServer`. The stubbing step is similar to the Mockito `when`/`given`, set the mocked data when submitting a specific request.
```java
@RunWith(SpringRunner.class)
@RestClientTest(UserServiceClient.class)
@Slf4j
public class UserServiceClientTest {
@Value("${services.user-service-url:http://localhost:8001}")
private String userServiceUrl;
@Autowired
private UserServiceClient client;
@Autowired
private MockRestServiceServer server;
@Test
public void testFindbyUsername() {
this.server.expect(requestTo(userServiceUrl + "/users/user"))
.andRespond(withSuccess(new ClassPathResource("/find-user-by-username.json"), MediaType.APPLICATION_JSON_UTF8));
//.andRespond(withSuccess("{\"username\":\"user\",\"password\":\"password\",\"email\":\"user@example.com\"}", MediaType.APPLICATION_JSON_UTF8));
User user = this.client.findByUsername("user");
assertNotNull(user);
assertEquals("user", user.getUsername());
this.server.verify();
}
@Test
public void testFindbyUsername_notFound() {
this.server.expect(requestTo(userServiceUrl + "/users/user1"))
.andRespond(withStatus(NOT_FOUND));
User user = this.client.findByUsername("user1");
assertNull(user);
this.server.verify();
}
}
```
Similar to Spring Boot `@WebMvcTest`, `@DataJpaTest`, etc. The `@RestClientTest` is also a *slice test* utility which only provides a `RestTemplateBuilder` in the test context.
#### WireMock
WireMock is a general purpose solution for mocking HTTP endpoints.
There is an example of using WireMock to test `UserServiceClient` .
```java
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
public class UserServiceClientWireMockTest {
@Value("${services.user-service-url:http://localhost:8001}")
private String userServiceUrl;
@Autowired
private UserServiceClient client;
@Rule
public WireMockRule wireMockRule = new WireMockRule(options().port(8001));
@Before
public void setup() {
WireMock.reset();
}
@Test
public void testFindbyUsername() {
stubFor(
get("/users/user")
//.withHeader("Accept", equalTo(MediaType.APPLICATION_JSON_VALUE))
.willReturn(
okJson("{\"username\":\"user\",\"password\":\"password\",\"email\":\"user@example.com\"}")
)
);
User user = this.client.findByUsername("user");
assertNotNull(user);
assertEquals("user", user.getUsername());
verify(1, getRequestedFor(urlMatching( "/users/user")));
}
@Test
public void testFindbyUsername_notFound() {
stubFor(
get( "/users/user1")
//.withHeader("Accept", equalTo(MediaType.APPLICATION_JSON_VALUE))
.willReturn(
aResponse()
.withStatus(HttpStatus.SC_NOT_FOUND)
)
);
User user = this.client.findByUsername("user1");
assertNull(user);
verify(1, getRequestedFor(urlMatching( "/users/user1")));
}
}
```
In the above codes, WireMock provides a `@Rule` to wire the stubbing into the lifecycle of the JUnit runner.
### Testing Service-to-Service Communication
The above `MockRestServiceServer` or `WireMock` is widely used when the existing external service is out of control, eg. it is from the 3rd party company or organization.
In our application, the auth service and user service are developed by ourselves, but may be produced by two different teams.
Assume when the auth service requires to embed the result of a `/users` endpoints that should be provided by user service, but at that moment such an AP does not exist in the user service at all. To resolve the problem, the best way is the developers from two sides sit down at a table and *sign a contract* about the communication details between these two services. Firstly the auth service developer lists all required HTTP endpoints that should be provided by the user service. For example.
* When sending a `GET` request on the endpoints `/users/user1`, then return a response with the json content like this: `{'username':'uesr', roles:'USER'}`, etc.
* When the requesting endpoint is `/users/noneexisting`, then return a 404 error.
* ...
The user service developer reviews the requirements, and confirm the items one by one, and make sure they are on the same page.
Then they are back to work and focus on their own development. When the development(both side) is done, they can use a real world environment to verify if they have complied with the rules defined in the contracts they have signed.
In the software development world, this kind of scene is called *Consumer Driven Contracts*. In the CDC world, the auth service is called the API consumer, and the user service is the API producer/provider. In these years, CDC/Contracts testing becomes more and more popular.
Obviously, an advantage of applying this pattern is the consumer side can start work immediately when the contract is *signed* and do not need to wait for the complete work from the producer side.
There are a few projects available to improve the CDC development process.
* Spring Cloud includes a [Spring Cloud Contracts](https://spring.io/projects/spring-cloud-contract) subproject, which is heavily dependent on the Spring ecosystem.
* [Pact](https://pact.io/) is a general HTTP endpoints contracts verification solution, not limited to Spring ecosystem.
#### Spring Cloud Contracts
[Spring Cloud Contracts Workshop](https://spring-cloud-samples.github.io/spring-cloud-contract-samples/workshops.html) provides the best practice when introducing Spring Cloud Contracts into your Microservices project.
#### Pact
## Deploying Microservices application
In this section, we will explore how to deploy the services to the popular container platform, including Docker Swarm and Kubernetes.
### Publishing Docker Images to Docker Hub
Create an account on the official [Docker Hub](https://hub.docker.com/), after the account is created, you will get a special namespace for yourself.
In former steps, we have set the image name with a *hantsy/* prefix where the hantsy is the account name in the DockerHub.
After the Docker is installed, you can login to docker hub in the terminal.
```bash
docker login
// follow the guide to input user name and password to log in.
```
Then run the following command to publish your Docker images to the public Docker Hub.
```bash
docker push hantsy/post-service
docker push hantsy/user-service
docker push hantsy/auth-service
docker push hantsy/ngnix-proxy
```
When all are finished, go to [Docker Hub](https://hub.docker.com/), login and you will see the uploaded Docker images.
To verify the Docker Images is available via DockerHub, run the following commands to pull them from Docker Hub.
```bash
//remove the existing images.
docker rmi post-service
//pull the docker images
docker pull hantsy/post-service
```
If you do not want to expose your docker images to the public, choose a paid service or setup a private Docker registry server.
No panic the official docker registry is available as a Docker image, follow the official guide to [deploy a docker registry server](https://docs.docker.com/registry/deploying/).
Besides the official Docker Hub and private Docker registry, almost all cloud platforms provide private Docker registry service for the customers.
And Github and GitLab provides a Packages feature which includes hosting Docker images services, check the following docs:
* [Working with Github Packages Registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry)
* [GitLab Container Registry](https://docs.gitlab.com/ee/user/packages/container_registry/)
### Deploying to Docker Swarm
Use Docker Machine to create multiple nodes.
> These steps are tested on the legacy Docker Toolbox and use VritualBox as virtual machines. If you are using Docker Desktop for Windows, use Hyper-V instead.
In order to demonstrate running this project in Swarm mode, we will create two managers and three workers.
```
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn manager1
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn manager2
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn worker1
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn worker2
$ docker-machine create -d virtualbox --engine-registry-mirror https://docker.mirrors.ustc.edu.cn worker3
```
List all docker machines you just created.
```
$ docker-machine ls
NAME ACTIVE DRIVER STATE URL SWARM DOCKER ERRORS
manager1 - virtualbox Running tcp://192.168.99.101:2376 v17.05.0-ce
manager2 - virtualbox Running tcp://192.168.99.102:2376 v17.05.0-ce
worker1 - virtualbox Running tcp://192.168.99.103:2376 v17.05.0-ce
worker2 - virtualbox Running tcp://192.168.99.104:2376 v17.05.0-ce
worker3 - virtualbox Running tcp://192.168.99.105:2376 v17.05.0-ce
```
Switch to machine `manager1`.
```
eval "$(docker-manager env manager1)"
```
Try to initialize a Docker Swarm host.
```
$ docker swarm init --listen-addr 192.168.99.101 --advertise-addr 192.168.99.101
Swarm initialized: current node (t36lxk020fasw5tdes4gm9ucf) is now a manager.
To add a worker to this swarm, run the following command:
docker swarm join \
--token SWMTKN-1-10bwwj2u6erepp9oc0qlkwao4o79vogifon51qkhdqfsl7zkkd-810eddvkzt2g8vvxb4gul4pnb \
192.168.99.101:2377
To add a manager to this swarm, run 'docker swarm join-token manager' and follow the instructions.
```
We want to add *manager2* as manager in this swarm. Follow the above info. Execute `docker swarm join-token manager`, it will show the guide to add more managers.
```
$ docker swarm join-token manager
To add a manager to this swarm, run the following command:
docker swarm join \
--token SWMTKN-1-10bwwj2u6erepp9oc0qlkwao4o79vogifon51qkhdqfsl7zkkd-4xus5y6wa7a4ass0f5bt20pym \
192.168.99.101:2377
```
Let us switch to machine *manager2*.
```
eval "$(docker-machine env manager2)"
```
Copy and paste the `docker swarm join` command lines and execute it.
```
$ docker swarm join \
--token SWMTKN-1-10bwwj2u6erepp9oc0qlkwao4o79vogifon51qkhdqfsl7zkkd-4xus5y6wa7a4ass0f5bt20pym \
192.168.99.101:2377
This node joined a swarm as a manager.
```
Switch to worker1, worker2, and worker3, join this swarm as a worker.
```
docker swarm join \
--token SWMTKN-1-10bwwj2u6erepp9oc0qlkwao4o79vogifon51qkhdqfsl7zkkd-810eddvkzt2g8vvxb4gul4pnb \
192.168.99.101:2377
```
Switch to any **manager** machine, and you can show all running nodes.
```
$ docker node ls
ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
9d07by6czpem6hx55ke3ks1v1 manager2 Ready Active Reachable
er9klqvww0kdwyfaxr5f7n15l worker1 Ready Active
hsmaugexj4l7p5ighl9nega8q worker2 Ready Active
lknqw5dg5jyxw3j2camcpnb0v * manager1 Ready Active Leader
ovqfs7ymrgbeyfqu8db8n6apc worker3 Ready Active
```
Switch to any **manager** machine, deploy all service via `docker stack` command.
```
docker stack deploy -c docker-stack.yml blogapp
```
The services will be scheduled to deploy in this swarm.
The *docker-stack.yml* file includes a `visualizer` service to visualize all services. It can be accessed via *http://<any manager ip>:8080*, you will see the deployment progress.

```
#curl http://192.168.99.102/user -u user:test123
{"roles":["ROLE_USER"],"name":"user"}
```
Remove this stack by the following command.
```
docker stack rm blogapp
```
### Deploying to Kubernetes
| 1 |
auth0-samples/auth0-servlet-sample | Auth0 Integration Samples for Java Servlets and JSP | auth0 authentication dx-sdk-quickstart java quickstart webapp | # Auth0 Servlet Samples
[](https://circleci.com/gh/auth0-samples/auth0-servlet-sample)
This sample demonstrates how to add authentication to a Java web app using Auth0.
Check the [Java Quickstart](https://auth0.com/docs/quickstart/webapp/java-spring-mvc) to better understand of this sample.
## What is Auth0?
Auth0 helps you to:
* Add authentication with [multiple authentication sources](https://docs.auth0.com/identityproviders), either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others**, or enterprise identity systems like **Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider**.
* Add authentication through more traditional **[username/password databases](https://docs.auth0.com/mysql-connection-tutorial)**.
* Add support for **[linking different user accounts](https://docs.auth0.com/link-accounts)** with the same user.
* Support for generating signed [Json Web Tokens](https://docs.auth0.com/jwt) to call your APIs and **flow the user identity** securely.
* Analytics of how, when and where users are logging in.
* Pull data from other sources and add it to the user profile, through [JavaScript rules](https://docs.auth0.com/rules).
## Create a free account in Auth0
1. Go to [Auth0](https://auth0.com) and click Sign Up.
2. Use Google, GitHub or Microsoft Account to login.
## Issue Reporting
If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
## Author
[Auth0](https://auth0.com)
## License
This project is licensed under the MIT license. See the [LICENSE](LICENSE.txt) file for more info.
| 0 |
lenve/springcloud-video-samples | null | null | ## Spring Cloud 视频案例
扫码加微信(微信ID:**a_java_boy2**),备注 Java,进群讨论。

松哥自制的 Spring Cloud 视频案例。按需下载:
|编号|视频|案例|备注|
|:---|:---|:---|:---|
|01|第 02 章 第 3 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v2-3.zip)|Eureka 单节点搭建|
|02|第 02 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v2-4.zip)|Eureka 集群搭建|
|03|第 03 章 第 1 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-1.zip)|服务注册|
|04|第 03 章 第 2 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-2.zip)|服务消费|
|05|第 03 章 第 3 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-3.zip)|服务消费升级改造|
|06|第 03 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-4.zip)|RestTemplate GET 请求 Demo|
|07|第 03 章 第 5 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-5.zip)|RestTemplate POST 请求 Demo|
|08|第 03 章 第 6 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-6.zip)|RestTemplate PUT 请求 Demo|
|09|第 03 章 第 7 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v3-7.zip)|RestTemplate DELETE 请求 Demo|
|10|第 04 章 第 3 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v4-3.zip)|Consul 单节点注册|
|11|第 04 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v4-4.zip)|Consul 集群注册|
|12|第 04 章 第 5 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v4-5.zip)|Consul 消费|
|13|第 05 章 第 2 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-2.zip)|Hystrix 基本使用|
|14|第 05 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-4.zip)|Hystrix 请求命令|
|15|第 05 章 第 5 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-5.zip)|Hystrix 注解实现异步调用|
|16|第 05 章 第 6 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-6.zip)|Hystrix 容错[请求命令方式]|
|17|第 05 章 第 7 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-7.zip)|Hystrix 异常处理|
|18|第 05 章 第 8 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-8.zip)|Hystrix 请求缓存|
|19|第 05 章 第 9 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-9.zip)|Hystrix 请求合并|
|20|第 05 章 第 10 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v5-10.zip)|Hystrix 请求合并[注解方式]|
|21|第 06 章 第 2 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-2.zip)|初识OpenFeign|
|22|第 06 章 第 3 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-3.zip)|OpenFeign参数传递|
|23|第 06 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-4.zip)|OpenFeign继承特性|
|24|第 06 章 第 5 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-5.zip)|OpenFeign日志配置|
|25|第 06 章 第 6 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-6.zip)|OpenFeign数据压缩|
|26|第 06 章 第 7 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v6-7.zip)|OpenFeign服务降级|
|27|第 07 章 第 2 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v7-2.zip)|Resilience4j断路器|
|28|第 07 章 第 3 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v7-3.zip)|Resilience4j-RateLimiter|
|29|第 07 章 第 4 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v7-4.zip)|Resilience4j-Retry|
|30|第 07 章 第 5 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v7-5.zip)|微服务中的重试|
|31|第 07 章 第 6 小节|[点击下载视频案例](https://github.com/lenve/springcloud-video-samples/archive/v7-6.zip)|微服务中的断路器| | 0 |
jxtaliu/SpringBatchSample | Spring Batch Sample 4 book | null | SpringBatchSample
=================
Spring Batch Sample 4 book
本项目是图书《Spring Batch批处理框架》的配套源代码。
| 1 |
st-tu-dresden/guestbook | Guestbook sample Java web-application | null | null | 1 |
heowc/SpringBootSample | spring boot sample source | spring spring-batch spring-boot spring-data spring-security spring-statemachine | # Intro
* Spring Boot Sample Code
# subproject
- `spring-boot-aop`
- `spring-boot-async`
- `spring-boot-batch`
- `spring-boot-cache`
- `spring-boot-configurable`
- `spring-boot-cors`
- `spring-boot-custom-jackson`
- `spring-boot-docker`
- `spring-boot-dynamo`
- `spring-boot-event`
- `spring-boot-excel`
- `spring-boot-exception`
- `spring-boot-graceful-shutdown`
- `spring-boot-grpc`
- `spring-boot-hateoas`
- `spring-boot-interceptor`
- `spring-boot-jpa`
- `spring-boot-jpa-security`
- `spring-boot-logstash`
- `spring-boot-micrometer`
- `spring-boot-mybatis`
- `spring-boot-notice`
- `spring-boot-oauth2`
- `spring-boot-querydsl`
- `spring-boot-rabbitmq`
- `spring-boot-rest`
- `spring-boot-restdoc`
- `spring-boot-security-redis`
- `spring-boot-security-jwt`
- `spring-boot-springdoc-openapi` [](https://gitpod.io/#project=SpringBootSpringDocOpenApi,path=swagger-ui.html/https://github.com/heowc/SpringBootSample/tree/master/SpringBootSpringDocOpenApi)
- `spring-boot-swagger` [](https://gitpod.io/#project=SpringBootSwagger,path=swagger-ui%2Findex.html/https://github.com/heowc/SpringBootSample/tree/master/SpringBootSwagger)
- `spring-boot-test`
- `spring-boot-validator`
- `spring-boot-vertx`
- `spring-boot-war`
- `spring-boot-webflux`
- `spring-boot-websocket` [](https://gitpod.io/#project=SpringBootWebSocket/https://github.com/heowc/SpringBootSample/tree/master/SpringBootWebSocket)
| 1 |
michaelisvy/mvc-layout-samples | null | null | null | 0 |
fits/try_samples | samples | null | null | 0 |
k33ptoo/School-Management-System-JavaFX | A sample JavaFX management system GUI | javafx javafx-application javafx-desktop-apps javafx-gui javafx-project | # School Management System JavaFX
Previews




This project is purely **JavaFX** - it gives you a basis of what to do regarding your projects, **Note:** it is not a fully fledged system. Some of the things covered apart from UI design is
- Adding data to tableview
- Setting Application Icon
- Showing FXML as modals
### Libraries
This project uses a number of libraries:
* [FontAwesome](https://bintray.com/jerady/maven/FontAwesomeFX/9.1.2) - Icons
* [CalendarFX](https://github.com/dlemmermann/CalendarFX) - sophisticated calendar views based on JavaFX.
**You can also check out a [Java Swing](https://github.com/k33ptoo/School-Management-System-Inspiration) version if you are interested or Watch the full video [here](https://youtu.be/YuiXnPefmhU).
**
| 1 |
kousen/java_latest | Samples for Java features from Java 8 through 21 | java | # Java Latest
Samples for Java features from Java 8 through 21 (including preview features).
| 0 |
moe-java-samples/moe-java-samples | [DEPRECATED] Go to https://multi-os-engine.org/ | null | **Samples for open-sourced Multi-OS Engine were moved to https://github.com/multi-os-engine/moe-samples-java**
--------
[DEPRECATED] Intel Multi-OS Engine Samples
--------
Overview
--------
[Intel Multi-OS Engine](https://software.intel.com/en-us/multi-os-engine) provides a Java runtime and Java interfaces to iOS platform API to develop native iOS applications with native look and feel, native performance, and portability of common Java logic modules from your Android Apps. It comes fully integrated with Android* Studio hosted on Mac* OS or Windows* and contains all the development tools needed to develop an iOS* app and publish to the App store.
Getting Started
---------------
- Visit [Intel Multi-OS Engine](https://software.intel.com/en-us/multi-os-engine) page to download the Technology Preview version of the product
- Walk through our [Quick Start Tutorials](https://software.intel.com/en-us/blogs/2015/08/27/tutorials-and-quick-start-guides-for-multi-os-engine) to configure your development environment with Multi-OS Engine
- Read API Reference Manual at [multi-os-engine.github.io](http://multi-os-engine.github.io/doc)
- Questions? Sure, we got you covered through the [Multi-OS Engine Forum](https://discuss.multi-os-engine.org/)
- Applications created using Multi-OS Engine and posted to GitHub available here: [github.com/moe-applications](https://github.com/moe-applications)
System Requirements
-------------------
**Requirements for Apple* Mac OS X* hosts:**
- Operating System: Apple* Mac OS X* 10.9 or later
- Google* Android Studio* 1.2 or later
- Java* Development Kit (JDK) version 8
- Android Platform SDK
- Apple* Xcode* 6.x and 7.x
**Requirements for Windows* hosts:**
- Operating System: Microsoft* Windows* 7 x64 edition or later
- Google* Android Studio* 1.2 or later
- Java* Development Kit (JDK) version 8
- Android* Platform SDK
- Apple* iTunes*
- Apple* Mac OS X* host in LAN that has Multi-OS Engine installed and can be accessed using SSH
List of samples
-------------------------
The following samples are available for the Intel Multi-OS Engine:
- **Calculator** is a cross platform calculator. Demonstrates simple techniques: work with buttons, performing actions
- **CurrencyConverter** demonstrates how to open an URL and retrieve the content of that URL just using built-in Java* classes
- **DateCell** demonstrates formatted display of date objects in table cells and use of UIDatePicker to edit those values
- **FlipView** is an application that illustrates the following techniques: subclassing UIView, reacting to taps in views, open a URL to an external web site using Safari, flipping view content from front to back
- **InAppPurchase** sample demonstrates how to make purchases in your applications
- **KeyboardAccessory** shows how to use a keyboard accessory and how to use the keyboard-will-show and keyboard-will-hide notifications to animate resizing a view that is obscured by the keyboard
- **LazyTableLoader** demonstrates a multi-stage approach to loading and displaying a UITableView
- **LibGDXMissileCommand** shows how to implement libGDX game
- **MuseumMap** sample is based on SimpleMap sample. This application demonstrates work with SQL DB
- **NoteSqlite** shows how to make persistent storage with SQLlite library using generated bindings for iOS part
- **NoteTaking** shows how to make persistent storage with file system
- **NoteTaking_Android** is Android-only version of the NoteTaking sample
- **OpenGLBox** demonstrates 3D graphics programming using OpenGL
- **Planets** demonstrates working with UI Kit graphics
- **RssReader** demonstrates use of HTTP and HTTPS using Java* API
- **SimpleMap** is a simple application that demonstrates working with MapView
- **SimpleNetworkStreams** demonstrates work with sockets
- **Snake** is a port of android snake sample. Demonstrates simple game creation technique without sprites. Using UIImageView.
- **SQLite3Demo_java_sql** shows how to make persistent storage as SQLite database using java.sql package
- **SQLite3Demo_android_database_sqlite** shows how to make persistent storage as SQLite database using android.database.sqlite package
- **Taxi** is a template for taxi app that allows to select an address on Google Map
- **TheElements** demonstrates reading content from XML file. Works with UITableView, adding cells, using scrolling. Example of Master-Detail view, loading images from assets, reacting to taps in views, flipping view content from front to back
- **TicTacToe** demonstrates a simple game creation technique without sprites. Using buttons and performing actions.
- **WebBrowser** is a simple browser that uses WebView
- **WordSearch** sample demonstrating work with dictionary and substring search added
Legal Information
-----------------
The Samples are distributed under BSD 3 Clause license. The Samples incorporate, or dynamically links against, some third-party software. See NOTICE.txt in the root folder for details.
*Other names and brands may be claimed as the property of others.
Copyright 2015, Intel Corporation All Rights Reserved.
| 0 |
saki4510t/AudioVideoRecordingSample | Simultaneous audio and video recording sample using MediaCodec/MediaMuxer | null | AudioVideoRecordingSample
=========================
Simultaneous audio and video recording sample using MediaCodec/MediaMuxer
Copyright (c) 2014-2016 saki t_saki@serenegiant.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.
All files in the folder are under this Apache License, Version 2.0.
=========
| 1 |
weavey/NormalSelectDialog | Some sample of dialog. | null |
已停止维护,慎用!!!!!!!!!
[Version 1.3详情](https://weavey.github.io/2016/09/07/%E7%9B%B4%E6%8E%A5%E6%8B%BF%E5%8E%BB%E7%94%A8%E4%B9%8BDialog/)
Version 1.3引用
> compile 'com.lai.weavey:dialog:1.3'
[Version 2.0详情](https://weavey.github.io/2016/12/28/%E7%9B%B4%E6%8E%A5%E6%8B%BF%E5%8E%BB%E7%94%A8%E4%B9%8BDialog2/)
Version 2.0引用
> compile 'com.lai.weavey:dialog:2.0.1'
| 1 |
eclipse-ee4j/glassfish-samples | null | null | # GlassFish Samples
This repository contains the source files for the
[GlassFish Samples](https://github.com/eclipse-ee4j/glassfish-samples) that are delivered with the
Java EE SDK.
This software is provided to you under the terms described in
this [License](LICENSE). By using this software, you agree to accept
the terms, as described by this license.
If you encounter any issues, or wish to report bugs, please log into
GitHub and file an [Issue](https://github.com/eclipse-ee4j/glassfish-samples/issues).
# Building the Java EE 8 Samples
## Prerequisites
- Maven
- JDK8+
- GlassFish 5
## Build the Examples
To build the Java EE 8 GlassFish Samples:
* Clone this repository.
* From the `ws/javaee8` directory, run
```
mvn install
```
Each application module builds and the resulting WAR is written to each respective `target` subdirectory.
See the [README](ws/javaee8/README.md) file in the `/javaee8` directory for details on adding additional modules.
| 0 |
Even201314/MRichEditor | A rich text editor sample (based on summernote) | richeditor wysiwyg | MRichEditor
======
A rich text editor sample (based on [summernote](https://github.com/summernote/summernote))
## Features
- Bold
- Italic
- Underline
- Strike-through
- Heading 1
- Heading 2
- Heading 3
- Heading 4
- Heading 5
- Heading 6
- Paragraph
- Quote
- Ordered List
- Unordered List
- Code
- Horizontal Rule
- Link
- Image
- Justify Center
- Justify Full
- Justify Left
- Justify Right
- Subscript
- Superscript
- Font Name
- Font Size
- Indent
- Outdent
- Undo
- Redo
#### Screenshot
<img src="gif/Screenshot_1.gif" width=300/>
<img src="gif/Screenshot_2.gif" width=300/>
<img src="gif/Screenshot_3.png" width=300/>
## License
```
The MIT License (MIT)
Copyright © 2017 Even201314,
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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 OR COPYRIGHT HOLDERS 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.
```
| 1 |
AxonIQ/code-samples | Multi-module project containing several Axon-based samples | cqrs domain-driven-design event-sourcing message-driven microservices moduliths | # Code Samples
This repository contains several Axon-based sample projects to explain specific topics.
Axon usage extends itself from the repositories under the [Axon Framework project](https://github.com/AxonFramework/),
as well as the tools provided by AxonIQ like [Axon Server](https://www.axoniq.io/products/axon-server).
Each Maven module within this project represents a different sample you can use, each with its own `README.md`
explaining the intent and usage.
Some of these modules can actually be run, while others are a plain set-up.
The latter typically are samples that don't require to be ran for additional or much needed explanation.
If a module can be run, you may expect a `docker-compose.yml` to set up the infrastructure in most cases, as well as a "
Spring Boot"-based main class.
Down below is an exhaustive list of all the sample:
1. [Axon-Spring Template](axon-spring-template/README.md) - Sample project providing the scaffolding for a simple Axon-
and Spring-based application.
2. [Distributed Exceptions](distributed-exceptions/README.md) - Sample showing how to deal with exceptions in a
distributed application.
3. [Multitenancy](multitenancy/README.md) - Sample showing 'a' approach to multitenancy.
4. [Reset Handler](reset-handler/README.md) - Sample showing how to reset a `StreamingEventProcessor`.
5. [Saga - No TOAST in PostgreSQL](saga/README.md) - Sample showing a basis Saga, that's stored in a PostgreSQL
without [TOAST](https://wiki.postgresql.org/wiki/TOAST).
6. [Sequencing Policy](sequencing-policy/README.md) - Sample showing how to set up a custom `SequencingPolicy` to adjust
the event sequence for a `StreamingEventProcessor`.
7. [Set-Based Validation](set-based-validation/README.md) - Sample showing several approaches to implement set-based
validation.
8. [Set-Based Validation - Actor Model](set-based-validation-actor-model/README.md) - Sample showing how to implement
set-based validation through a dedicated aggregate instance.
9. [Snapshots](snapshots/README.md) - Sample showing how to configure aggregate snapshotting.
10. [Stateful Event Handler](stateful-event-handler/README.md) - Sample showing a stateful event handler that can be
used as a replacement for sagas.
11. [Subscription Query - REST](subscription-query-rest/README.md) - Sample showing how to use Axon's subscription query
cleanly in a REST-based controller.
12. [Subscription Query - Streaming](subscription-query-streaming/README.md) - Sample showing how to use Axon's
subscription query cleanly in a streaming-based controller.
13. [Upcasters](upcaster/README.md) - Sample showing several implementations of upcasters.
| 0 |
piomin/sample-spring-microservices | Many samples in different branches that shows how to create microservices with Spring Boot, Spring Cloud, Zipkin, Zuul, Eureka, Hystrix, Kubernetes, Elastic Stack and many more tools | elastic-stack eureka hystrix kibana kubernetes logstash microservices ribbon spring-boot spring-boot-admin spring-cloud spring-cloud-netflix spring-cloud-sleuth zipkin zuul | null | 0 |
dougqh/jvm-mechanics | Presentation & Code Samples Showing Compilation & Deoptimization Behavior of HotSpot | null | null | 0 |
iuliana/book-code | Spring various code samples. | null | null | 0 |
dunithd/edu-samples | This repository contains the source code for samples featured in eventdrivenutopia.com | null | # Code Samples for Articles Featured at eventdrivenutopia.com
This repository contains the source code for samples featured in eventdrivenutopia.com
| 0 |
micrometer-metrics/micrometer-samples | Sample apps to demo Micrometer features | null | # Micrometer Samples
[](https://circleci.com/gh/micrometer-metrics/micrometer-samples)
[](https://www.apache.org/licenses/LICENSE-2.0)
[](https://search.maven.org/artifact/io.micrometer/micrometer-core)
[](https://www.javadoc.io/doc/io.micrometer/micrometer-core)
[](https://ge.micrometer.io/)
Sample apps to demo [Micrometer](https://github.com/micrometer-metrics/micrometer) features.
## Building
To build the project with Brave tracer just run
```bash
$ ./gradlew build
```
To build the project with OpenTelemetry tracer just run
```bash
$ ./gradlew build -Potel
```
## Running
You can run each of the samples individually.
## Join the discussion
Join the [Micrometer Slack](https://slack.micrometer.io) to share your questions, concerns, and feature requests.
## Documentation
The reference documentation is managed in [a separate GitHub repository](https://github.com/micrometer-metrics/micrometer-docs) and published to https://micrometer.io/.
## Contributing
See our [Contributing Guide](CONTRIBUTING.md) for information about contributing to Micrometer.
-------------------------------------
_Licensed under [Apache Software License 2.0](https://www.apache.org/licenses/LICENSE-2.0)_
_Sponsored by [VMware](https://tanzu.vmware.com)_
| 1 |
Coder-EdisonZhou/EDT.SpringBoot.Samples | 基于程序猿DD的SpringBoot教程所做的学习实践,基于SprintBoot 1.5.15版本,每个项目均演示了部分内容:如SpringSecurity、Spring-Data-JPA、多数据源处理、Redis与MongoDB的集成等等等等。由于程序猿DD的文章示例版本太旧,部分Code无法正常运行,所以在学习途中(非SpringBoot2.0版本的学习)可以参考本示例Demo来学习。 | null | # EDC.SpringBoot.Learning
## SpringBoot
[](https://start.spring.io/)
基于程序猿DD的SpringBoot教程所做的学习实践,基于SprintBoot 1.5.15版本,每个项目均演示了部分内容。由于程序猿DD的文章示例版本太旧,部分Code无法正常运行,所以在学习途中(非SpringBoot2.0版本的学习)可以参考本示例Demo来学习。
- msadv1 :
Hello World & 配置文件的使用(多环境配置文件的使用) & MVC Controller & 热部署
- msadv2 :
分层的CRUD RESTful API示例 & 单元测试(针对Controller和Service及Mock的使用)
- msadv3 :
静态资源的导入 & Thymeleaf模板的使用 & Swagger API Doc & 统一异常处理
- msadv4 :
Spring Security基本使用 & JdbcTemplate访问数据库 & Spring-data-jpa访问数据库
- msadv5 :
多数据源配置(基于JdbcTemplate 与 基于Spring-data-jpa)
- msadv6 :
Redis & MongoDB 集成与基本使用
- msadv7 :
整合 MyBatis & MyBatis 注解配置的使用
- msadv8 :
Spring Boot中的事务管理 & 使用Flyway管理数据库版本
- msadv9 :
Spring Boot中的缓存注解 & 使用Ehcache作为缓存
- msadv10 :
集成使用Redis作为缓存
- msadv11 :
使用log4j记录日志 & 多环境不同日志级别的控制 & 使用AOP统一处理Web请求日志
- msadv12 :
使用log4j实现http请求日志存入MongoDB & 动态修改日志级别(1.5.x新特性)
- msadv13 :
RabbitMQ的基本集成和使用
- msadv14 :
使用@Scheduled创建定时任务 & 使用@Async实现异步调用
- msadv15 :
使用@Async实现异步调用:自定义线程池
- msadv16 :
使用@Async实现异步调用:ThreadPoolTaskScheduler线程池的优雅关闭
- msadv17 :
使用@Async实现异步调用:使用Future & 定义超时
- msadv18 :
实现邮件发送:简单邮件、带附件的邮件、带资源的文件以及基于模板的邮件 & 使用spring boot actuator监控端点
- msadv19 :
自定义启动Banner & 使用Spring StateMachine框架实现状态机 & 使用exclude排除不必要的自动化配置的加载
## 推荐学习资料
> 程序猿DD [SpringBoot基础教程](http://blog.didispace.com/Spring-Boot%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/)<br/>
> 纯洁的微笑 [SpringBoot基础教程](http://www.ityouknow.com/spring-boot.html)<br/>
> EdisonChou [Spring Boot on Docker](https://www.cnblogs.com/edisonchou/p/springboot_on_docker_foundation.html)
## 推荐开发环境
[](https://www.jetbrains.com/idea/)
> Intellij Idea Community 2018版本<br/>
`PS`: 如果是.Net程序猿想要学习SpringBoot,建议更改快捷键与Visual Studio保持一致,这样能加快开发效率
| 0 |
dandelion/dandelion-datatables-samples | Sample applications to demonstrate Dandelion-Datatables features | null | # dandelion-datatables-samples
Sample applications to demonstrate Dandelion-Datatables features
| 1 |
tmatyashovsky/spark-ml-samples | null | null | # Sample Application for "Introduction to ML with Apache Spark MLlib" Presentation
## Presentation
Link to the presentation: http://www.slideshare.net/tmatyashovsky/introduction-to-ml-with-apache-spark-mllib
## Idea
Create few examples to demonstrate regression, classification and clustering to Java developers.
Main focus is on feature extraction and creation of interesting ML pipelines.
### DOU Dataset
DOU (http://dou.ua) stands for developers.org.ua is a main hub for Ukrainian developers.
It provides anonymous survey for getting information about Ukrainian engineers, their salary, experience, English level, etc.
#### DOU Dataset Regression
Given poll results predict salary based on experience, English level and programming language.
Nuances:
* English level is string, should be converted to numeric, e.g. 0…5
* Languages are strings, should be exploded to 18 booleans, e.g. java=0|1, python=0|1, etc.
* Sparse vector [21, [0, 1, 13], [3, 4, 1]] is more preferable
#### DOU Dataset Clustering
Given poll results predict level (junior, middle, senior) based on experience and English level.
Nuances:
* English level is string, should be converted to numeric, e.g. 0…5
* 1$ difference in salary is not as significant as 1 year of experience, so data should be scaled before clustering
* Dense vector is ok
### Pop vs. Heavy Metal
Given verse from verse1 recognize genre.
Strategy:
* Collect raw data set of verse1 (~65k sentences in total):
* Abba, Ace of base, Backstreet Boys, Britney Spears, Christina Aguilera, Madonna, etc.
* Black Sabbath, In Flames, Iron Maiden, Metallica, Moonspell, Nightwish, Sentenced, etc.
* Create training set, i.e. label (0|1) + features
* Train logistic regression
### MNIST Dataset
Given set of images recognize digits.
Nuances:
* Tranform images into training examples
## Build, Configure and Run
### Build
Standard build:
```
./gradlew clean build shadowJar
```
Quick build without tests:
```
./gradlew clean build shadowJar -x test
```
### Configuration
All available configuration properties are spread out via 3 files:
* application.properties - contains business logic specific stuff
* spark.properties - contains Spark specific stuff
All properties are self explanatory, but few the most important ones are listed explicitly below.
#### Application Properties
| Name | Type | Default value | Description |
| ---- | ---- | ------------- | ----------- |
| server.port | Integer | 9090 | The port to listen for incoming HTTP requests |
#### Spark Properties
| Name | Type | Default value | Description |
| ---- | ---- | ------------- | ----------- |
| spark.master | String | spark://127.0.0.1:7077 | The URL of the Spark master. For development purposes, you can use `local[n]` that will run Spark on n threads on the local machine without connecting to a cluster. For example, `local[2]`. |
|spark.distributed-libraries | String | | Path to distributed library that should be loaded into each worker of a Spark cluster. |
#### Sample configuration for a local development environment
Create *application.properties* (for instance, in your user home directory) and override any of the described properties.
For instance, minimum set of values that should be specified for your local environment is listed below:
```
spark.distributed-libraries=<path_to_your_repo>/spark-distributed-library/build/libs/spark-distributed-library-1.0-SNAPSHOT-all.jar
dou.training.set.csv.file.path=<path_to_your_repo>/training-set/dou/2016_may_mini.csv
dou.regression.model.directory.path=<path_to_your_repo>/training-set/dou/regression-model
dou.clustering.model.directory.path=<path_to_your_repo>/training-set/dou/clustering-model
verse1.training.set.directory.path=<path_to_your_repo>/training-set/verse1/
verse1.model.directory.path=<path_to_your_repo>/training-set/verse1/model
mnist.training.set.image.file.path=<path_to_your_repo>/training-set/mnist/train-images-idx3-ubyte
mnist.training.set.label.file.path=<path_to_your_repo>/training-set/mnist/train-labels-idx1-ubyte
mnist.test.set.image.file.path=<path_to_your_repo>/training-set/mnist/t10k-images-idx3-ubyte
mnist.test.set.label.file.path=<path_to_your_repo>/training-set/mnist/t10k-labels-idx1-ubyte
mnist.training.set.parquet.file.path=<path_to_your_repo>/training-set/mnist/training-set.parquet
mnist.test.set.parquet.file.path=<path_to_your_repo>/training-set/mnist/test-set.parquet
mnist.model.directory.path=<path_to_your_repo>/training-set/mnist/model
mnist.validation.set.directory.path=<path_to_your_repo>/training-set/mnist/validation-set
```
### Run
From your favourite IDE plese run `ApplicationConfiguration` main method.
This will use default configuration bundled in the source code.
In order to run the application with custom configuration please add spring.config.location parameter that corresponds to directory that contains your custom *application.properties* (in our example your user home directory). Or just enumerate them explicitly, for instance:
```
spring.config.location=/Users/<your user>/application.properties
```
| 0 |
making/spring-boot-db-samples | Spring Boot + Data access libraries | null | ## Spring Boot Data Accesss Examples
### Implemented technologies
* [Spring JDBC](demo-spring-jdbc)
* [Spring Data JPA](demo-spring-data-jpa)
* [jOOQ](demo-jooq)
* [MyBatis](demo-mybatis)
* [Doma2](demo-doma2)
* [Querydsl](demo-querydsl)
* [JDBI](demo-jdbi)
* [Sql2o](demo-sql2o)
* [Iciql](demo-iciql)
* Exposed
* [S2JDBC](demo-s2jdbc)
* [DBFlute](demo-dbflute)
* [Ebean](demo-ebean)
Pull Requests Welcome :)
### Points to implement
* many to one
* many to many
* batch insert
* generate key
| 0 |
oldrev/axelor-cookbook-samples | Axelor 二次开发入门视频教程代码范例 | null | # axelor-cookbook-samples
Axelor 教程代码范例仓库,本仓库保存“命叔杂技”视频专栏《Axelor 开发系列教程》的实例代码。
本项目的 `build.gradle` 中引用了作者提供的 Axelor 开发平台汉化版:
https://github.com/axelor-l10n-cn
请确保网络可以访问 GitHub 的内容,自己的项目可参考如何使用汉化版。
任何问题可进 QQ 群 1048161339 讨论。
# 视频教程在线观看:
* Youtube: https://www.youtube.com/watch?v=wegQWkt3vDg&list=PLlQK_EEIm_sWj-BvmcOcj8klPX2M96aF9
* Bilibili: https://space.bilibili.com/26188820/channel/detail?cid=103191
* 西瓜视频: https://www.ixigua.com/pseries/6791677568144638477
# 编译环境需求
* Java JDK8(必须 Java8)
* Gradle 5.6+(必须,但必须 <= 6.3,6.4 无法运行)
* Intellij IDEA(可选)
# 命令行编译运行
进入各个例子的目录,执行:
## Windows
```cmd
.\gradlew.bat run
```
## Linux & MacOSX
```bash
./gradlew run
```
启动完成以后命令行日志会提示服务器 URL,用浏览器打开即可,默认用户名、密码:`admin`和`admin`。
# FAQ
* **Q:编译时出现错误,`generateCode` 任务生成的代码报“注释未结束”的错误。** A:升级机器上的 Gradle 到 6.0 或更高版本可解决。
| 0 |
mudigal-technologies/microservices-sample | Sample project to create an application using microservices architecture | angular9 api-gateway consul docker docker-compose dockerfile elasticsearch h2 java kibana logback logstash microservices-architecture mysql rabbitmq spring-boot springboot-webflux springboot-webflux-mongodb springboot2 zuul | # Microservices Sample
[](https://travis-ci.org/mudigal-technologies/microservices-sample)
[](https://quay.io/repository/microservices-sample/api-gateway)
[](https://quay.io/repository/microservices-sample/service-one)
[](https://quay.io/repository/microservices-sample/service-two)
[](https://quay.io/repository/microservices-sample/web-application)
# Microservices Sample
### What is it?
"Microservices", a trending buzz word nowadays. What problems does it solve?
Many organizations nowadays are driving the technology migrations and one of the biggest challenges is to migrate from monolithic application to micro-services based application.
This microservices-sample project demonstrates how multiple services run independently leveraging on the best microservices patterns to enable scale, performance and resilience.
<p align="center">
<a href="https://www.youtube.com/watch?v=AYcsnuIOW2M" target="_blank" rel="noopener noreferrer"><img src="https://img.youtube.com/vi/AYcsnuIOW2M/0.jpg" alt="https://www.youtube.com/watch?v=AYcsnuIOW2M"/></a>
</p>
### Use case
The sample application has two services namely service-one and service-two. Each of the service has its own database service-one-db and service-two-db respectively. During the startup of the services, it persists the service name and an auto generated UUID in its perspective database and sends the data to the RabbitMQ exchange which then broadcasts the data to all the queues based on the routing key. Every microservices listens to its own RabbitMQ queue and keeps updating the database as and when it receives the data.
Below are the screens of the application.

Clicking on the tab's one or two the data that you see on the screen is based on the data fetched by the respective service by calling its database.

Notice that the UUID generated for service-one which lies in service-one-db is in sync with service-two tab which is achieved by RabbitMQ (asychronous communication between microservices).

### Service Registration
During the initialization of a service, it would get registered to the discovery and registration server (which in our example is Hashicorp's Consul).
.png?raw=true)
#### Service Discovery
When one service (say api-gateway) needs to access a resource from another service (say service-one), all it has to do is ask discovery and registration server (Consul) to give one of the service-one's instance information.
.png?raw=true)
### Architecture
Below is the architectural diagram for microservices sample project.

### Components Integrated & Tools Usage
##### API Gateway
Netflix Zuul is a the reverse proxy server which acts as the API Gateway for accessing the micro services behind the gateway which routes the request to the respective service. Microservice’s stay behind reverse proxy server and needs to be consumed via api gateway. The api-gateway micro service with docker profile runs on port 8080 and can be accessed by http://localhost:8080 .
Configuration done in API Gateway for Routing:
```
zuul:
ignoredServices: '*'
routes:
one:
path: /service-one/**
serviceId: Service-One
two:
path: /service-two/**
serviceId: Service-Two
```
##### Service registration and discovery
Registration and discovery is taken care by the HashiCorp’s Consul. During the startup of the individual services, they register with service registration service those details such as host name, port etc. by which the services can be accessed. Once the service is registered to the consul, consul checks for the health of the service by sending a heartbeat for the health check path and health check interval that has been registered with Consul. Requests to the micro-services has to be routed through api-gateway during with the api-gateway contacts discovery service to get the information required to send the request to the intended microservice.
Configuration done in micro services to register to Consul:
```
management:
contextPath: /actuator
spring:
application.name: service-one
cloud:
consul:
host: consul
port: 8500
discovery:
hostName: service-one
instanceId:${spring.application.name}:${spring.application.instance_id:${random.value}}
healthCheckPath: ${management.contextPath}/health
healthCheckInterval: 15s
```
Consul management console can be accessed at http://localhost:8500/ui/

##### Monitoring and vizualization
Monitoring, visualisation & management of the container in docker is done by weave scope.
Weavescope management console can be accessed at http://localhost:4040/

##### Centralized logging using ELK
Logback integrated with every microservices creates application logs and send the log data to the logging server (Logstash). Logstash formats the data and send it to the indexing server (Elasticsearch). The data stored in elasticsearch server can be beautifully visualized using Kibana.
Accessing tools:
Elasticsearch: http://localhost:9200/_search?pretty
Kibana: http://localhost:5601/app/kibana









##### Asynchronous microservices communication
Intercommunication between microservices happens asynchronously with the help of RabbitMQ.
RabbitMQ console can be accessed at http://localhost:15672/



### Technology
Microservices sample project uses a number of open source projects to work properly:
* [SpringBoot] - Application framework
* [Zuul] - API Gateway (Load Balancer)
* [Consul] - Service registration and Discovery
* [Docker] - Containerization platform
* [RabbitMQ] - asynchronous microservices messaging.
* [Logstash] - Log collector
* [Elasticsearch] - Log indexer
* [Kibana] - Data visualization
* [Angular] - HTML enhanced for web apps!
* [Bootstrap] - great UI boilerplate for modern web apps
* [jQuery] - HTML document traversal and manipulation
* [Swagger] - API documentation
### Tools
* [Java] - Programming
* [Maven] - Build
* [Git] - Version control
* [Docker] - Deployment
### Development
Below are the steps to bring up the development environment and get started.
1) Install Git, Java, Maven and Docker</br>
2) For the project using https://github.com/mudigal-technologies/microservices-sample.git
3) Clone the fork using https://github.com/{YOUR_GIT_ID}/microservices-sample.git</br>
4) Execute "cd /microservices-sample/build/docker/scripts/"</br>
5) To deploy docker please run "./deploy.sh docker".</br>
6) Access the Application at http://localhost/</br></br>
### Extras
Mysql on service-two-db:
```
$ docker exec -it service-two-db mysql -u service-two -p
Enter password: service-two
mysql> USE service-two;
Database changed
mysql> SELECT * FROM name_value;
```
### Help
Feel free to reach "[MUDIGAL TECHNOLOGIES LLP]" at "contact@mudigal.com" incase of any concerns.
[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job.)
[MUDIGAL TECHNOLOGIES LLP]: <https://www.mudigal.com>
[Bootstrap]: <https://twitter.github.com/bootstrap/>
[jQuery]: <https://jquery.com>
[Angular]: <https://angular.io/>
[SpringBoot]: <https://projects.spring.io/spring-boot/>
[Consul]: <https://www.consul.io>
[Docker]: <https://www.docker.com>
[Zuul]: <https://github.com/Netflix/zuul/wiki>
[Kitematic]: <https://kitematic.com>
[Maven]: <https://maven.apache.org>
[MySQL]: <https://www.mysql.com>
[Git]: <https://git-scm.com>
[Java]: <https://go.java>
[Logstash]: <https://www.elastic.co/products/logstash>
[Elasticsearch]: <https://www.elastic.co/products/elasticsearch>
[Kibana]: <https://www.elastic.co/products/kibana>
[RabbitMQ]: <https://www.rabbitmq.com/>
[Swagger]: <https://swagger.io/>
| 1 |
yixia/VitamioDemo | DEPRECATED - Please use the [VitamioBundle/sample] | null | VitamioDemo
===========
Demo of Vitamio for Android, it's reference the [VitamioBundle][1] .
DEPRECATED
==========
Please use the VitamioBundle [sample][2]
License
=======
Copyright 2013 yixia.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://github.com/yixia/VitamioBundle
[2]: https://github.com/yixia/VitamioBundle/tree/master/vitamio-sample
| 0 |
totvs/tjf-samples | TOTVS Java Framework Samples | cloud java microservices spring tjf tjf-samples totvs-java-framework | # TOTVS Java Framework
## Samples
Repositório contendo todos os _samples_ de uso das bibliotecas do __TOTVS Java Framework ([TJF])__.
> __Importante__
> No momento, apenas colaboradores da TOTVS tem acesso ao repositório Maven do TJF,
de onde podem ser baixados os artefatos que são referenciados nos _samples_.
[TJF]: https://tjf.totvs.com.br
| 0 |
googlemaps/last-mile-fleet-solution-samples | null | null | # Last Mile Fleet Solution Sample Apps
## Introduction
The LMFS Sample Apps provide reference implementations of the various
integrations and applications that use the
[LMFS APIs](https://developers.google.com/maps/documentation/transportation-logistics/last-mile-fleet-solution).
You can use these samples to quickly bootstrap a solution to create, update, and
simulate vehicles, journeys and tasks. These apps work for both mobile and web.
To get started, use the [getting started guide](getting-started.md).
## Components
There are three main pieces to the sample applications:
1. The backend, a Java-based server using the Fleet Engine API, which supports
services for the mobile applications as well as web-facing applications.
The backend is contained in the `backend/` directory.
1. Mobile driver apps:
- The Android Driver app, an Android client for delivery drivers written
in Java using the Driver, Navigation, and Maps SDKs, which can be run on
Android devices or simulators.
The Android Driver app is contained in the `android_driverapp_samples`
directory.
- The iOS Driver app, an iOS client for delivery drivers written in Swift
using the Driver, Navigation, and Maps SDKs, which can be compiled and
run on iOS devices or simulators.
The iOS Driver app is contained in the `ios_driverapp_samples`
directory.
1. Web apps:
- The Shipment Tracking web app for users to track the progress of their
shipments.
- The Fleet Tracking web app used by operators to track delivery vehicles.
The sample web apps are located in the `backend/src/main/webapp/html`
directory, but can be hosted on any web server that can serve static HTML,
CSS and JavaScript assets. These apps use the JavaScript Shipment Tracking
and Fleet Tracking libraries.
In addition, some tools are shipped to help with the deployment and
instantiation of a sample apps instance:
- `update_configuration.sh`: this script is used during deployment to set up
credentials for the whole project.
- `generator`: this is a utility that creates scenario files that can be used
to simulate delivery scenarios. For more information, consult the utility's
[README](tools/generator/README.md).
## System architecture

### Backend
For a detailed listing of the web pages and endpoints, refer to
[the backend README file](backend/README.md).
#### Authentication and token generation
The authentication component communicates with the Cloud Project for a LMFS
deployment, generates JSON Web Tokens (JWTs) of various kinds, and passes the
tokens onto the other apps to facilitate their communication with Fleet Engine.
This component makes use of the
[Fleet Engine Auth Library for Java](https://github.com/googlemaps/java-fleetengine-auth),
and requires that the the development host has been set up for Google Cloud
authentication, and that the Google Cloud project used for Fleet Engine access
has created service accounts used to sign these tokens.
For detailed setup procedure, refer to the
[getting started guide](getting-started.md).
#### Scenario ingestion
The scenario ingestion component allows the user to upload a delivery
configuration file, which contains definitions for delivery vehicles, stops, and
tasks to be performed at each stop. A task can be a pick-up or delivery of a
package. Upon receiving such a file, the component calls Fleet Engine to create
these vehicles, stops, and tasks.
#### Delivery vehicle assignment
When a mobile driver app requests a vehicle assignment, the backend associates
one of the defined (and available) delivery vehicles to the requester, and sends
the information to the app. The app uses the information to set up its internal
representations of these entities, and allows for simulation of a delivery
vehicle as it travels through its assigned stops and performs its assigned
tasks.
#### Vehicle and task updates
The backend exposes endpoints that allow the mobile driver app to request
vehicle and task updates. These updates allow the mobile driver app to indicate,
for example, that a task has been completed, that the vehicle is en route to its
next stop, or that the driver has requested the stops to be re-sequenced.
#### Web pages and app serving
The backend serves the static resources for the shipment tracking and fleet
tracking web apps: HTML, CSS and JavaScript. In addition, the backend has
endpoints through which the web apps can obtain information about the tasks and
vehicles that they are tracking.
### Mobile driver app
The mobile driver app communicates with the backend, obtains a manifest of stop
and task definitions, and shows the data in a user interface that allows the
driver to perform the following actions:
- Check the tasks to be performed at each stop.
- Manually resequence the stops to change the order in which they are to be
visited, if needed.
- Initiate navigation to the first stop on the list.
- Automatically send location updates to Fleet Engine.
- Mark tasks as complete.
For details on the setup and usage of the mobile app, refer to the
[Android](android_driverapp_samples/README.md) and
[iOS](ios_driverapp_samples/README.md) mobile driver app README files.
### Web apps
The web apps communicate with the backend and Fleet Engine to retrieve status
updates for a task or delivery vehicle. The apps then visualize the movement of
the tracked entity in an automatically updated map and present data such as ETA
in a tabular format. The web apps are designed for end users (such as package
recipients) and delivery company dispatch operators.
The web apps integrate with the JavaScript Shipment Tracking and Fleet Tracking
SDKs.
For details on the usage of the web apps, refer to the [web apps](web-apps.md)
document.
## Delivery configuration file
The delivery configuration file specifies the list of vehicles, their manifests
(consisting of a list of stops and tasks), and the order in which the stops are
to be traversed. The
[file format](backend/README.md#delivery-configuration-file) is designed to be
human-readable and easy to adapt to existing scheduling formats.
### Command-line utility for generating a delivery configuration
This utility, written in Python, generates a delivery configuration file with
stops and tasks scattered in a region. For details on the utility, refer to
[the generator's README file](tools/generator/README.md).
## License
```
Copyright 2022 Google LLC.
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.
```
| 0 |
neoremind/coddding | My sample code repository | null | # Sample code

This repository is mainly used as a training court.
Do something today that your future self will thank you for!
| 1 |
citerus/dddsample-core | This is the new home of the original DDD Sample app (previously hosted at sf.net).. | null | # DDDSample
[](https://github.com/citerus/dddsample-core/actions/workflows/pipeline.yml)
This is the new home of the original DDD Sample app hosted at SourceForge.
Our intention is to move everything from SourceForge to GitHub in due time while starting upgrading both the technical aspects as well as the DDD aspects of the DDD Sample.
This project is a joint effort by Eric Evans' company [Domain Language](https://www.domainlanguage.com/) and the [Swedish software consulting company Citerus](https://www.citerus.se/).
The application uses Spring Boot. To start it go to the root directory and type `mvn spring-boot:run` or run the `main` method of the `Application` class from your IDE.
Then open http://localhost:8080/dddsample in your browser (and make sure that no firewall is blocking the communication and that Javascript for localhost is not blocked).
Discussion group: https://groups.google.com/forum/#!forum/dddsample
Development blog: https://citerus.github.io/dddsample-core/
Trello board: https://trello.com/b/PTDFRyxd
## How to build
Using Maven (we recommend using the included Maven wrapper), run this command to compile and run all the tests:
./mvnw verify
If you want to compile without running the tests, run the following command:
./mvnw compile
For Windows users, use the included `mvnw.cmd` file instead, without the `./` but using the same arguments.
## How to run
To start the app using the included application server and in-process HSQL database, run this command:
./mvnw spring-boot:run
For Windows users, use the included `mvnw.cmd` file instead, without the `./` but using the same arguments.
## Entity relationships

The diagram was created with diagrams.net (formerly draw.io).
## Using the HandlingReport REST API
The HandlingReport API has one endpoint that takes a JSON request body:
POST /dddsample/handlingReport
You can use cURL to send the request using an JSON file for the body:
curl --data-binary "@/path/to/project/src/test/resources/sampleHandlingReport.json" \
-H 'Content-Type: application/json;charset=UTF-8' \
http://localhost:8080/dddsample/handlingReport
See the [api-docs.yaml](/api-docs.yaml) file for a complete API definition.
| 1 |
eyal-lupu/eyallupu-blog | Code samples from my blog | null | [](https://travis-ci.org/eyal-lupu/eyallupu-blog)
# eyallupu-blog
Code samples from my blog
| 0 |
ThomasVitale/cloud-native-spring-in-action | 🍃 Code samples and projects from the book Cloud Native Spring in Action - With Spring Boot and Kubernetes" (Manning) " | buildpacks cloud-native devops docker gradle java jvm kubernetes kubernetes-native microservices spring spring-boot spring-cloud | # 🍃 Cloud Native Spring in Action
<a href="https://www.manning.com/books/cloud-native-spring-in-action"><img src="/book-cover.jpg" alt="The book cover of 'Cloud Native Spring in Action' by Thomas Vitale" align="left" height="200px" /></a>
This repository contains the source code accompanying the book [Cloud Native Spring in Action - With Spring Boot and Kubernetes](https://www.manning.com/books/cloud-native-spring-in-action) written by [Thomas Vitale](https://www.thomasvitale.com/) and published by Manning Publications.
There is a folder for each chapter, for which both an _initial_ and _final_ versions are available. For example, for chapter 4, you can use `Chapter04/04-begin` as a starting point to follow along with the examples in the chapter and `Chapter04/04-end` to check the code as it looks like at the end.
The book uses Spring Boot 2.7.x and this main branch contains the samples updated to version 2.7.18. You can find the same examples upgraded to the latest [3.x](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/sb-3-main) version of Spring Boot in a dedicated branche. Feel free to use **Spring Boot 3** while reading the book. Only a few minor changes are necessary to the code samples and they are documented [here](https://github.com/ThomasVitale/cloud-native-spring-in-action/blob/sb-3-main/README.md).
## Prerequisites
Chapter after chapter, you'll build, containerize, and deploy cloud native applications. Along the journey, you will need the following software installed.
* Java 17+
* OpenJDK: [Eclipse Temurin](https://adoptium.net)
* GraalVM: [GraalVM](https://www.graalvm.org)
* JDK Management: [SDKMAN](https://sdkman.io)
* Docker 24+
* [Docker for Linux](https://docs.docker.com/engine/install/ubuntu/)
* [Docker Desktop for Mac](https://www.docker.com/products/docker-desktop)
* [Docker Desktop for Windows](https://www.docker.com/products/docker-desktop)
* Kubernetes 1.28+
* [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)
* [minikube](https://minikube.sigs.k8s.io/docs/)
* Other
* [HTTPie](https://httpie.org/)
## Gradle and Maven
The code samples in the book use Gradle as the build tool. Should you prefer Maven, here's a table mapping Gradle commands to Maven so that you can easily follow along.
Gradle | Maven
------ | ------
`./gradlew clean` | `./mvnw clean`
`./gradlew build` | `./mvnw install`
`./gradlew test` | `./mvnw test`
`./gradlew bootJar` | `./mvnw spring-boot:repackage`
`./gradlew bootRun` | `./mvnw spring-boot:run`
`./gradlew bootBuildImage` | `./mvnw spring-boot:build-image`
## Guides, Tools and Tips
* [Configuring IntelliJ IDEA](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/configuring-intellij-idea.md)
* [Configuring Visual Studio Code](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/configuring-visual-studio-code.md)
* [Minikube configuration behind a proxy](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/minikube-configuration-behind-a-proxy.md)
* [Observability setup on Kubernetes](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/grafana-observability-stack)
* [Replacing Kubeval with Kubeconform](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/replacing-kubeval-with-kubeconform.md)
* [Setting up a Kubernetes cluster for Polar Bookshop on Azure](#)
* [Setting up a Kubernetes cluster for Polar Bookshop on DigitalOcean](#)
* [Working with macOS on Apple Silicon](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/working-with-macos-on-apple-silicon.md)
* [Working with Windows](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Guides/working-with-windows.md)
## Source Code by Chapter
| Chapter | Starting point | Intermediate version | Final version |
|---------|----------------|----------------------|---------------|
| 1. Introduction to cloud native | - | - | - |
| 2. Cloud native patterns and technologies | [02-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter02/02-begin) | - | [02-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter02/02-end) |
| 3. Getting started with cloud native development | [03-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter03/03-begin) | - | [03-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter03/03-end) |
| 4. Externalized configuration management | [04-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter04/04-begin) | - | [04-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter04/04-end) |
| 5. Persisting and managing data in the cloud | [05-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter05/05-begin) | [05-intermediate](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter05/05-intermediate) | [05-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter05/05-end) |
| 6. Containerizing Spring Boot | [06-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter06/06-begin) | - | [06-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter06/06-end) |
| 7. Kubernetes fundamentals for Spring Boot | [07-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter07/07-begin) | - | [07-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter07/07-end) |
| 8. Reactive Spring: Resilience and scalability | [08-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter08/08-begin) | - | [08-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter08/08-end) |
| 9. API gateway and circuit breakers | [09-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter09/09-begin) | - | [09-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter09/09-end) |
| 10. Event-driven applications and functions | [10-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter10/10-begin) | [10-intermediate](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter10/10-intermediate) | [10-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter10/10-end) |
| 11. Security: Authentication and SPA | [11-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter11/11-begin) | - | [11-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter11/11-end) |
| 12. Security: Authorization and auditing | [12-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter12/12-begin) | - | [12-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter12/12-end) |
| 13. Observability and monitoring | [13-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter13/13-begin) | - | [13-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter13/13-end) |
| 14. Configuration and secrets management | [14-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter14/14-begin) | - | [14-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter14/14-end) |
| 15. Continuous delivery and GitOps | [15-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter15/15-begin) | - | [15-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter15/15-end) |
| 16. Serverless, GraalVM and Knative | [16-begin](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter16/16-begin) | - | [10-end](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/Chapter16/16-end) |
## Polar Bookshop
The final project developed throughout the book is available [here](https://github.com/ThomasVitale/cloud-native-spring-in-action/tree/main/PolarBookshop).
You can find the source code for the Angular frontend [here](https://github.com/PolarBookshop/polar-ui/tree/v1).
## Book Forum
Feel free to submit questions, feedback, or errata to the forum dedicated to "Cloud Native Spring in Action": https://livebook.manning.com/book/cloud-native-spring-in-action/.
## Contact the Author
You are very welcome to contact me for questions, feedback, or suggestions. Feel free to reach out to me on [Twitter](https://twitter.com/vitalethomas), [LinkedIn](https://www.linkedin.com/in/vitalethomas), [Mastodon](https://mastodon.online/@thomasvitale), [BlueSky](https://bsky.app/profile/thomasvitale.com) or here on [GitHub](https://github.com/ThomasVitale/).
| 0 |
git-moss/ConvertWithMoss | Converts multisamples from a source format (WAV, multisample, KMP, wavestate, NKI, SFZ, SoundFont 2) to a different destination format. | converter multi-sample music samples | # ConvertWithMoss
Converts multisamples in a specific source format to a different destination format. Furthermore, it can create multisample files from plain WAV files.
Additionally, the conversion process reads and writes metadata (name, category, creator, description and keywords) as well as envelopes and filter settings, if supported by the format. If the source format does not support the information a guessing algorithm is applied based on the samples names.
Furthermore, samples can be grouped into groups and key ranges. Each sample can have 1 or no loop and parameters for pitch and different playback parameters.
## Supported formats
The following multisample formats are supported as the source and destination formats (except SF2 is currenlty only a source):
1. 1010music blackbox, tangerine, bitbox (preset.xml)
2. Akai MPC Keygroups (*.xpm)
3. CWITEC TX16Wx (*.txprog)
4. DecentSampler (*.dspreset, *.dslibrary)
5. Korg KMP/KSF (*.KMP)
6. Korg wavestate/modwave (*.korgmultisample)
7. Logic EXS24 (*.exs)
8. Multisample Format (*.multisample)
9. Native Instruments Kontakt (*.nki)
10. Propellerhead Reason NN-XT (*.sxt)
11. SFZ (*.sfz)
12. SoundFont 2 (*.sf2)
13. WAV files (*.wav)
See [README-FORMATS.md][1] document for more details. Even more details about the specific converted parameters can be found here:
https://github.com/git-moss/ConvertWithMoss/blob/main/documentation/SupportedFeaturesSampleFormats.ods
## Installation
[Download][2] and run the matching installer for your operating system.
After that you can start the application ConvertWithMoss.
> **Note**
>
> macOS users should read [README-MACOS.md][3] document for important notices.
## Build from sources
Ensure to have the required `JVM`, `JRE`, `JavaFX` and `Maven` dependencies preinstalled and set the `JAVA_HOME` environment variable to specify which Java version to use; the minimum required version is `17`. Then use `mvn install` command to start the build.
See also the various build scripts in this directory as references on how to build the documentation and/or the application source files.
For Linux (BSD not tested) there is also a `Makefile` for build and install with the usual `make` and `make install` commands.
## Usage
1. Select a source folder, which contains one or multiple folders with multisamples in the selected source format. The files can also be located in sub-folders.
2. Select the output folder where you want to create the multisamples. This folder must be empty. You can add a non-existing folder to the name, which then is automatically created. E.g. you could select the Desktop and then add a folder *Conversions*.
3. Press the *Convert* button to start the conversion. The progress is shown with notification messages in the log area, which you should check for potential errors like defect source files, skipped folder, etc.
Alternatively, press *Analyse* to execute the same process as *Convert* but does not write any files. Use this to check for errors before finally running the conversion.
### Options
* **Renaming**: Allows to rename multi-samples. Enable the checkbox to use this feature. If enabled select the file which contains the mapped names. The file is a simple text file in UTF-8 format (important if non-ASCII characters are used!). Each row contains one mapping. A mapping consists of 2 names separated either by ';' or ','. E.g. a row which contains "AcPno;Acoustic Piano" would name a multi-sample with the name "AcPno" into "Acoustic Piano" as output.
* **Create folder structure**: If enabled, sub-folders from the source folder are created as well in the output folder. For example, if I select my whole "Sounds" folder, there are sub-folders like `Sounds\07 Synth\Lead\01W Emerson'70 Samples`. In that case the output folder would contain e.g. `07 Synth\Lead\01W Emerson'70.multisample` if Bitwig multisample is selected as the destination format.
* **Add new files**: Starts the conversion even if the output folder is not empty but only adds files which are not already present.
* **Dark Mode**: Toggles the user interface between a light and dark layout.
[1]: README-FORMATS.md
[2]: https://mossgrabers.de/Software/ConvertWithMoss/ConvertWithMoss.html
[3]: README-MACOS.md
| 0 |
apache/sling-samples | Apache Sling Samples | graphql java samples sling | [](https://sling.apache.org)
 [](https://ci-builds.apache.org/job/Sling/job/modules/job/sling-samples/job/master/) [](https://ci-builds.apache.org/job/Sling/job/modules/job/sling-samples/job/master/test/?width=800&height=600) [](https://sonarcloud.io/dashboard?id=apache_sling-samples) [](https://www.apache.org/licenses/LICENSE-2.0)
Apache Sling Samples
---
This repository contains various samples, generally unrelated to each other.
See the README of each sample for more info.
| 0 |
dyn4j/dyn4j-samples | A collection of samples that use the dyn4j library in a variety of ways | dyn4j | # dyn4j-samples
A collection of samples that use the dyn4j library in a variety of ways.
The intent of these samples is to provide a simple framework for building applications with the dyn4j library. The samples show how to use features like joints, static collision detection, raycasting, CCD, and so on. They also provide some creative ways to solve common problems like one-way platforms, jumping, destruction, player control, and so on. That said, none of these are intended to be complete solutions or even the correct solution for your use-case.
* All samples support zoom and pan using the mouse and mouse wheel
* All samples support object manipulation with the mouse
* All samples have features like reset, reset camera, toggle rendering, etc.
* Each sample may have it's own controls - see the console output when running for the full list of controls
| Sample | Description | Concepts |
| --- | --- | --- |
| [BasketBall](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/BasketBall.java) | A side view basketball game | Player Input, DistanceJoint, RevoluteJoint, Image Mapping/Texturing, Filtering, Bounds Listening |
| [Billiards](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Billiards.java) | A top down billiards simulation | Density, Friction, Damping, Player Input |
| [Bowling](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Bowling.java) | A side view of a bowling ball hitting pins | Density, Friction, Restitution, CategoryFilter |
| [Bridge](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Bridge.java) | A side view of a bridge made from joined bodies | RevoluteJoint |
| [Bucket](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Bucket.java) | A side view of a bucket with 200 random objects | Larger world |
| [Concave](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Concave.java) | A side view of a concave object | Concave vs. Convex, Convex Composition |
| [Crank](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Crank.java) | A side view of a piston | RevoluteJoint, PrismaticJoint |
| [Decomposition](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Decomposition.java) | A side view of a few simple polygons decomposed | Convex Decomposition |
| [Destructible](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Destructible.java) | A side view of destruction of a body and joint | Remove/Add Buffering |
| [Images](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Images.java) | A side view of a scene where images are mapped to bodies | Image Mapping/Texturing |
| [LinkTerrain](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/LinkTerrain.java) | A side view of a link-based floor | Smooth Sliding, Link |
| [Maze](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Maze.java) | A top down view of a maze with a player controled body | MotorJoint, Player Control |
| [Organize](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Organize.java) | A side view of a scene where bodies are randomly joined and self organize | DistanceJoint |
| [Platformer](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Platformer.java) | A side view of a platformer simulation | OnGround, Player Control, One-way Platform, Jumping |
| [Pyramid](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Pyramid.java) | A side view of a Pyramid of stacked boxes | Stacking |
| [Ragdoll](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Ragdoll.java) | A side view of a ragdoll made from joints | RevoluteJoint |
| [Stacking](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Stacking.java) | A side view of a scene where the player can add boxes dynamically | Stacking, Add Bodies |
| [Tank](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Tank.java) | A top down tank simulation | Raycasting, Player Control, FrictionJoint, RevoluteJoint |
| [Thrust](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Thrust.java) | A side view of a scene with a rocket | Applying Forces |
| [Tracking](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Tracking.java) | A scene where contact tracking is printed to the console | Contact Tracking |
| [Truck](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/Truck.java) | A scene where a truck filled with boxes moves through a world | WheelJoint, Fixture Composition |
| [UsingGraphics2D](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/UsingGraphics2D.java) | A scene with just a bunch of shapes rendered via Java 2D | Java 2D |
| [UsingJogl](https://github.com/dyn4j/dyn4j-samples/tree/master/src/main/java/org/dyn4j/samples/UsingJogl.java) | A scene with a few shapes rendered via OpenGL via JOGL | JOGL |
### BasketBall
Use angle, power, and position to attempt to make baskets. The sample only scores goals, so don't miss! If you are close you get 2 points, far away you get 3. Only if you get it in when you launch it is counted.

### Billiards
Use the cue stick to hit the cue ball to hit the other balls. You must wait until the balls settle before your next hit.

### Platformer
Use the ball to "run" around the level and jump. You can jump onto platforms above you no matter where you are, but if you land on them, they are solid. You can drop down from the top level as well. Green means you are touching the ground and can jump. Purple means you are not touching the ground.

### Ragdoll
Use your mouse to drag around and contort the ragdoll

### Tank
Drive a tank! Independently operating the tracks and barrel. The barrel will be pushed aside by obstacles. The barrel is "shooting" a ray to see what it would hit. You can press a key to destroy the closest object you are aiming at.

### Thrust
How hard can it be to fly a rocket? Using only front, back and side thrusters (applied force) fly a rocket around an enclosed area. Challenge yourself to land without tipping over or flying in a smooth trajectory.

### Truck
Drive a truck with cargo! Accelerate and decelerate using the keyboard or stop immediately. Watch the contents slide around as you drive. Use the mouse to manipulate the truck frame to see the suspension compress.

| 0 |
CatalinPrata/funcodetuts | Funcode sample tutorials | null | funcodetuts
===========
Funcode sample tutorials, you can find more on https://www.myandroidsolutions.com/
| 1 |
devops-dojo/the-app | Sample application and CD Pipeline for DevOps Dojo | devops hubot pipeline pipelines-as-code reference-implementation | # Microservice Phone Shop Application and CD pipeline
## Introduction
This application and its continuous delivery pipeline is used as training
material during the DevOps Dojo green belt training.
## Overview
This application gives software architects and developers an example how a
microservice web application can look like and it simulates a development
cluster, which contains continuous integration infrastructure as well as all
necessary nodes that are needed to run an online shop. Thus it will furthermore
shown, how a distributed online shop can deployed with a multi deployment
pipeline and how the distributed system can be monitored. The application is
based on the following two online shop applications, which can be found on
Github:
- [AngularJS Phone Catalog](https://github.com/angular/angular-phonecat)
- [MongoDB Pizza Shop](https://github.com/comsysto/mongodb-onlineshop)
Both project were combined to an new online shop that is indeed to sell mobile devices and implements the following use
cases. A user is able to:
- see different kinds of mobile devices catalogs (e.g. mobiles or tablets),
- create a cart,
- and order the created cart.

This use cases are implemented in the following two ways:
- A [Monolitic Webshop](https://github.com/devops-dojo/the-app/#monolith-appserver), which is represented by a three layered
online shop based on [Apache Wicket](http://wicket.apache.org/), the [Spring Framework](http://projects.spring.io/spring-framework/)
and [Spring Data](http://projects.spring.io/spring-data/) that implements all given use cases,
- and microservice architecture, which is based on a mix of the Monolitic Webshop and a [Microservice Catalog Frontend](https://github.com/devops-dojo/the-app/#microservice-appserver)
as it is shown in the below deployment diagram. In this mix a so called Microservice Catalog Frontend provides the
use case that an user should be able to see the different mobile. Finally the Monolitic Webshop is used by the user
to create an order that means Monolitic Webshop represents a microservice on its own for this specific use case.
The Microservice Catalog Frontend is based on an [AngularJS](https://angularjs.org/) and [Typescript](http://www.typescriptlang.org/)
which access different kinds of [REST-Services](http://en.wikipedia.org/wiki/Representational_state_transfer) that are
implemented in [Scala](http://www.scala-lang.org/), [Spray](http://spray.io/), [Restx](http://restx.io/) and [Spring Boot](http://projects.spring.io/spring-boot/).

## Used technologies
For simplicity all services are supposed to run on a Java-VM at the moment.
* Web frontend
* Based on Angular JS and Typescript
* Cart service
* Based on Spring boot and Groovy
* Redis backend via Spring Data
* Product backend
* Based on Scala and Spray
* MongoDB backend via ReactiveMongo
* Navigation backend
* Based on Restx with embedded Jetty
* MongoDB backend via Jongo
## Directory Layout
The following directory layout shows only the important directories that are necessary to implement the given use cases
in the [overview](https://github.com/devops-dojo/the-app/#overview).
microservice/ --> all files of the microservice applications are located in this folder
frontend/ --> all microservice frontend applications are located in this folder
catalog/ --> an AngularJS frontend application that shows the product catalog and is used to create a cart is located in this directory
checkout/ --> all files that are needed to glue the checkout form of the monolithic to the microservice catalog frontend
service/ --> all business services are located in the folder
cart/ --> a spring boot cart rest service is located in the folder
navigation/ --> a java based restx navigation rest service is located in the folder
product/ --> a scala spray product rest service is located in the folder
monolithic/ --> all files of the monolithic application are located in this directory
vagrant/ --> Install the application and the continuous delivery pipeline (local VirtualBox or Microsoft Azure)
## Prerequisites
You need some dependencies to run the application cluster or to add your own services to the showcase application.
###Running
See [vagrant directory](/vagrant) on installing the cluster of machines to run the application and the continuous delivery pipeline. You need at least 16 GB RAM to run the whole cluster in one machine (local virtualbox) or leverage the Azure cloud installer to have different VMs for each function.
If you just want to run the application, use Docker: [Docker](/compose/README.md)
## The application
###Microservice Appserver
The microservice based online shop is deployed on the microservice appserver
which is a reference implementation for the given use cases in the
[Overview](https://github.com/devops-dojo/the-app/#overview). You can reach the
online shop under the following url
http://shop.microservice.io/.

The microservice based online shop consists of two frontend parts as you can see
in the deployment diagram in the [overview
section](https://github.com/devops-dojo/the-app/#overview). The first part is an
AngularJS Catalog Frontend that makes it possible to see a catalog for mobiles
as well as a catalog for tablets. Furthermore a user is able to create a cart.
If a user wants to order a created cart there is same clue logic in the
[monolithic web
application](https://github.com/devops-dojo/the-app/#monolith-appserver) that a
cart which was created in the AngularJS Catalog Frontend can be order with the
checkout of the Wicket online shop on the monolith appserver.
###Monolith Appserver
The monolith online shop is deployed on the Monolith Appserver which is a
reference implementation for the given use cases in the
[Overview](https://github.com/devops-dojo/the-app/#overview). You can reach the
online shop under the following url
http://shop.monolith.io:8080/shop/ .

## The Continuous Delivery pipeline
### CI-Node
A Jenkins build server is running on the CI-Node. Jenkins is an open source continuous integration tool written in Java
that provides a continuous integration services for software development which supports different SCM tools. Furthermore
Jenkins can execute different build scripts like [Gradle](http://gradle.org/) as well as arbitrary
shell scripts and Windows batch commands.
You can reach the jenkins that builds and deploy the monolith and microservice application under the following url http://ci.microservice.io:8080/.

### Monitoring Server
Monitoring a monolithic web application is no major pain as you can see in the [monolith appserver section](https://github.com/devops-dojo/the-app/#monolith-appserver).
A distributed web application, like it is shown in the [microservice appserver section](https://github.com/devops-dojo/the-app/#microservice-appserver),
is not so easy to monitor. In this small example there is a [Ngnix](http://nginx.org/) web server that logs all request
that comes into it. The Ngnix deliveries a AngularJS Catalog Frontend that
represents a A single-page application (SPA). A SPA is a web application that
fits on a single web page with the goal of providing a more fluid user
experience akin to a desktop application. In addition to the SPA there are the
three rest services a cart, product and a navigation service which are need for
the different uses cases and are implemented in the programming languages
Groovy, Scala and Java. This services must be alive that an user can see the
products or create a cart. Furthermore there is a legacy JEE web application
which is deployed in a [Tomcat Webserver](http://tomcat.apache.org/). An user
can order its cart with that legacy JEE web application.
#### Icinga
Icinga is an open source network and computer system monitoring application. It
was originally created as a fork of the Nagios system monitoring application.
Icinga is attempting to get past perceived short-comings in Nagios development
process, as well as adding new features such as a modern Web 2.0 style user
interface, additional database connectors, and a REST API that lets
administrators integrate numerous extensions without complicated modification of
the Icinga core.


#### Kibana
Kibana is a browser based analytics and search interface for Elasticsearch that was developed primarily to view
Logstash event data. Logstash is a tool that can be used to collect, process and forward events and log messages.
Collection is accomplished via number of configurable input plugins including raw socket/packet communication,
file tailing and several message bus clients. Once an input plugin has collected data it can be processed by any number
of filters which modify and annotate the event data. Finally events are routed to output plugins which can forward the
events to a variety of external programs including Elasticsearch, local files and several message bus implementations.

#### PSI Probe
Furthermore you can reach the [PSI Probe](https://code.google.com/p/psi-probe/)
monitoring and log analysis services under the following url
http://shop.monolith.io:8080/probe/. The user
credentials are admin / topsecret.
PSI Probe is a community-driven fork of Lambda Probe, which is intended to replace the Tomcat Manager and should make
it easier to manage and monitor an instance of Apache Tomcat. PSI Probe does not require any changes to an existing app
and it provides many features through a web-accessible interface that becomes available simply by deploying it to your
server. These features include:
- Requests: Monitor traffic in real-time, even on a per-application basis.
- Sessions: Browse/search attributes, view last IP, expire, estimate size.
- Logs: View contents, download, change levels at runtime.
- Threads: View execution stack, kill.
- JVM: Memory usage charts, advise GC.


#### JETM
JETM performance monitor [JETM](http://jetm.void.fm/) is at the following url
http://shop.monolith.io:8080/shop/performance/. JETM
is a small and free library that is included in the monolith online shop, that
helps locating performance problems in existing Java applications. JETM enables
developers to track down performance issues on demand, either programmatic or
declarative with minimal impact on application performance, even in production.


#### JMX
[JMX](http://en.wikipedia.org/wiki/Java_Management_Extensions) is a natural way to have access to technical management,
e.g. for tuning, statistics, log levels and so on. Unfortunately, it lacks a lightweight tool to expose mbeans and to browse
them securely on any application and environment without heavy infrastructure setup. [JMiniX](https://code.google.com/p/jminix/)
provides such a feature. You can reach JMiniX under the following url http://shop.monolith.io:8080/shop/jmx/.

## Credits
A lot of this repository leverages the work from [Bernd Zuther](https://github.com/zutherb/).
## Contact
If you have any questions or remarks, please use the [issue tracker](https://github.com/devops-dojo/the-app/issues)
## Licensing
This work is open source, and is licensed under the Apache License, Version 2.0.
| 1 |
arun-gupta/serverless | Serverless samples | null | null | 0 |
jgoodyear/ApacheKarafCookbook | Samples for Packt Publishing's Apache Karaf Cookbook | null | Apache Karaf Cookbook
=====================
Samples for Packt Publishing's Apache Karaf Cookbook.
The samples in this project were written with JDK 1.7 and Maven 3.0.5.
1. Apache Karaf for system builders.
2. Making a Smart Router with Apache Camel. (Sample Chapter)
3. Deploying a Message Broker with Apache ActiveMQ.
4. Hosting a JSP with Pax-web.
5. Hosting web services with Apache CXF.
6. Distributing a clustered container with Apache Karaf Cellar.
7. Providing a persistence layer with Apache Aries and OpenJPA.
8. Making a scalable persistence layer with Apache Cassandra.
9. Manage big data with Apache Hadoop.
Recipes tested on:
* Suse Enterprise Linux 11 sp3
* Ubuntu LTS 12.04 Server
* Windows Pro 7
* Mac OSX 10.9
| 0 |
aws-samples/amazon-eks-jenkins-terraform | These samples focus on Continuous Integration, and contain installation and configuration of Jenkins on Amazon EC2 using Hashicorp Terraform (Open Source) | null | # Continuous Intergration on Amazon EKS
<br />
## Prerequisites
To implement the instructions in this post, you will need the following accounts:
* An AWS account – [how to create a new AWS account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)
* A Docker hub account – [how to register for docker id](https://success.docker.com/article/how-do-you-register-for-a-docker-id)
* A GitHub account – [sign up for a new GitHub account](https://help.github.com/en/github/getting-started-with-github/signing-up-for-a-new-github-account)
<br />
## Architecture
<img width="1042" alt="architecture-screenshot" src="images/Architecture.png">
<br />
## Sample Application [](https://travis-ci.org/spring-projects/spring-petclinic/)
### Understanding the Spring Petclinic application with a few diagrams
### Running petclinic locally
Petclinic is a [Spring Boot](https://spring.io/guides/gs/spring-boot) application built using [Maven](https://spring.io/guides/gs/maven/). You can build a jar file and run it from the command line:
```
git clone https://github.com/aws-samples/amazon-eks-jenkins-terraform
cd amazon-eks-jenkins-terraform
./mvnw package
java -jar target/*.jar
```
You can then access petclinic here: http://localhost:8080/
<img width="1042" alt="petclinic-screenshot" src="https://cloud.githubusercontent.com/assets/838318/19727082/2aee6d6c-9b8e-11e6-81fe-e889a5ddfded.png">
Or you can run it from Maven directly using the Spring Boot Maven plugin. If you do this it will pick up changes that you make in the project immediately (changes to Java source files require a compile as well - most people use an IDE for this):
```
./mvnw spring-boot:run
```
| 0 |
bijukunjummen/spring-cloud-ping-pong-sample | Sample spring-cloud based app | null | ## Up and running with Sample Spring-Cloud based app
There are two ways to run the entire application:
- On Local Machine
- Using Docker
### On Local Machine
Running it all local is simple, do the following in sequence, in four different terminal windows:
#### Start up Eureka
```sh
cd sample-eureka
../mvnw spring-boot:run
```
#### Start up Config server
```sh
cd sample-config
../mvnw spring-boot:run
```
#### Start up Pong Service
```sh
cd sample-pong
../mvnw spring-boot:run
```
and test with:
```shell
curl -v -X POST \
-H "Content-type: application/json" \
-H "Accept: application/json" \
http://localhost:8082/message \
-d '{
"id": "test",
"payload": "hello"
}'
```
#### Start up Gateway
```sh
cd sample-gateway
../mvnw spring-boot:run
```
and test with:
```shell
curl -v -X POST \
-H "Content-type: application/json" \
-H "Accept: application/json" \
http://localhost:8082/message \
-d '{
"id": "test",
"payload": "hello"
}'
```
#### Start up Ping Service
```sh
cd sample-ping
../mvnw spring-boot:run
```
If all the applications have come up cleanly, the endpoint should be available at http://localhost:8080
### On Docker
Running using Docker is even simpler, assuming that docker-compose and docker are installed on your box, just run the following:
#### Build the docker images for the microservices
```sh
mvn clean package docker:build
```
#### Start up Docker containers
```sh
docker-compose up
```
That is it, the endpoint should be available at http://dockerhost:8080 | 1 |
yangliuy/LDAGibbsSampling | Open Source Package for Gibbs Sampling of LDA | gibbs-sampling java lda topic topic-modeling | LDAGibbsSampling
================
/**
Copyright (C) 2013 by
SMU Text Mining Group/Singapore Management University/Peking University
LDAGibbsSampling is distributed for research purpose, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Feel free to contact the following people if you find any
problems in the package.
lyang@cs.umass.edu
Updated in Oct. 10, 2016. * */
Brief Introduction
=============================
1. This is an open source implementation for Gibbs Sampling of LDA. The data set is Newsgroup-18828, which is included in the project. You can test other data sets with it. Just import the project into Eclipse and run LdaGibbsSampling.java to start it without any configuration. The sample original documents and sample output files have been included. To download the whole Newsgroup-18828 data set, you can refer to http://qwone.com/~jason/20Newsgroups/ .
2. The format of the output files
lda_n.params: the hyper-parameters of the LDA model.
lda_n.phi: a K * V matrix, which is the leant topic word distribution.
lda_n.tassign: the topic assignments of each word in each document when there are n iterations.
lda_n.theta: a M * K matrix, which is the learnt document topic distribution.
lda_n.twords: the top topic words with their probabilies under each topic.
2. The author's technical blog : http://blog.csdn.net/yangliuy
The author's homepage:https://people.cs.umass.edu/~lyang
For more information of LDA and Gibbs Sampling: http://blog.csdn.net/yangliuy/article/details/8302599 (a technical blog on LDA and Gibbs Sampling in Chinese.)
3. This is an initial implementation for the Topic Expertise Model which is proposed in the following paper:
Liu Yang, Minghui Qiu, Swapna Gottipati, Feida Zhu, Jing Jiang, Huiping Sun and Zhong Chen. CQARank: Jointly Model Topics and Expertise in Community Question Answering. In Proceedings of the 22nd ACM International Conference on Information and Knowledge Management (CIKM 2013). (http://dl.acm.org/citation.cfm?id=2505720) (http://www.mysmu.edu/faculty/fdzhu/paper/CIKM'13.pdf) (https://ink.library.smu.edu.sg/cgi/viewcontent.cgi?article=3232&context=sis_research)
If you use this model implementation, please cite this paper.
4. We will also release more open source code for topic models in https://github.com/yangliuy.
| 0 |
jkazama/ddd-java | Spring Boot + Java [ DDD Sample ] | ddd devcontainer java spring-boot | ddd-java
---
### Preface
It is DDD sample implementation from [Spring Boot](http://projects.spring.io/spring-boot/).
It is not a framework, This is a simple example of the implementation based on Evans's DDD.
#### 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.
- Use standard definitions as much as possible, such as DB settings.
- The configuration file uses yml. do not use xml files for Bean definition.
- The exception handling defines it in a endpoint (RestErrorAdvice).
#### Use policy of Java coding
- Java17 over
- 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
- 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 *ddd-java* 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 ddd-java`.
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+.
Do the server start in the next step.
1. You move to the cloned *ddd-java* 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 -H "Content-Type: application/json" -d '{"accountId" : "sample" , "currency" : "JPY", "absAmount": 1000}' http://localhost:8080/asset/cio/withdraw`
- Request for withdrawal.
- `curl 'http://localhost:8080/asset/cio/unprocessedOut'`
- Search for outstanding withdrawal requests
#### Internal Use Case
- `curl 'http://localhost:8080/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 http://localhost:8080/system/job/daily/closingCashOut`
- Close the withdrawal request.
- `curl -X POST http://localhost:8080/system/job/daily/processDay`
- Set the business day to the next day.
- `curl -X POST http://localhost:8080/system/job/daily/realizeCashflow`
- Realize cash flow. (Reflected to the balance on the delivery date)
> Please execute according to the business day appropriately
### 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 |
gwtboot/gwt-boot-samples | GWT Boot: Samples to check all the Starters | boot framework gwt java javascript spring-boot starter | # GWT Boot Samples

Here you can find some samples on how you can use the GWT Boot Starters in
your project. This quickstart document is based on following sample project: [gwt-boot-sample-basic](https://github.com/gwtboot/gwt-boot-samples/tree/master/gwt-boot-sample-basic).
Introduction article about GWT Boot Starters: [GWT Boot Starters — Bootstrap a Simple GWT Web App](https://bit.ly/GWTBootStartersFinal)
# IDE
You can use IntelliJ or Eclipse / STS. To be able to use Java APT correctly please take a look on how
to [configure Java APT with Maven](https://immutables.github.io/apt.html) in each development environment.
# Quick Start
## Step 1 - Create a Maven Project
Just create a simple Maven Project. Add the parent project and the
starter dependencies. To be able to compile to JavaScript you
need to add _gwt-maven-plugin_ and add your GWT module name.
```xml
<parent>
<groupId>com.github.gwtboot</groupId>
<artifactId>gwt-boot-starter-parent</artifactId>
<version>VERSION</version>
</parent>
<dependencies>
<dependency>
<groupId>com.github.gwtboot</groupId>
<artifactId>gwt-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>net.ltgt.gwt.maven</groupId>
<artifactId>gwt-maven-plugin</artifactId>
<configuration>
<moduleName>hello.YourModule</moduleName>
<startupUrls>
<url>/basic/</url>
</startupUrls>
</configuration>
</plugin>
</plugins>
</build>
```
**If you are using the SNAPSHOT version of the starter** you need to add Sonatype Snapshots repository by extending or creating `<repositories>` section since the `gwtboot-modules` are not released yet, so the example needs to access the SNAPSHOT version of `gwtboot-modules`.
```xml
<repositories>
<repository>
<id>sonatype-snapshots</id>
<name>Sonatype Snapshots</name>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
```
## Step 2 - Create a GWT Module Descriptor _module.gwt.xml_
Create a GWT module descriptor at _src/main_ directory. In this file
you describe the _EntryPoint_ class which is similar to Java Main class
and method. Module rename-to="basic" means that the JavaScript will
be compiled to the script _basic.nocache.js_. This module inherits
everything from the Starter module. This JavaScript
can be imported in the host HTML file on the next step.
```xml
<module rename-to="basic">
<inherits name="com.github.gwtboot.starter.Starter"/>
<entry-point class='hello.client.YourEntryPoint'/>
</module>
```
## Step 3 - Create a Host HTML File where your JavaScript can run
In this HTML file, located at _hello/public_, your generated JavaScript will run.
This JavaScript can access the HTML file. In this example the generated JavaScript
will access the div with _id="helloButton"_.
```html
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Demo GWT Webapp</title>
<script type="text/javascript" language="javascript"
src="basic.nocache.js" async=""></script>
</head>
<body>
<div id="helloButton"/>
</body>
</html>
```
## Step 4 - Create your Java Entry Point _Main_ Class
The EntryPoint is the first class which will be executed.
In this example it will exchange the _"helloButton"_ with a
Button.
```java
package hello.client;
import com.google.gwt.core.client.*;
import com.google.gwt.user.client.ui.*;
public class YourEntryPoint implements EntryPoint {
@Override
public void onModuleLoad() {
Button button = new Button("Click me");
button.addClickHandler(clickEvent -> {
Window.alert("Hello World!");
});
RootPanel.get("helloButton").add(button);
}
}
```
In [gwt-boot-sample-basic](https://github.com/gwtboot/gwt-boot-samples/tree/master/gwt-boot-sample-basic)
you can take a look at the basic example in GWT.
Now you are ready to start your GWT basic sample app for the first time.
# Starting GWT in SuperDev Mode
The application _[gwt-boot-sample-basic](https://github.com/gwtboot/gwt-boot-samples/tree/master/gwt-boot-sample-basic)_
uses integrated Jetty server from GWT to deliver the HTML host file.
This can be done with other Servlet apps as well.
## Step 1 - Run GWT DevMode to automatically compile the code
First generate the GWT Module Descriptor and then run the GWT Dev Mode
in SuperDev mode to be able to compile the Java code to JavaScript code
on reload in the web browser. In Maven you can run following command:
```java
mvn gwt:generate-module gwt:devmode
```
You can just generate the module once and after that just run:
```java
mvn gwt:devmode
```

## Step 2 - Run the App in your Browser
Now you can copy&paste the "Copy to Clipboard" result of the GWT Development Mode UI above. Run it on:
```java
http://localhost:8888/basic
```
Just reload your web app and GWT SuperDev mode will transpile your
Java code to JavaScript on the fly. That's it, now you can develop
your web app with GWT incrementally and fast!
## Step 3 - Debug the App in your Browser
You can debug the Java code on the browser with the help of source maps. In this example we use Google Chrome.

Enjoy!
| 0 |
AndroidAdvanceWithGeektime/Chapter07 | Sample for Add Systrace Tag | null | # Chapter07
这个Sample是学习如何给代码加入Trace Tag, 大家可以将这个代码运用到自己的项目中,然后利用systrace查看结果
结果如下:
```
protected void onResume() {
TraceTag.i("com.sample.systrace.MainActivity.onResume.()V");
super.onResume();
Log.i("MainActivity", "[onResume]");
TraceTag.o();
}
```
## 操作步骤
操作步骤如下:
1. 使用Android Studio打开工程Chapter07
2. 运行gradle task ":systrace-gradle-plugin:buildAndPublishToLocalMaven" 编译plugin插件
3. 使用Android Studio单独打开工程systrace-sample-android
4. 编译app
## 注意事项
在systrace-sample-android工程中,需要注意以下几点:
1. 插桩代码会自动过滤短函数,过滤结果输出到`Chapter07/systrace-sample-android/app/build/systrace_output/Debug.ignoremethodmap`。
2. 我们也可以单独控制不插桩的白名单,配置文件位于`Chapter07/systrace-sample-android/app/blacklist/blackMethodList.txt`, 可以指定class或者包名。
3. 插桩后的class文件在目录`Chapter07/systrace-sample-android/app/build/systrace_output/classes`中查看。
然后运行应用,需要打开systrace
```
python $ANDROID_HOME/platform-tools/systrace/systrace.py gfx view wm am pm ss dalvik app sched -b 90960 -a com.sample.systrace -o test.log.html
``` | 1 |
johanvos/quantumjava | Samples related to Quantum Computing for Java Developers"" | java quantum quantum-computing | # Quantum Computing samples in Java
This repository contains the source code for the samples discussed in
<a href="https://www.manning.com/books/quantum-computing-for-java-developers?a_aid=quantu
mjava&a_bid=e5166ab9">Quantum Computing for Developers</a>
<a href="https://www.manning.com/books/quantum-computing-for-java-developers?a_aid=quantumjava&a_bid=e5166ab9"><img align="right" src="https://user-images.githubusercontent.com/767876/187063034-b40b74c8-7ff1-4236-b643-383da8003723.png" alt="Quantum Computing for Developers"/></a>
It is based on the <a href="https://github.com/redfx-quantum/strange">Strange</a> Quantum Simulator, which provides an execution environment for
quantum algorithms in Java.
Some samples use a UI, e.g. to visualize the quantum circuit. In
that case, <a href="https://github.com/redfx-quantum/strangefx">StrangeFX</a>
is used, which is a JavaFX-based framework that allows the visualisation
of quantum circuits.
The samples in this repository correspond to the chapters in the book.
Don't worry if you don't have the book, you can still run the
samples.
## Chapter 2: HelloWorld, Quantum Computing
<a href="/ch02/hellostrange">HelloStrange</a>
## Chapter 3: Qubits and Quantum Gates, the basic units in Quantum Computing
<a href="/ch03/paulix">Pauli X</a>
<a href="/ch03/paulixui">Pauli X with user interface</a>
## Chapter 4: Superposition
<a href="/ch04/hadamard">Hadamard</a>
## Chapter 5: Entanglement
<a href="/ch05/classiccoin">Classic coins</a>
<a href="/ch05/quantumcoin">Quantum coins</a>
<a href="/ch05/cnot">CNot gate</a>
<a href="/ch05/bellstate">Bell state</a>
## Chapter 6: Quantum networking, the basics
<a href="/ch06/classic">Classic network</a>
<a href="/ch06/classiccopy">No-cloning theorem</a>
<a href="/ch06/teleport">Quantum Teleportation</a>
<a href="/ch06/repeater">Quantum Repeater</a>
## Chapter 7: Our HelloWorld explained
<a href="/ch07/randombit">RandomBit</a>
<a href="/ch07/randombitdebug">RandomBit with debug</a>
<a href="/ch07/add1">Quantum Adder</a>
<a href="/ch07/add2">Quantum Adder with carry bit</a>
## Chapter 8: Secure Communication using quantum computing
<a href="/ch08/naive">A first (naive) approach</a>
<a href="/ch08/haha">Applying 2 Hadamard gates</a>
<a href="/ch08/superposition">Using superposition</a>
<a href="/ch08/guess">Guess the possibilities</a>
<a href="/ch08/bb84">QKD in Java</a>
## Chapter 9: Deutsch-Jozsa algorithm
<a href="/ch09/function">Constant and balanced functions</a>
<a href="/ch09/reversibleX">Reversible gates</a>
<a href="/ch09/oracle">Quantum oracle</a>
<a href="/ch09/applyoracle">Applying a Quantum oracle</a>
<a href="/ch09/deutsch">Deutsch algorithm</a>
<a href="/ch09/deutschjozsa">Deutsch Jozsa algorithm</a>
## Chapter 10: Grover's Search Algorithm
<a href="/ch10/classicsearch">A classic search function</a>
<a href="/ch10/quantumsearch">Quantum search</a>
<a href="/ch10/grover">The algorithm behind Grover's search</a>
<a href="/ch10/stepbystepgrover">The algorithm, step by step</a>
<a href="/ch10/groveroracle">The quantum Oracle in Grover's search</a>
## Chapter 11: Shor's Algorithm
<a href="/ch11/classicfactor">A classic factoring approach</a>
<a href="/ch11/semiclassicfactor">A classic implementation of a quantum factoringapproach</a>
<a href="/ch11/quantumfactor">A quantum factoring approach</a>
| 0 |
gxercavins/dataflow-samples | Examples using Google Cloud Dataflow - Apache Beam | null | # Dataflow-samples
This repository contains some Google Cloud Dataflow / Apache Beam samples.
## Quickstart
Each folder contains specific instructions for the corresponding example.
Use the below button to clone this repository into Cloud Shell and start right away:
[](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/gxercavins/dataflow-samples&page=editor&tutorial=README.md)
## Examples
Currently, these are the examples available:
* **Adaptive triggers (Java)**: modify the behavior of triggers at the start and end of the same window so that you can have some degree of control on the output rate.
* **Assign sessions (Java)**: assign timestamped events into a given list of all possible sessions.
* **Batch Schema auto-detect (Java)**: how to load multiple JSON files with disparate schemas into BigQuery.
* **BigQuery dead letters (Python)**: how to handle rows that could not be correctly streamed into BigQuery.
* **BigQuery Storage API (Java)**: how to read directly from a BigQuery table using the new Storage API.
* **Data-driven Triggers (Java)**: how to use the State API to simulate data-driven triggers.
* **Dynamic destinations (Java)**: write dynamically to different BigQuery tables according to the schema of the processed record.
* **Empty windows (Java)**: how to log/emit information even when the input source has no data for that window.
* **Filename match (Python)**: read from multiple files and prepend to each record the name of the matching file (optionally enrich with BigQuery).
* **Lag function (Python)**: how to compare an event with the equivalent one from the previous window.
* **Logging GroupByKey (Java)**: some ideas to log information about grouped elements using Stackdriver and BigQuery.
* **Normalize values (Python)**: normalize all PCollection values after calculating the maximum and minimum per each key.
* **Quick, Draw! dataset (Python)**: download raw data from a public dataset, convert to images and save them in `png` format.
* **RegEx pattern (Java)**: tag every path pattern and be able to associate each matched file with it.
* **Session windows (Python)**: example to demonstrate how to group events per user and session.
* **Timestamps in path (Java)**: process hourly files where timestamp needs to be inferred from folder structure.
* **Top10 distinct combiner (Python)**: we'll modify `TopCombineFn` to have unique keys when accumulating fired panes.
* **When are Pub/Sub messages ACKed? (Java)**: example to see what happens with `PubsubIO` in Dataflow.
* **With Timestamps (Java)**: assign processing time as element timestamp and shift to the past if needed.
In addition, the `UTILS` folder contains simple Dataflow snippets: adding labels, stopping jobs programmatically, process files selectively according to their format, understanding wall time, ensuring custom options are globally available, retrieving job ID or SDK version, writing BigQuery results in CSV format, enrich a PCollection with data from a BigQuery table, processing files using Pub/Sub notifications for GCS, etc.
The `BEAM-PATTERNS` folder contains common usage patterns that have been contributed to the Beam documentation.
The `TEMPLATES` folder groups examples that make for some convenient template use cases.
The `PLAYGROUND` folder recaps other more experimental examples that can be interesting to share such as trying to zip a PCollection, throttling a step or BeamSQL tests.
## License
These examples are provided under the Apache License 2.0.
## Issues
Report any issue to the GitHub issue tracker.
| 0 |
SolaceSamples/solace-samples-semp | Getting Started Samples for the Solace SEMP API. | solace solace-samples | [](https://travis-ci.org/SolaceSamples/solace-samples-semp)
# Getting Started Examples
## Solace Element Management Protocol (SEMP)
These tutorials will get you up to speed and managing Solace message routers with SEMP as quickly as possible.
If you are new to SEMP, you can learn more here for full documentation and API reference:
* [SEMP Docs](https://docs.solace.com/SEMP/Using-SEMP.htm#mc-main-content)
* [SEMP API Reference](https://docs.solace.com/SEMP/SEMP-API-Ref.htm)
These tutorials apply to the SEMP API starting in version 2. For older versions of the SEMP API, you can see the [Legacy SEMP Documentation](https://docs.solace.com/SEMP/Using-Legacy-SEMP.htm)
**Note**: SEMP v2 is supported on Solace virtual message routers and Solace message router appliances running SolOS version 7.2.2 and above.
## Contents
This repository contains code and matching tutorial walk throughs for different basic scenarios and programming languages. Sample code is organised in programming language specific subdirectories.
It is best to view the associated [tutorials home page](https://tutorials.solace.dev/semp).
## Prerequisites
There are no prerequisites.
## Building and running the Samples
Refer to the README.md in the [`java`](https://github.com/SolaceSamples/solace-samples-semp/tree/master/java), [`python`](https://github.com/SolaceSamples/solace-samples-semp/tree/master/python) and [`ruby`](https://github.com/SolaceSamples/solace-samples-semp/tree/master/ruby) subdirectories for a short description of how to build and run the samples for the programming languages.
To try individual samples, see the tutorials linked from the [tutorials home page](//solace.com/samples/solace-samples-semp/) for full details which can walk you through the samples, what they do, and how to correctly run them to explore SEMP.
## 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-semp/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:
- The Solace Developer Portal website at: https://solace.dev
- Ask the https://solace.community
- Solace API Tutorials @ https://tutorials.solace.dev
| 0 |
jvm-graphics-labs/jogl-samples | The Java OpenGL Samples Pack | null | # jogl-samples
The Java OpenGL Samples Pack (called unsurprisingly jogl-samples :scream: ) is the java port of the [OpenGL Samples Pack](http://www.g-truc.net/project-0026.html), a collection of [OpenGL](http://www.opengl.org/) samples based on the OpenGL "core profile" specifications.
The project aims to promote the new OpenGL features making easier version transitions for OpenGL programmers with a complementary documentation for the OpenGL specification. Despite the fact that the OpenGL Samples Pack provides as simple (and dumb) as possible samples, it's not a tutorial for beginner but a project for programmers already familiar with OpenGL. The OpenGL Samples Pack is also a good OpenGL drivers feature test.
These samples use [NEWT](http://jogamp.org/jogl/doc/NEWT-Overview.html) to create window and [jogl](http://jogamp.org/jogl/www/) of [Jogamp](http://jogamp.org/) as OpenGL wrapper, [glm](https://github.com/elect86/Jglm) as math library and to replace OpenGL fixed pipeline functions and [gli](https://github.com/elect86/jgli) to load images.
The over 230 samples illustrate almost all OpenGL features ranging from ES 2.0 up to the last GL extenstions, same of them usually also called AZDO (Almost Zero Driver Overhead). They are divided per profiles and I also wrote a little wiki for each profile quoting the most relevant part of g-truc's reviews, really interesting (I have learnt a lot myself reading them):
* [es-200](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/es_200)
* [es-300](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/es_300)
* [gl-300](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_300)
* [gl-320](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_320)
* [gl-330](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_330)
* [gl-400](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_400)
* [gl-410](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_410)
* [gl-420](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_420)
* [gl-430](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_430)
* [gl-440](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_440)
* [gl-450](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_450)
* [gl-500](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/tests/gl_500)
* [micro]
## Quick setup:
- add "-ea" in VM options in run config for the `assert`s to work
- add all the jars you find under [`dependencies`](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/dependencies)
You can find the results inside the [`templates` directory](https://github.com/elect86/jogl-samples/tree/master/jogl-samples/src/templates).
Ps: Hello Triangle and Hello Texture have been moved into a stand-alone [project](https://github.com/elect86/helloTriangle)
Pps: I'd need some guinea pigs (aka: volunteers, but don't worry, it won't hurt :smirk:) to test the amd-only and intel-only extensions :octocat:
## Changelog:
- 03-03-16, [`gl-430-program-compute-variable-group-size`](https://github.com/elect86/jogl-samples/blob/master/jogl-samples/src/tests/gl_430/Gl_430_program_compute_variable_group_size.java) added
| 0 |
spinscale/elasticsearch-rest-client-samples | Elasticsearch REST client samples using Testcontainers | null | # Elasticsearch REST client examples
This repository shows a few examples of how to use the [Elasticsearch Java
client](https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html).
It is using Testcontainers for Elasticsearch, so you need to have Docker
up and running.
You can run the tests via `./gradlew clean check`, but I suppose just reading
the source in an IDE is more interesting.
Note: The `main` branch of this repo uses the [new Elasticsearch
Client](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html).
If you are still using the [old
one](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html)
``, simply switch to the `hlrc` branch of this repo).
| 0 |
SolaceSamples/solace-samples-jms | Getting Started Samples for the Solace JMS API. | solace solace-samples | [](https://travis-ci.org/SolaceSamples/solace-samples-jms)
# Getting Started Examples
## Solace JMS API
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 basic Solace messaging patterns. For a nice introduction to the Solace API and associated tutorials, check out the [Getting Started Home Page](https://dev.solace.com/samples/solace-samples-jms/).
See the individual tutorials for details:
- [Publish/Subscribe](https://tutorials.solace.dev/jms/publish-subscribe/): Learn how to set up pub/sub messaging on a Solace VMR.
- [Persistence](https://tutorials.solace.dev/jms/persistence-with-queues/): Learn how to set up persistence for guaranteed delivery.
- [Request/Reply](https://tutorials.solace.dev/jms/request-reply/): Learn how to set up request/reply messaging.
- [Confirmed Delivery](https://tutorials.solace.dev/jms/confirmed-delivery/): Learn how to confirm that your messages are received by a Solace message router.
- [Topic to Queue Mapping](https://tutorials.solace.dev/jms/topic-to-queue-mapping/): Learn how to map existing topics to Solace queues.
- [Obtaining JMS objects using JNDI](https://tutorials.solace.dev/jms/using-jndi/): Learn how to use JNDI as a way to create JMS objects.
- [Obtaining JMS objects using external service JNDI](https://tutorials.solace.dev/jms/using-external-jndi/): Learn how to use external JNDI service as a way to create JMS objects.
## Prerequisites
This tutorial requires the Solace JMS API library. There are multiple options for getting the Solace JMS API.
### Option 1: Download the JMS API library
Download from [here](https://solace.com/downloads/?fwp_downloads=solace-apis). The JMS API is distributed as a zip file containing the required jars, API documentation, and examples.
### Option 2: Using it with Gradle
`implementation("com.solacesystems:sol-jms:10.10.0")`
or `implementation group: 'com.solacesystems', name: 'sol-jms', version: '10.10.0'`
### Option 3: Using it with Maven
```
<dependency>
<groupId>com.solacesystems</groupId>
<artifactId>sol-jms</artifactId>
<version>10.10.0</version>
</dependency>
```
## Build the Samples
Just clone and build. For example:
1. clone this GitHub repository
1. `./gradlew assemble`
## Running the Samples
To try individual samples, build the project from source and then run samples like the following:
./build/staged/bin/topicPublisher <msg_backbone_ip:port>
The individual tutorials linked above provide full details which can walk you through the samples, what they do, and how to correctly run them to explore Solace messaging.
## 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-jms'* 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-jms/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:
- The Solace Developer Portal website at: https://solace.dev
- Ask the https://solace.community
- Solace API Tutorials @ https://tutorials.solace.dev
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.