full_name
stringlengths
7
70
description
stringlengths
4
590
created_at
stringlengths
20
20
last_commit
float64
readme
stringlengths
14
559k
label
int64
0
1
GoogleCloudPlatform/DataflowTemplates
Cloud Dataflow Google-provided templates for solving in-Cloud data tasks
2018-02-10T00:31:37Z
null
# Google Cloud Dataflow Template Pipelines These Dataflow templates are an effort to solve simple, but large, in-Cloud data tasks, including data import/export/backup/restore and bulk API operations, without a development environment. The technology under the hood which makes these operations possible is the [Google Cloud Dataflow](https://cloud.google.com/dataflow/) service combined with a set of [Apache Beam](https://beam.apache.org/) SDK templated pipelines. Google is providing this collection of pre-implemented Dataflow templates as a reference and to provide easy customization for developers wanting to extend their functionality. [![Open in Cloud Shell](http://gstatic.com/cloudssh/images/open-btn.svg)](https://console.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2FGoogleCloudPlatform%2FDataflowTemplates.git) ## Note on Default Branch As of November 18, 2021, our default branch is now named "main". This does not affect forks. If you would like your fork and its local clone to reflect these changes you can follow [GitHub's branch renaming guide](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-branches-in-your-repository/renaming-a-branch). ## Template Pipelines - Get Started - [Word Count](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Word_Count&type=code) - Process Data Continuously (stream) - [Azure Eventhub to Pubsub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Azure_Eventhub_to_PubSub&type=code) - [Bigtable Change Streams to HBase Replicator](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Bigtable_Change_Streams_to_HBase&type=code) - [Cloud Bigtable change streams to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Bigtable_Change_Streams_to_BigQuery&type=code) - [Cloud Bigtable change streams to Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Bigtable_Change_Streams_to_Google_Cloud_Storage&type=code) - [Cloud Spanner change streams to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Spanner_Change_Streams_to_BigQuery&type=code) - [Cloud Spanner change streams to Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Spanner_Change_Streams_to_Google_Cloud_Storage&type=code) - [Cloud Spanner change streams to Pub/Sub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Spanner_Change_Streams_to_PubSub&type=code) - [Cloud Storage Text to BigQuery (Stream)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Stream_GCS_Text_to_BigQuery_Flex&type=code) - [Data Masking/Tokenization from Cloud Storage to BigQuery (using Cloud DLP)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Stream_DLP_GCS_Text_to_BigQuery_Flex&type=code) - [Datastream to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Datastream_to_BigQuery&type=code) - [Datastream to Cloud Spanner](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Datastream_to_Spanner&type=code) - [Datastream to SQL](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Datastream_to_SQL&type=code) - [JMS to Pubsub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Jms_to_PubSub&type=code) - [Kafka to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Kafka_to_BigQuery&type=code) - [Kafka to Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Kafka_to_GCS&type=code) - [Kinesis To Pubsub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Kinesis_To_Pubsub&type=code) - [MongoDB to BigQuery (CDC)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20MongoDB_to_BigQuery_CDC&type=code) - [Mqtt to Pubsub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Mqtt_to_PubSub&type=code) - [Ordered change stream buffer to Source DB](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Ordered_Changestream_Buffer_to_Sourcedb&type=code) - [Pub/Sub Avro to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_Avro_to_BigQuery&type=code) - [Pub/Sub CDC to Bigquery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_CDC_to_BigQuery&type=code) - [Pub/Sub Proto to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_Proto_to_BigQuery&type=code) - [Pub/Sub Subscription or Topic to Text Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_GCS_Text_Flex&type=code) - [Pub/Sub Subscription to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_to_BigQuery_Flex&type=code) - [Pub/Sub Topic to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_to_BigQuery&type=code) - [Pub/Sub to Avro Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_Avro_Flex&type=code) - [Pub/Sub to Datadog](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_Datadog&type=code) - [Pub/Sub to Elasticsearch](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_to_Elasticsearch&type=code) - [Pub/Sub to JDBC](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Pubsub_to_Jdbc&type=code) - [Pub/Sub to Kafka](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PubSub_to_Kafka&type=code) - [Pub/Sub to MongoDB](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_MongoDB&type=code) - [Pub/Sub to Pub/Sub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_Cloud_PubSub&type=code) - [Pub/Sub to Redis](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_Redis&type=code) - [Pub/Sub to Splunk](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_Splunk&type=code) - [Pub/Sub to Text Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_PubSub_to_GCS_Text&type=code) - [Pubsub to JMS](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Pubsub_to_Jms&type=code) - [Spanner Change Streams to Sink](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Spanner_Change_Streams_to_Sink&type=code) - [Synchronizing CDC data to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cdc_To_BigQuery_Template&type=code) - [Text Files on Cloud Storage to Pub/Sub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Stream_GCS_Text_to_Cloud_PubSub&type=code) - Process Data in Bulk (batch) - [AstraDB to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20AstraDB_To_BigQuery&type=code) - [Avro Files on Cloud Storage to Cloud Bigtable](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Avro_to_Cloud_Bigtable&type=code) - [Avro Files on Cloud Storage to Cloud Spanner](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Avro_to_Cloud_Spanner&type=code) - [BigQuery export to Parquet (via Storage API)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20BigQuery_to_Parquet&type=code) - [BigQuery to Bigtable](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20BigQuery_to_Bigtable&type=code) - [BigQuery to Datastore](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_BigQuery_to_Cloud_Datastore&type=code) - [BigQuery to Elasticsearch](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20BigQuery_to_Elasticsearch&type=code) - [BigQuery to MongoDB](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20BigQuery_to_MongoDB&type=code) - [BigQuery to TensorFlow Records](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_BigQuery_to_GCS_TensorFlow_Records&type=code) - [Cassandra to Cloud Bigtable](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cassandra_To_Cloud_Bigtable&type=code) - [Cloud Bigtable to Avro Files in Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Bigtable_to_GCS_Avro&type=code) - [Cloud Bigtable to Parquet Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Bigtable_to_GCS_Parquet&type=code) - [Cloud Bigtable to SequenceFile Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Bigtable_to_GCS_SequenceFile&type=code) - [Cloud Spanner to Avro Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Cloud_Spanner_to_GCS_Avro&type=code) - [Cloud Spanner to Text Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Spanner_to_GCS_Text&type=code) - [Cloud Storage To Splunk](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_To_Splunk&type=code) - [Cloud Storage to Elasticsearch](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_to_Elasticsearch&type=code) - [Dataplex JDBC Ingestion](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Dataplex_JDBC_Ingestion&type=code) - [Dataplex: Convert Cloud Storage File Format](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Dataplex_File_Format_Conversion&type=code) - [Dataplex: Tier Data from BigQuery to Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Dataplex_BigQuery_to_GCS&type=code) - [Firestore (Datastore mode) to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Firestore_to_BigQuery_Flex&type=code) - [Firestore (Datastore mode) to Text Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Firestore_to_GCS_Text&type=code) - [Google Ads to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Google_Ads_to_BigQuery&type=code) - [Google Cloud to Neo4j](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Google_Cloud_to_Neo4j&type=code) - [JDBC to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Jdbc_to_BigQuery&type=code) - [JDBC to BigQuery with BigQuery Storage API support](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Jdbc_to_BigQuery_Flex&type=code) - [JDBC to Pub/Sub](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Jdbc_to_PubSub&type=code) - [MongoDB to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20MongoDB_to_BigQuery&type=code) - [MySQL to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20MySQL_to_BigQuery&type=code) - [Parquet Files on Cloud Storage to Cloud Bigtable](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Parquet_to_Cloud_Bigtable&type=code) - [PostgreSQL to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20PostgreSQL_to_BigQuery&type=code) - [SQLServer to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20SQLServer_to_BigQuery&type=code) - [SequenceFile Files on Cloud Storage to Cloud Bigtable](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_SequenceFile_to_Cloud_Bigtable&type=code) - [Text Files on Cloud Storage to BigQuery](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Text_to_BigQuery&type=code) - [Text Files on Cloud Storage to BigQuery with BigQuery Storage API support](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Text_to_BigQuery_Flex&type=code) - [Text Files on Cloud Storage to Cloud Spanner](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Text_to_Cloud_Spanner&type=code) - [Text Files on Cloud Storage to Firestore (Datastore mode)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Text_to_Firestore&type=code) - Utilities - [Bulk Compress Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Bulk_Compress_GCS_Files&type=code) - [Bulk Decompress Files on Cloud Storage](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Bulk_Decompress_GCS_Files&type=code) - [Bulk Delete Entities in Firestore (Datastore mode)](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Firestore_to_Firestore_Delete&type=code) - [Convert file formats between Avro, Parquet & CSV](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20File_Format_Conversion&type=code) - [Streaming Data Generator](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Streaming_Data_Generator&type=code) - Legacy Templates - [Bulk Delete Entities in Datastore [Deprecated]](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Datastore_to_Datastore_Delete&type=code) - [Datastore to Text Files on Cloud Storage [Deprecated]](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20Datastore_to_GCS_Text&type=code) - [Text Files on Cloud Storage to Datastore [Deprecated]](https://github.com/search?q=repo%3AGoogleCloudPlatform%2FDataflowTemplates%20GCS_Text_to_Datastore&type=code) For documentation on each template's usage and parameters, please see the official [docs](https://cloud.google.com/dataflow/docs/templates/provided-templates). ## Contributing To contribute to the repository, see [CONTRIBUTING.md](./CONTRIBUTING.md). ## Release Process Templates are released in a weekly basis (best-effort) as part of the efforts to keep [Google-provided Templates](https://cloud.google.com/dataflow/docs/guides/templates/provided-templates) updated with latest fixes and improvements. To learn more about this process, or how you can stage your own changes, see [Release Process](./release-process.md). ## More Information * [Dataflow](https://cloud.google.com/dataflow/docs/overview) - general Dataflow documentation. * [Dataflow Templates](https://cloud.google.com/dataflow/docs/concepts/dataflow-templates) - basic template concepts. * [Google-provided Templates](https://cloud.google.com/dataflow/docs/guides/templates/provided-templates) - official documentation for templates provided by Google (the source code is in this repository). * Dataflow Cookbook: [Blog](https://cloud.google.com/blog/products/data-analytics/introducing-dataflow-cookbook), [GitHub Repository](https://github.com/GoogleCloudPlatform/dataflow-cookbook) - pipeline examples and practical solutions to common data processing challenges. * [Dataflow Metrics Collector](https://github.com/GoogleCloudPlatform/dataflow-metrics-exporter) - CLI tool to collect dataflow resource & execution metrics and export to either BigQuery or Google Cloud Storage. Useful for comparison and visualization of the metrics while benchmarking the dataflow pipelines using various data formats, resource configurations etc * [Apache Beam](https://beam.apache.org) - [Overview](https://beam.apache.org/use/beam-overview/) - Quickstart: [Java](https://beam.apache.org/get-started/quickstart-java), [Python](https://beam.apache.org/get-started/quickstart-py), [Go](https://beam.apache.org/get-started/quickstart-go) - [Tour of Beam](https://tour.beam.apache.org/) - an interactive tour with learning topics covering core Beam concepts from simple ones to more advanced ones. - [Beam Playground](https://beam.apache.org/get-started/try-beam-playground/) - an interactive environment to try out Beam transforms and examples without having to install Apache Beam. - [Beam College](https://beamcollege.dev/) - hands-on training and practical tips, including video recordings of Apache Beam and Dataflow Templates lessons. - [Getting Started with Apache Beam - Quest](https://www.cloudskillsboost.google/quests/310) - A 5 lab series that provides a Google Cloud certified badge upon completion.
0
apache/parquet-mr
Apache Parquet
2014-06-10T07:00:07Z
null
<!-- ~ 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. --> Parquet MR [![Build Status](https://github.com/apache/parquet-mr/workflows/Test/badge.svg)](https://github.com/apache/parquet-mr/actions) ====== Parquet-MR contains the java implementation of the [Parquet format](https://github.com/apache/parquet-format). Parquet is a columnar storage format for Hadoop; it provides efficient storage and encoding of data. Parquet uses the [record shredding and assembly algorithm](https://github.com/julienledem/redelm/wiki/The-striping-and-assembly-algorithms-from-the-Dremel-paper) described in the Dremel paper to represent nested structures. You can find some details about the format and intended use cases in our [Hadoop Summit 2013 presentation](http://www.slideshare.net/julienledem/parquet-hadoop-summit-2013) ## Building Parquet-MR uses Maven to build and depends on the thrift compiler (protoc is now managed by maven plugin). ### Install Thrift To build and install the thrift compiler, run: ``` wget -nv http://archive.apache.org/dist/thrift/0.20.0/thrift-0.20.0.tar.gz tar xzf thrift-0.20.0.tar.gz cd thrift-0.20.0 chmod +x ./configure ./configure --disable-libs sudo make install -j ``` If you're on OSX and use homebrew, you can instead install Thrift 0.20.0 with `brew` and ensure that it comes first in your `PATH`. ``` brew install thrift export PATH="/usr/local/opt/thrift@0.20.0/bin:$PATH" ``` ### Build Parquet with Maven Once protobuf and thrift are available in your path, you can build the project by running: ``` LC_ALL=C mvn clean install ``` ## Features Parquet is a very active project, and new features are being added quickly. Here are a few features: * Type-specific encoding * Hive integration (deprecated) * Pig integration * Cascading integration (deprecated) * Crunch integration * Apache Arrow integration * Scrooge integration (deprecated) * Impala integration (non-nested) * Java Map/Reduce API * Native Avro support * Native Thrift support * Native Protocol Buffers support * Complex structure support * Run-length encoding (RLE) * Bit Packing * Adaptive dictionary encoding * Predicate pushdown * Column stats * Delta encoding * Index pages * Java Vector API support (experimental) ## Java Vector API support `The feature is experimental and is currently not part of the parquet distribution`. Parquet-MR has supported Java Vector API to speed up reading, to enable this feature: * Java 17+, 64-bit * Requiring the CPU to support instruction sets: * avx512vbmi * avx512_vbmi2 * To build the jars: `mvn clean package -P vector-plugins` * For Apache Spark to enable this feature: * Build parquet and replace the parquet-encoding-{VERSION}.jar on the spark jars folder * Build parquet-encoding-vector and copy parquet-encoding-vector-{VERSION}.jar to the spark jars folder * Edit spark class#VectorizedRleValuesReader, function#readNextGroup refer to parquet class#ParquetReadRouter, function#readBatchUsing512Vector * Build spark with maven and replace spark-sql_2.12-{VERSION}.jar on the spark jars folder ## Map/Reduce integration [Input](https://github.com/apache/parquet-mr/blob/master/parquet-hadoop/src/main/java/org/apache/parquet/hadoop/ParquetInputFormat.java) and [Output](https://github.com/apache/parquet-mr/blob/master/parquet-hadoop/src/main/java/org/apache/parquet/hadoop/ParquetOutputFormat.java) formats. Note that to use an Input or Output format, you need to implement a WriteSupport or ReadSupport class, which will implement the conversion of your object to and from a Parquet schema. We've implemented this for 2 popular data formats to provide a clean migration path as well: ### Thrift Thrift integration is provided by the [parquet-thrift](https://github.com/apache/parquet-mr/tree/master/parquet-thrift) sub-project. ### Avro Avro conversion is implemented via the [parquet-avro](https://github.com/apache/parquet-mr/tree/master/parquet-avro) sub-project. ### Protobuf Protobuf conversion is implemented via the [parquet-protobuf](https://github.com/apache/parquet-mr/tree/master/parquet-protobuf) sub-project. ### Create your own objects * The ParquetOutputFormat can be provided a WriteSupport to write your own objects to an event based RecordConsumer. * the ParquetInputFormat can be provided a ReadSupport to materialize your own objects by implementing a RecordMaterializer See the APIs: * [Record conversion API](https://github.com/apache/parquet-mr/tree/master/parquet-column/src/main/java/org/apache/parquet/io/api) * [Hadoop API](https://github.com/apache/parquet-mr/tree/master/parquet-hadoop/src/main/java/org/apache/parquet/hadoop/api) ## Apache Pig integration A [Loader](https://github.com/apache/parquet-mr/blob/master/parquet-pig/src/main/java/org/apache/parquet/pig/ParquetLoader.java) and a [Storer](https://github.com/apache/parquet-mr/blob/master/parquet-pig/src/main/java/org/apache/parquet/pig/ParquetStorer.java) are provided to read and write Parquet files with Apache Pig Storing data into Parquet in Pig is simple: ``` -- options you might want to fiddle with SET parquet.page.size 1048576 -- default. this is your min read/write unit. SET parquet.block.size 134217728 -- default. your memory budget for buffering data SET parquet.compression lzo -- or you can use none, gzip, snappy STORE mydata into '/some/path' USING parquet.pig.ParquetStorer; ``` Reading in Pig is also simple: ``` mydata = LOAD '/some/path' USING parquet.pig.ParquetLoader(); ``` If the data was stored using Pig, things will "just work". If the data was stored using another method, you will need to provide the Pig schema equivalent to the data you stored (you can also write the schema to the file footer while writing it -- but that's pretty advanced). We will provide a basic automatic schema conversion soon. ## Hive integration Hive integration is provided via the [parquet-hive](https://github.com/apache/parquet-mr/tree/master/parquet-hive) sub-project. Hive integration is now deprecated within the Parquet project. It is now maintained by Apache Hive. ## Build To run the unit tests: `mvn test` To build the jars: `mvn package` The build runs in [GitHub Actions](https://github.com/apache/parquet-mr/actions): [![Build Status](https://github.com/apache/parquet-mr/workflows/Test/badge.svg)](https://github.com/apache/parquet-mr/actions) ## Add Parquet as a dependency in Maven The current release is version `1.13.0` ```xml <dependencies> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-common</artifactId> <version>1.13.0</version> </dependency> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-encoding</artifactId> <version>1.13.0</version> </dependency> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-column</artifactId> <version>1.13.0</version> </dependency> <dependency> <groupId>org.apache.parquet</groupId> <artifactId>parquet-hadoop</artifactId> <version>1.13.0</version> </dependency> </dependencies> ``` ### How To Contribute We prefer to receive contributions in the form of GitHub pull requests. Please send pull requests against the [parquet-mr](https://github.com/apache/parquet-mr) Git repository. If you've previously forked Parquet from its old location, you will need to add a remote or update your origin remote to https://github.com/apache/parquet-mr.git If you are looking for some ideas on what to contribute, check out jira issues for this project labeled ["pick-me-up"](https://issues.apache.org/jira/browse/PARQUET-5?jql=project%20%3D%20PARQUET%20and%20labels%20%3D%20pick-me-up%20and%20status%20%3D%20open). Comment on the issue and/or contact [dev@parquet.apache.org](http://mail-archives.apache.org/mod_mbox/parquet-dev/) with your questions and ideas. If you’d like to report a bug but don’t have time to fix it, you can still post it to our [issue tracker](https://issues.apache.org/jira/browse/PARQUET), or email the mailing list [dev@parquet.apache.org](http://mail-archives.apache.org/mod_mbox/parquet-dev/) To contribute a patch: 1. Break your work into small, single-purpose patches if possible. It’s much harder to merge in a large change with a lot of disjoint features. 2. Create a JIRA for your patch on the [Parquet Project JIRA](https://issues.apache.org/jira/browse/PARQUET). 3. Submit the patch as a GitHub pull request against the master branch. For a tutorial, see the GitHub guides on forking a repo and sending a pull request. Prefix your pull request name with the JIRA name (ex: https://github.com/apache/parquet-mr/pull/240). 4. Make sure that your code passes the unit tests. You can run the tests with `mvn test` in the root directory. 5. Add new unit tests for your code. We tend to do fairly close readings of pull requests, and you may get a lot of comments. Some common issues that are not code structure related, but still important: * Use 2 spaces for whitespace. Not tabs, not 4 spaces. The number of the spacing shall be 2. * Give your operators some room. Not `a+b` but `a + b` and not `foo(int a,int b)` but `foo(int a, int b)`. * Generally speaking, stick to the [Sun Java Code Conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html) * Make sure tests pass! Thank you for getting involved! ## Authors and contributors * [Contributors](https://github.com/apache/parquet-mr/graphs/contributors) * [Committers](dev/COMMITTERS.md) ## Code of Conduct We hold ourselves and the Parquet developer community to two codes of conduct: 1. [The Apache Software Foundation Code of Conduct](https://www.apache.org/foundation/policies/conduct.html) 2. [The Twitter OSS Code of Conduct](https://github.com/twitter/code-of-conduct/blob/master/code-of-conduct.md) ## Discussions * Mailing list: [dev@parquet.apache.org](http://mail-archives.apache.org/mod_mbox/parquet-dev/) * Bug tracker: [jira](https://issues.apache.org/jira/browse/PARQUET) * Discussions also take place in github pull requests ## License Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
0
apache/dubbo-spring-boot-project
Spring Boot Project for Apache Dubbo
2018-01-18T12:10:50Z
null
# Apache Dubbo Spring Boot Project ## This repo has been archived. All of the implements have been moved to [apache/dubbo](https://github.com/apache/dubbo). [![Build Status](https://travis-ci.org/apache/dubbo-spring-boot-project.svg?branch=master)](https://travis-ci.org/apache/dubbo-spring-boot-project) [![codecov](https://codecov.io/gh/apache/dubbo-spring-boot-project/branch/master/graph/badge.svg)](https://codecov.io/gh/apache/dubbo-spring-boot-project) ![license](https://img.shields.io/github/license/apache/dubbo-spring-boot-project.svg) [Apache Dubbo](https://github.com/apache/dubbo) Spring Boot Project makes it easy to create [Spring Boot](https://github.com/spring-projects/spring-boot/) application using Dubbo as RPC Framework. What's more, it also provides: * [auto-configure features](dubbo-spring-boot-autoconfigure) (e.g., annotation-driven, auto configuration, externalized configuration). * [production-ready features](dubbo-spring-boot-actuator) (e.g., security, health checks, externalized configuration). > Apache Dubbo |ˈdʌbəʊ| is a high-performance, light weight, java based RPC framework. Dubbo offers three key functionalities, which include interface based remote call, fault tolerance & load balancing, and automatic service registration & discovery. ## [中文说明](README_CN.md) ## Released version You can introduce the latest `dubbo-spring-boot-starter` to your project by adding the following dependency to your pom.xml ```xml <properties> <spring-boot.version>2.3.0.RELEASE</spring-boot.version> <dubbo.version>2.7.8</dubbo.version> </properties> <dependencyManagement> <dependencies> <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!-- Apache Dubbo --> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-dependencies-bom</artifactId> <version>${dubbo.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <!-- Dubbo Spring Boot Starter --> <dependency> <groupId>org.apache.dubbo</groupId> <artifactId>dubbo-spring-boot-starter</artifactId> <version>2.7.8</version> </dependency> </dependencies> ``` If your project failed to resolve the dependency, try to add the following repository: ```xml <repositories> <repository> <id>apache.snapshots.https</id> <name>Apache Development Snapshot Repository</name> <url>https://repository.apache.org/content/repositories/snapshots</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> ``` ### Legacy Versions If you still use the legacy Dubbo whose version is less than 2.7.0, please use the following Spring Boot starters: | Dubbo Spring Boot | Dubbo | Spring Boot | | ----------------- | ------ | ----------- | | [0.2.1.RELEASE](https://github.com/apache/dubbo-spring-boot-project/tree/0.2.x) | 2.6.5+ | 2.x | | [0.1.2.RELEASE](https://github.com/apache/dubbo-spring-boot-project/tree/0.1.x) | 2.6.5+ | 1.x | ### Build from Source If you'd like to attempt to experience the latest features, you also can build from the source code as follow: 1. Maven install current project in your local repository. > Maven install = `mvn install` ## Getting Started If you don't know about Dubbo, please take a few minutes to learn http://dubbo.apache.org/. After that you could dive deep into dubbo [user guide](http://dubbo.apache.org/en-us/docs/user/quick-start.html). Usually, There are two usage scenarios for Dubbo applications, one is Dubbo service(s) provider, another is Dubbo service(s) consumer, thus let's get a quick start on them. First of all, we suppose an interface as Dubbo RPC API that a service provider exports and a service client consumes: ```java public interface DemoService { String sayHello(String name); } ``` ### Dubbo service(s) provider 1. Service Provider implements `DemoService` ```java @DubboService(version = "1.0.0") public class DefaultDemoService implements DemoService { /** * The default value of ${dubbo.application.name} is ${spring.application.name} */ @Value("${dubbo.application.name}") private String serviceName; public String sayHello(String name) { return String.format("[%s] : Hello, %s", serviceName, name); } } ``` 2. Provides a bootstrap class ```java @EnableAutoConfiguration public class DubboProviderDemo { public static void main(String[] args) { SpringApplication.run(DubboProviderDemo.class,args); } } ``` 3. Configures the `application.properties`: ```properties # Spring boot application spring.application.name=dubbo-auto-configuration-provider-demo # Base packages to scan Dubbo Component: @org.apache.dubbo.config.annotation.Service dubbo.scan.base-packages=org.apache.dubbo.spring.boot.sample.provider.service # Dubbo Application ## The default value of dubbo.application.name is ${spring.application.name} ## dubbo.application.name=${spring.application.name} # Dubbo Protocol dubbo.protocol.name=dubbo dubbo.protocol.port=12345 ## Dubbo Registry dubbo.registry.address=N/A ``` ### Dubbo service(s) consumer 1. Service consumer also provides a bootstrap class to reference `DemoService` ```java @EnableAutoConfiguration public class DubboAutoConfigurationConsumerBootstrap { private final Logger logger = LoggerFactory.getLogger(getClass()); @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:12345") private DemoService demoService; public static void main(String[] args) { SpringApplication.run(DubboAutoConfigurationConsumerBootstrap.class).close(); } @Bean public ApplicationRunner runner() { return args -> { logger.info(demoService.sayHello("mercyblitz")); }; } } ``` 2. configures `application.yml` ```yaml spring: application: name: dubbo-auto-configure-consumer-sample ``` If `DubboProviderDemo` works well, please make sure `DubboProviderDemo` is started. More details, please refer to [Samples](dubbo-spring-boot-samples). ## Getting help Having trouble with Dubbo Spring Boot? We’d like to help! - If you are upgrading, read the [release notes](https://github.com/apache/dubbo-spring-boot-project/releases) for upgrade instructions and "new and noteworthy" features. - Ask a question - You can subscribe [Dubbo User Mailling List](mailto:dubbo+subscribe@googlegroups.com). - Report bugs at [github.com/apache/dubbo-spring-boot-project/issues](https://github.com/apache/dubbo-spring-boot-project/issues). ## Building from Source If you want to try out the latest features of Dubbo Spring Boot, it can be easily built with the [maven wrapper](https://github.com/takari/maven-wrapper). Your JDK is 1.8 or above. ``` $ ./mvnw clean install ``` ## Modules There are some modules in Apache Dubbo Spring Boot Project, let's take a look at below overview: ### [dubbo-spring-boot-parent](dubbo-spring-boot-parent) The main usage of `dubbo-spring-boot-parent` is providing dependencies management for other modules. ### [dubbo-spring-boot-autoconfigure](dubbo-spring-boot-autoconfigure) `dubbo-spring-boot-autoconfigure` uses Spring Boot's `@EnableAutoConfiguration` which helps core Dubbo's components to be auto-configured by `DubboAutoConfiguration`. It reduces code, eliminates XML configuration. ### [dubbo-spring-boot-actuator](dubbo-spring-boot-actuator) `dubbo-spring-boot-actuator` provides production-ready features (e.g., [health checks](https://github.com/apache/dubbo-spring-boot-project/tree/master/dubbo-spring-boot-actuator#health-checks), [endpoints](https://github.com/apache/dubbo-spring-boot-project/tree/master/dubbo-spring-boot-actuator#endpoints), and [externalized configuration](https://github.com/apache/dubbo-spring-boot-project/tree/master/dubbo-spring-boot-actuator#externalized-configuration)). ### [dubbo-spring-boot-starter](dubbo-spring-boot-starter) `dubbo-spring-boot-starter` is a standard Spring Boot Starter, which contains [dubbo-spring-boot-autoconfigure](dubbo-spring-boot-autoconfigure) and [dubbo-spring-boot-actuator](dubbo-spring-boot-actuator). It will be imported into your application directly. ### [dubbo-spring-boot-samples](dubbo-spring-boot-samples) The samples project of Dubbo Spring Boot that includes: - [Auto-Configuaration Samples](dubbo-spring-boot-samples/auto-configure-samples) - [Externalized Configuration Samples](dubbo-spring-boot-samples/externalized-configuration-samples) - [Registry Zookeeper Samples](https://github.com/apache/dubbo-spring-boot-project/tree/master/dubbo-spring-boot-samples/registry-samples/zookeeper-samples) - [Registry Nacos Samples](https://github.com/apache/dubbo-spring-boot-project/tree/master/dubbo-spring-boot-samples/registry-samples/nacos-samples) ## License Apache Dubbo spring boot project is under the Apache 2.0 license. See the [LICENSE](https://github.com/apache/dubbo-spring-boot-project/blob/master/LICENSE) file for details.
0
winterbe/java8-tutorial
Modern Java - A Guide to Java 8
2014-03-16T17:25:43Z
null
# Modern Java - A Guide to Java 8 _This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/)._ > **You should also read my [Java 11 Tutorial](https://winterbe.com/posts/2018/09/24/java-11-tutorial/) (including new language and API features from Java 9, 10 and 11).** Welcome to my introduction to [Java 8](https://jdk8.java.net/). This tutorial guides you step by step through all new language features. Backed by short and simple code samples you'll learn how to use default interface methods, lambda expressions, method references and repeatable annotations. At the end of the article you'll be familiar with the most recent [API](http://download.java.net/jdk8/docs/api/) changes like streams, functional interfaces, map extensions and the new Date API. **No walls of text, just a bunch of commented code snippets. Enjoy!** --- <p align="center"> ★★★ Like this project? Leave a star, <a href="https://twitter.com/winterbe_">follow on Twitter</a> or <a href="https://www.paypal.me/winterbe">donate</a> to support my work. Thanks! ★★★ </p> --- ## Table of Contents * [Default Methods for Interfaces](#default-methods-for-interfaces) * [Lambda expressions](#lambda-expressions) * [Functional Interfaces](#functional-interfaces) * [Method and Constructor References](#method-and-constructor-references) * [Lambda Scopes](#lambda-scopes) * [Accessing local variables](#accessing-local-variables) * [Accessing fields and static variables](#accessing-fields-and-static-variables) * [Accessing Default Interface Methods](#accessing-default-interface-methods) * [Built-in Functional Interfaces](#built-in-functional-interfaces) * [Predicates](#predicates) * [Functions](#functions) * [Suppliers](#suppliers) * [Consumers](#consumers) * [Comparators](#comparators) * [Optionals](#optionals) * [Streams](#streams) * [Filter](#filter) * [Sorted](#sorted) * [Map](#map) * [Match](#match) * [Count](#count) * [Reduce](#reduce) * [Parallel Streams](#parallel-streams) * [Sequential Sort](#sequential-sort) * [Parallel Sort](#parallel-sort) * [Maps](#maps) * [Date API](#date-api) * [Clock](#clock) * [Timezones](#timezones) * [LocalTime](#localtime) * [LocalDate](#localdate) * [LocalDateTime](#localdatetime) * [Annotations](#annotations) * [Where to go from here?](#where-to-go-from-here) ## Default Methods for Interfaces Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the `default` keyword. This feature is also known as [virtual extension methods](http://stackoverflow.com/a/24102730). Here is our first example: ```java interface Formula { double calculate(int a); default double sqrt(int a) { return Math.sqrt(a); } } ``` Besides the abstract method `calculate` the interface `Formula` also defines the default method `sqrt`. Concrete classes only have to implement the abstract method `calculate`. The default method `sqrt` can be used out of the box. ```java Formula formula = new Formula() { @Override public double calculate(int a) { return sqrt(a * 100); } }; formula.calculate(100); // 100.0 formula.sqrt(16); // 4.0 ``` The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation of `sqrt(a * 100)`. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8. ## Lambda expressions Let's start with a simple example of how to sort a list of strings in prior versions of Java: ```java List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } }); ``` The static utility method `Collections.sort` accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method. Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, **lambda expressions**: ```java Collections.sort(names, (String a, String b) -> { return b.compareTo(a); }); ``` As you can see the code is much shorter and easier to read. But it gets even shorter: ```java Collections.sort(names, (String a, String b) -> b.compareTo(a)); ``` For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even shorter: ```java names.sort((a, b) -> b.compareTo(a)); ``` List now has a `sort` method. Also the java compiler is aware of the parameter types so you can skip them as well. Let's dive deeper into how lambda expressions can be used in the wild. ## Functional Interfaces How does lambda expressions fit into Java's type system? Each lambda corresponds to a given type, specified by an interface. A so called _functional interface_ must contain **exactly one abstract method** declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface. We can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method. To ensure that your interface meet the requirements, you should add the `@FunctionalInterface` annotation. The compiler is aware of this annotation and throws a compiler error as soon as you try to add a second abstract method declaration to the interface. Example: ```java @FunctionalInterface interface Converter<F, T> { T convert(F from); } ``` ```java Converter<String, Integer> converter = (from) -> Integer.valueOf(from); Integer converted = converter.convert("123"); System.out.println(converted); // 123 ``` Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be omitted. ## Method and Constructor References The above example code can be further simplified by utilizing static method references: ```java Converter<String, Integer> converter = Integer::valueOf; Integer converted = converter.convert("123"); System.out.println(converted); // 123 ``` Java 8 enables you to pass references of methods or constructors via the `::` keyword. The above example shows how to reference a static method. But we can also reference object methods: ```java class Something { String startsWith(String s) { return String.valueOf(s.charAt(0)); } } ``` ```java Something something = new Something(); Converter<String, String> converter = something::startsWith; String converted = converter.convert("Java"); System.out.println(converted); // "J" ``` Let's see how the `::` keyword works for constructors. First we define an example class with different constructors: ```java class Person { String firstName; String lastName; Person() {} Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } } ``` Next we specify a person factory interface to be used for creating new persons: ```java interface PersonFactory<P extends Person> { P create(String firstName, String lastName); } ``` Instead of implementing the factory manually, we glue everything together via constructor references: ```java PersonFactory<Person> personFactory = Person::new; Person person = personFactory.create("Peter", "Parker"); ``` We create a reference to the Person constructor via `Person::new`. The Java compiler automatically chooses the right constructor by matching the signature of `PersonFactory.create`. ## Lambda Scopes Accessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables. ### Accessing local variables We can read final local variables from the outer scope of lambda expressions: ```java final int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3 ``` But different to anonymous objects the variable `num` does not have to be declared final. This code is also valid: ```java int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); stringConverter.convert(2); // 3 ``` However `num` must be implicitly final for the code to compile. The following code does **not** compile: ```java int num = 1; Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num); num = 3; ``` Writing to `num` from within the lambda expression is also prohibited. ### Accessing fields and static variables In contrast to local variables, we have both read and write access to instance fields and static variables from within lambda expressions. This behaviour is well known from anonymous objects. ```java class Lambda4 { static int outerStaticNum; int outerNum; void testScopes() { Converter<Integer, String> stringConverter1 = (from) -> { outerNum = 23; return String.valueOf(from); }; Converter<Integer, String> stringConverter2 = (from) -> { outerStaticNum = 72; return String.valueOf(from); }; } } ``` ### Accessing Default Interface Methods Remember the formula example from the first section? Interface `Formula` defines a default method `sqrt` which can be accessed from each formula instance including anonymous objects. This does not work with lambda expressions. Default methods **cannot** be accessed from within lambda expressions. The following code does not compile: ```java Formula formula = (a) -> sqrt(a * 100); ``` ## Built-in Functional Interfaces The JDK 1.8 API contains many built-in functional interfaces. Some of them are well known from older versions of Java like `Comparator` or `Runnable`. Those existing interfaces are extended to enable Lambda support via the `@FunctionalInterface` annotation. But the Java 8 API is also full of new functional interfaces to make your life easier. Some of those new interfaces are well known from the [Google Guava](https://code.google.com/p/guava-libraries/) library. Even if you're familiar with this library you should keep a close eye on how those interfaces are extended by some useful method extensions. ### Predicates Predicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate) ```java Predicate<String> predicate = (s) -> s.length() > 0; predicate.test("foo"); // true predicate.negate().test("foo"); // false Predicate<Boolean> nonNull = Objects::nonNull; Predicate<Boolean> isNull = Objects::isNull; Predicate<String> isEmpty = String::isEmpty; Predicate<String> isNotEmpty = isEmpty.negate(); ``` ### Functions Functions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen). ```java Function<String, Integer> toInteger = Integer::valueOf; Function<String, String> backToString = toInteger.andThen(String::valueOf); backToString.apply("123"); // "123" ``` ### Suppliers Suppliers produce a result of a given generic type. Unlike Functions, Suppliers don't accept arguments. ```java Supplier<Person> personSupplier = Person::new; personSupplier.get(); // new Person ``` ### Consumers Consumers represent operations to be performed on a single input argument. ```java Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName); greeter.accept(new Person("Luke", "Skywalker")); ``` ### Comparators Comparators are well known from older versions of Java. Java 8 adds various default methods to the interface. ```java Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0 ``` ## Optionals Optionals are not functional interfaces, but nifty utilities to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work. Optional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning `null` you return an `Optional` in Java 8. ```java Optional<String> optional = Optional.of("bam"); optional.isPresent(); // true optional.get(); // "bam" optional.orElse("fallback"); // "bam" optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" ``` ## Streams A `java.util.Stream` represents a sequence of elements on which one or more operations can be performed. Stream operations are either _intermediate_ or _terminal_. While terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a `java.util.Collection` like lists or sets (maps are not supported). Stream operations can either be executed sequentially or parallely. > Streams are extremely powerful, so I wrote a separate [Java 8 Streams Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/). **You should also check out [Sequency](https://github.com/winterbe/sequency) as a similiar library for the web.** Let's first look how sequential streams work. First we create a sample source in form of a list of strings: ```java List<String> stringCollection = new ArrayList<>(); stringCollection.add("ddd2"); stringCollection.add("aaa2"); stringCollection.add("bbb1"); stringCollection.add("aaa1"); stringCollection.add("bbb3"); stringCollection.add("ccc"); stringCollection.add("bbb2"); stringCollection.add("ddd1"); ``` Collections in Java 8 are extended so you can simply create streams either by calling `Collection.stream()` or `Collection.parallelStream()`. The following sections explain the most common stream operations. ### Filter Filter accepts a predicate to filter all elements of the stream. This operation is _intermediate_ which enables us to call another stream operation (`forEach`) on the result. ForEach accepts a consumer to be executed for each element in the filtered stream. ForEach is a terminal operation. It's `void`, so we cannot call another stream operation. ```java stringCollection .stream() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa2", "aaa1" ``` ### Sorted Sorted is an _intermediate_ operation which returns a sorted view of the stream. The elements are sorted in natural order unless you pass a custom `Comparator`. ```java stringCollection .stream() .sorted() .filter((s) -> s.startsWith("a")) .forEach(System.out::println); // "aaa1", "aaa2" ``` Keep in mind that `sorted` does only create a sorted view of the stream without manipulating the ordering of the backed collection. The ordering of `stringCollection` is untouched: ```java System.out.println(stringCollection); // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1 ``` ### Map The _intermediate_ operation `map` converts each element into another object via the given function. The following example converts each string into an upper-cased string. But you can also use `map` to transform each object into another type. The generic type of the resulting stream depends on the generic type of the function you pass to `map`. ```java stringCollection .stream() .map(String::toUpperCase) .sorted((a, b) -> b.compareTo(a)) .forEach(System.out::println); // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1" ``` ### Match Various matching operations can be used to check whether a certain predicate matches the stream. All of those operations are _terminal_ and return a boolean result. ```java boolean anyStartsWithA = stringCollection .stream() .anyMatch((s) -> s.startsWith("a")); System.out.println(anyStartsWithA); // true boolean allStartsWithA = stringCollection .stream() .allMatch((s) -> s.startsWith("a")); System.out.println(allStartsWithA); // false boolean noneStartsWithZ = stringCollection .stream() .noneMatch((s) -> s.startsWith("z")); System.out.println(noneStartsWithZ); // true ``` #### Count Count is a _terminal_ operation returning the number of elements in the stream as a `long`. ```java long startsWithB = stringCollection .stream() .filter((s) -> s.startsWith("b")) .count(); System.out.println(startsWithB); // 3 ``` ### Reduce This _terminal_ operation performs a reduction on the elements of the stream with the given function. The result is an `Optional` holding the reduced value. ```java Optional<String> reduced = stringCollection .stream() .sorted() .reduce((s1, s2) -> s1 + "#" + s2); reduced.ifPresent(System.out::println); // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" ``` ## Parallel Streams As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrently on multiple threads. The following example demonstrates how easy it is to increase the performance by using parallel streams. First we create a large list of unique elements: ```java int max = 1000000; List<String> values = new ArrayList<>(max); for (int i = 0; i < max; i++) { UUID uuid = UUID.randomUUID(); values.add(uuid.toString()); } ``` Now we measure the time it takes to sort a stream of this collection. ### Sequential Sort ```java long t0 = System.nanoTime(); long count = values.stream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("sequential sort took: %d ms", millis)); // sequential sort took: 899 ms ``` ### Parallel Sort ```java long t0 = System.nanoTime(); long count = values.parallelStream().sorted().count(); System.out.println(count); long t1 = System.nanoTime(); long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); System.out.println(String.format("parallel sort took: %d ms", millis)); // parallel sort took: 472 ms ``` As you can see both code snippets are almost identical but the parallel sort is roughly 50% faster. All you have to do is change `stream()` to `parallelStream()`. ## Maps As already mentioned maps do not directly support streams. There's no `stream()` method available on the `Map` interface itself, however you can create specialized streams upon the keys, values or entries of a map via `map.keySet().stream()`, `map.values().stream()` and `map.entrySet().stream()`. Furthermore maps support various new and useful methods for doing common tasks. ```java Map<Integer, String> map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.putIfAbsent(i, "val" + i); } map.forEach((id, val) -> System.out.println(val)); ``` The above code should be self-explaining: `putIfAbsent` prevents us from writing additional if null checks; `forEach` accepts a consumer to perform operations for each value of the map. This example shows how to compute code on the map by utilizing functions: ```java map.computeIfPresent(3, (num, val) -> val + num); map.get(3); // val33 map.computeIfPresent(9, (num, val) -> null); map.containsKey(9); // false map.computeIfAbsent(23, num -> "val" + num); map.containsKey(23); // true map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33 ``` Next, we learn how to remove entries for a given key, only if it's currently mapped to a given value: ```java map.remove(3, "val3"); map.get(3); // val33 map.remove(3, "val33"); map.get(3); // null ``` Another helpful method: ```java map.getOrDefault(42, "not found"); // not found ``` Merging entries of a map is quite easy: ```java map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); map.get(9); // val9 map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); map.get(9); // val9concat ``` Merge either put the key/value into the map if no entry for the key exists, or the merging function will be called to change the existing value. ## Date API Java 8 contains a brand new date and time API under the package `java.time`. The new Date API is comparable with the [Joda-Time](http://www.joda.org/joda-time/) library, however it's [not the same](http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html). The following examples cover the most important parts of this new API. ### Clock Clock provides access to the current date and time. Clocks are aware of a timezone and may be used instead of `System.currentTimeMillis()` to retrieve the current time in milliseconds since Unix EPOCH. Such an instantaneous point on the time-line is also represented by the class `Instant`. Instants can be used to create legacy `java.util.Date` objects. ```java Clock clock = Clock.systemDefaultZone(); long millis = clock.millis(); Instant instant = clock.instant(); Date legacyDate = Date.from(instant); // legacy java.util.Date ``` ### Timezones Timezones are represented by a `ZoneId`. They can easily be accessed via static factory methods. Timezones define the offsets which are important to convert between instants and local dates and times. ```java System.out.println(ZoneId.getAvailableZoneIds()); // prints all available timezone ids ZoneId zone1 = ZoneId.of("Europe/Berlin"); ZoneId zone2 = ZoneId.of("Brazil/East"); System.out.println(zone1.getRules()); System.out.println(zone2.getRules()); // ZoneRules[currentStandardOffset=+01:00] // ZoneRules[currentStandardOffset=-03:00] ``` ### LocalTime LocalTime represents a time without a timezone, e.g. 10pm or 17:30:15. The following example creates two local times for the timezones defined above. Then we compare both times and calculate the difference in hours and minutes between both times. ```java LocalTime now1 = LocalTime.now(zone1); LocalTime now2 = LocalTime.now(zone2); System.out.println(now1.isBefore(now2)); // false long hoursBetween = ChronoUnit.HOURS.between(now1, now2); long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); // -239 ``` LocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings. ```java LocalTime late = LocalTime.of(23, 59, 59); System.out.println(late); // 23:59:59 DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.SHORT) .withLocale(Locale.GERMAN); LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); System.out.println(leetTime); // 13:37 ``` ### LocalDate LocalDate represents a distinct date, e.g. 2014-03-11. It's immutable and works exactly analog to LocalTime. The sample demonstrates how to calculate new dates by adding or subtracting days, months or years. Keep in mind that each manipulation returns a new instance. ```java LocalDate today = LocalDate.now(); LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); LocalDate yesterday = tomorrow.minusDays(2); LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); System.out.println(dayOfWeek); // FRIDAY ``` Parsing a LocalDate from a string is just as simple as parsing a LocalTime: ```java DateTimeFormatter germanFormatter = DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.GERMAN); LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); System.out.println(xmas); // 2014-12-24 ``` ### LocalDateTime LocalDateTime represents a date-time. It combines date and time as seen in the above sections into one instance. `LocalDateTime` is immutable and works similar to LocalTime and LocalDate. We can utilize methods for retrieving certain fields from a date-time: ```java LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); System.out.println(dayOfWeek); // WEDNESDAY Month month = sylvester.getMonth(); System.out.println(month); // DECEMBER long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); System.out.println(minuteOfDay); // 1439 ``` With the additional information of a timezone it can be converted to an instant. Instants can easily be converted to legacy dates of type `java.util.Date`. ```java Instant instant = sylvester .atZone(ZoneId.systemDefault()) .toInstant(); Date legacyDate = Date.from(instant); System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 ``` Formatting date-times works just like formatting dates or times. Instead of using pre-defined formats we can create formatters from custom patterns. ```java DateTimeFormatter formatter = DateTimeFormatter .ofPattern("MMM dd, yyyy - HH:mm"); LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); String string = formatter.format(parsed); System.out.println(string); // Nov 03, 2014 - 07:13 ``` Unlike `java.text.NumberFormat` the new `DateTimeFormatter` is immutable and **thread-safe**. For details on the pattern syntax read [here](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). ## Annotations Annotations in Java 8 are repeatable. Let's dive directly into an example to figure that out. First, we define a wrapper annotation which holds an array of the actual annotations: ```java @interface Hints { Hint[] value(); } @Repeatable(Hints.class) @interface Hint { String value(); } ``` Java 8 enables us to use multiple annotations of the same type by declaring the annotation `@Repeatable`. ### Variant 1: Using the container annotation (old school) ```java @Hints({@Hint("hint1"), @Hint("hint2")}) class Person {} ``` ### Variant 2: Using repeatable annotations (new school) ```java @Hint("hint1") @Hint("hint2") class Person {} ``` Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation information via reflection. ```java Hint hint = Person.class.getAnnotation(Hint.class); System.out.println(hint); // null Hints hints1 = Person.class.getAnnotation(Hints.class); System.out.println(hints1.value().length); // 2 Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); System.out.println(hints2.length); // 2 ``` Although we never declared the `@Hints` annotation on the `Person` class, it's still readable via `getAnnotation(Hints.class)`. However, the more convenient method is `getAnnotationsByType` which grants direct access to all annotated `@Hint` annotations. Furthermore the usage of annotations in Java 8 is expanded to two new targets: ```java @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) @interface MyAnnotation {} ``` ## Where to go from here? My programming guide to Java 8 ends here. If you want to learn more about all the new classes and features of the JDK 8 API, check out my [JDK8 API Explorer](http://winterbe.com/projects/java8-explorer/). It helps you figuring out all the new classes and hidden gems of JDK 8, like `Arrays.parallelSort`, `StampedLock` and `CompletableFuture` - just to name a few. I've also published a bunch of follow-up articles on my [blog](http://winterbe.com) that might be interesting to you: - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) - [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) - [Java 8 Concurrency Tutorial: Threads and Executors](http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/) - [Java 8 Concurrency Tutorial: Synchronization and Locks](http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/) - [Java 8 Concurrency Tutorial: Atomic Variables and ConcurrentMap](http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/) - [Java 8 API by Example: Strings, Numbers, Math and Files](http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/) - [Avoid Null Checks in Java 8](http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/) - [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/) - [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/) You should [follow me on Twitter](https://twitter.com/winterbe_). Thanks for reading!
1
davinci1012/pinduoduo_backdoor_unpacker
Samples and Unpacker of malicious backdoors and exploits developed and used by Pinduoduo
2023-03-10T14:25:33Z
null
# 详细分析报告 Detailed Analysis Report English version see [Report](https://github.com/davincifans101/pinduoduo_backdoor_detailed_report/blob/main/report_en.pdf), 中文分析报告见[分析报告](https://github.com/davincifans101/pinduoduo_backdoor_detailed_report/blob/main/report_cn.pdf) # Pinduoduo恶意代码样本和脱壳机 听说PDD今天开始发律师函删帖抵赖了![PDDNB](https://user-images.githubusercontent.com/25000885/224233765-5195f16a-f41c-482f-a664-1cf72796651e.png),那就放点新东西出来。 拼多多的两个壳,manwe和nvwa脱壳脚本。适用于样本中.mw1 .nw0文件。.nw0要用nvwa脱壳脚本,.mw1用manwe脚本。 ## 拼多多manwe一键脱壳脚本 代码在`manwe_unpacker`目录,用法如下,或自己改路径: /tmp/mw1.bin放解压出来的文件,在`/tmp/final_java/`会生成脱壳后的java class文件,压缩一下拖到jadx里看。 ```java public class ManweVmpLoader { public static void main(String[] args) throws Throwable { String firmwarePath = "/tmp/mw1.bin"; ManweVmpDataInputStream inputStream = new ManweVmpDataInputStream(Files.newInputStream(Paths.get(firmwarePath))); ManweVmpDex manweVmpDex = new ManweVmpDex(inputStream); System.out.printf("Load %d class%n", manweVmpDex.manweVmpClazzes.length); if (inputStream.available() != 0) { throw new RuntimeException(String.format("%d bytes remaining", inputStream.available())); } inputStream.close(); if (Files.notExists(Paths.get("/tmp/final_java/"))) { new File("/tmp/final_java/").mkdirs(); } manweVmpDex.writeClazzes("/tmp/final_java/"); } } ``` ## 拼多多nvwa一键脱壳脚本 代码见`nvwa_unpacker`目录 ## 提取出的恶意样本 PDD的恶意代码以加壳后的文件形式组织,APK自带AliveBaseAbility,其他的都是远程下发,以下称为“样本”。因为有些样本是动态下发,不一定全,如果有这里没有的,欢迎Pull Request补充。 样本在samples目录中,包含PDD APK自带的样本,以及其动态下发的样本。动态样本为3.2日之前从安装了PDD的手机里/data/data/com.xunmeng.pinduoduo/files/bot/, /data/data/com.xunmeng.pinduoduo/files/.components/提取出,现在新版本可能被PDD删掉了,有兴趣的可以找下装了之前的版本的手机看下,顺便看下`app_mango`目录,里面是配置文件,有惊喜。 带符号的样本为PDD 6.2.0提取出(`samples/old_alive_base_ability_with_symbol/mw1.bin`),新版本的APP携带的样本去掉了符号。 样本各个都是干货,值得看看。AliveBaseAbility是第一步,davinci仓库中提到的dex只是这个evil plan的第三步,这里其他的是第二步。 ## 其他 一视同仁,平等对待才是好的营商环境,纵容、包庇不是。 据说PDD搞这个的100多号人的团队连夜解散了,删库跑路,是吗?又听说PDD这些漏洞手段被曝光停了之后,DAU出现明显下跌,是吗? 等下,有人敲门说查水表了,我先出 ## 免责声明 仅用于研究用途,禁止和PDD一样作恶,没靠山别学
1
junit-team/junit5
✅ The 5th major version of the programmer-friendly testing framework for Java and the JVM
2015-01-11T19:06:10Z
null
# <img src="https://junit.org/junit5/assets/img/junit5-logo.png" align="right" width="100">JUnit 5 This repository is the home of _JUnit 5_. ## Sponsors [![Support JUnit](https://img.shields.io/badge/%F0%9F%92%9A-Support%20JUnit-brightgreen.svg)](https://junit.org/sponsoring) * **Gold Sponsors:** [JetBrains](https://jb.gg/junit-logo) * **Silver Sponsors:** [Micromata](https://www.micromata.de), [Quo Card](https://quo-digital.jp) * **Bronze Sponsors:** [Premium Minds](https://www.premium-minds.com), [Testmo](https://www.testmo.com), [codefortynine](https://codefortynine.com), [Info Support](https://www.infosupport.com), [Stiltsoft](https://stiltsoft.com), [Code Intelligence](https://www.code-intelligence.com) ## Latest Releases - General Availability (GA): [JUnit 5.10.2](https://github.com/junit-team/junit5/releases/tag/r5.10.2) (February 4, 2024) - Preview (Milestone/Release Candidate): [JUnit 5.11.0-M1](https://github.com/junit-team/junit5/releases/tag/r5.11.0-M1) (April 23, 2024) ## Documentation - [User Guide] - [Javadoc] - [Release Notes] - [Samples] ## Contributing Contributions to JUnit 5 are both welcomed and appreciated. For specific guidelines regarding contributions, please see [CONTRIBUTING.md] in the root directory of the project. Those willing to use milestone or SNAPSHOT releases are encouraged to file feature requests and bug reports using the project's [issue tracker](https://github.com/junit-team/junit5/issues). Issues marked with an <a href="https://github.com/junit-team/junit5/issues?q=is%3Aissue+is%3Aopen+label%3Aup-for-grabs">`up-for-grabs`</a> label are specifically targeted for community contributions. ## Getting Help Ask JUnit 5 related questions on [StackOverflow] or chat with the community on [Gitter]. ## Continuous Integration Builds [![CI Status](https://github.com/junit-team/junit5/workflows/CI/badge.svg)](https://github.com/junit-team/junit5/actions) [![Cross-Version Status](https://github.com/junit-team/junit5/workflows/Cross-Version/badge.svg)](https://github.com/junit-team/junit5/actions) Official CI build server for JUnit 5. Used to perform quick checks on submitted pull requests and for build matrices including the latest released OpenJDK and early access builds of the next OpenJDK. ## Code Coverage Code coverage using [JaCoCo] for the latest build is available on [Codecov]. A code coverage report can also be generated locally via the [Gradle Wrapper] by executing `./gradlew -Ptesting.enableJaCoCo clean jacocoRootReport`. The results will be available in `build/reports/jacoco/jacocoRootReport/html/index.html`. ## Develocity [![Revved up by Develocity](https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.junit.org/scans) JUnit 5 utilizes [Develocity](https://gradle.com/) for [Build Scans](https://scans.gradle.com/), [Build Cache](https://docs.gradle.org/current/userguide/build_cache.html), and [Predictive Test Selection](https://docs.gradle.com/enterprise/predictive-test-selection/). The latest Build Scans are available on [ge.junit.org](https://ge.junit.org/). Currently, only core team members can publish Build Scans on that server. You can, however, publish a Build Scan to [scans.gradle.com](https://scans.gradle.com/) by using the `--scan` parameter explicitly. The remote Build Cache is enabled by default for everyone so that local builds can reuse task outputs from previous CI builds. ## Building from Source You need [JDK 21] to build JUnit 5. [Gradle toolchains] are used to detect and potentially download additional JDKs for compilation and test execution. All modules can be _built_ and _tested_ with the [Gradle Wrapper] using the following command. `./gradlew build` ## Installing in Local Maven Repository All modules can be _installed_ with the [Gradle Wrapper] in a local Maven repository for consumption in other projects via the following command. `./gradlew publishToMavenLocal` ## Dependency Metadata [![JUnit Jupiter version](https://img.shields.io/maven-central/v/org.junit.jupiter/junit-jupiter/5..svg?color=25a162&label=Jupiter)](https://central.sonatype.com/search?namespace=org.junit.jupiter) [![JUnit Vintage version](https://img.shields.io/maven-central/v/org.junit.vintage/junit-vintage-engine/5..svg?color=25a162&label=Vintage)](https://central.sonatype.com/search?namespace=org.junit.vintage) [![JUnit Platform version](https://img.shields.io/maven-central/v/org.junit.platform/junit-platform-commons/1..svg?color=25a162&label=Platform)](https://central.sonatype.com/search?namespace=org.junit.platform) Consult the [Dependency Metadata] section of the [User Guide] for a list of all artifacts of the JUnit Platform, JUnit Jupiter, and JUnit Vintage. See also <https://repo1.maven.org/maven2/org/junit/> for releases and <https://oss.sonatype.org/content/repositories/snapshots/org/junit/> for snapshots. [Codecov]: https://codecov.io/gh/junit-team/junit5 [CONTRIBUTING.md]: https://github.com/junit-team/junit5/blob/HEAD/CONTRIBUTING.md [Dependency Metadata]: https://junit.org/junit5/docs/current/user-guide/#dependency-metadata [Gitter]: https://gitter.im/junit-team/junit5 [Gradle toolchains]: https://docs.gradle.org/current/userguide/toolchains.html [Gradle Wrapper]: https://docs.gradle.org/current/userguide/gradle_wrapper.html#sec:using_wrapper [JaCoCo]: https://www.eclemma.org/jacoco/ [Javadoc]: https://junit.org/junit5/docs/current/api/ [JDK 21]: https://javaalmanac.io/jdk/21/ [Release Notes]: https://junit.org/junit5/docs/current/release-notes/ [Samples]: https://github.com/junit-team/junit5-samples [StackOverflow]: https://stackoverflow.com/questions/tagged/junit5 [User Guide]: https://junit.org/junit5/docs/current/user-guide/
0
gz-yami/mall4cloud
⭐️⭐️⭐️微服务商城系统 springcloud微服务商城 小程序商城
2021-08-04T03:04:36Z
null
![输入图片说明](doc/img/readme/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20211203094919.png) 一个基于Spring Cloud、Nacos、Seata、Mysql、Redis、RocketMQ、canal、ElasticSearch、minio的微服务B2B2C电商商城系统,采用主流的互联网技术架构、全新的UI设计、支持集群部署、服务注册和发现以及拥有完整的订单流程等,代码完全开源,没有任何二次封装,是一个非常适合二次开发的电商平台系统。 ## Spring以及VUE官方宣布,SpringBoot2与Vue2已在2023年底停止维护。新项目建议使用SpringBoot3+Vue3的组合,本商城已完成升级!!! ## 前言 本商城致力于为中大型企业打造一个功能完整、易于维护的微服务B2B2C电商商城系统,采用主流微服务技术实现。后台管理系统包含平台管理,店铺管理、商品管理、订单管理、规格管理、权限管理、资源管理等模块。 ## 文档 这代码有没有文档呀? 当然有啦,你已经下载了,在doc这个文件夹上,实在不知道,我就给链接出来咯: gitee:https://gitee.com/gz-yami/mall4cloud/tree/master/doc **开发环境搭建视频(推荐先看下文档再看视频):https://www.bilibili.com/video/BV1TK411C7aV** 有声音了。如果视频对你有用,记得点赞投币噢。 本项目是一个极度遵守阿里巴巴代码规约的项目,以下是代码规约扫描结果 ![阿里代码规约扫描结果](doc/img/readme/阿里代码规约扫描结果.png) 具体目录结构和代码规范,可以查看 https://gitee.com/gz-yami/mall4cloud/tree/master/doc/%E4%BB%A3%E7%A0%81%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84 ## 授权 除开源版本外,本商城还提供商业版本的商城,欲知详情,请访问官网。 商城官网:https://www.mall4j.com 商城使用 AGPLv3 开源,请遵守 AGPLv3 的相关条款,或者联系作者获取商业授权(https://www.mall4j.com) ## 项目链接 JAVA后台:https://gitee.com/gz-yami/mall4cloud 平台端:https://gitee.com/gz-yami/mall4cloud-platform 商家端:https://gitee.com/gz-yami/mall4cloud-multishop uni-app:https://gitee.com/gz-yami/mall4cloud-uniapp ## 演示地址 商业版演示地址: pc端:https://cloud-pc.mall4j.com H5端:https://h5.mall4j.com/cloud 商业版小程序演示 ![输入图片说明](doc/img/readme/%E7%99%BD%E6%B4%9E%E7%89%88%E5%B0%8F%E7%A8%8B%E5%BA%8F.png) ## 目录结构规范 我们也有自己的目录结构 ![img](./doc/img/%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84%E5%92%8C%E8%A7%84%E8%8C%83/%E5%BA%94%E7%94%A8%E5%88%86%E5%B1%82.png) - VO(View Object):显示层对象,通常是 Web 向模板渲染引擎层传输的对象。 - DTO(Data Transfer Object):数据传输对象,前端像后台进行传输的对象,类似于param。 - BO(Business Object):业务对象,内部业务对象,只在内部传递,不对外进行传递。 - Model:模型层,此对象与数据库表结构一一对应,通过 Mapper 层向上传输数据源对象。 - Controller:主要是对外部访问控制进行转发,各类基本参数校验,或者不复用的业务简单处理等。为了简单起见,一些与事务无关的代码也在这里编写。 - FeignClient:由于微服务之间存在互相调用,这里是内部请求的接口。 - Controller:主要是对内部访问控制进行转发,各类基本参数校验,或者不复用的业务简单处理等。为了简单起见,一些与事务无关的代码也在这里编写。 - Service 层:相对具体的业务逻辑服务层。 - Manager 层:通用业务处理层,它有如下特征: - 1) 对第三方平台封装的层,预处理返回结果及转化异常信息,适配上层接口。 - 2) 对 Service 层通用能力的下沉,如缓存方案、中间件通用处理。 - 3) 与 DAO 层交互,对多个 DAO 的组合复用。 - Mapper持久层:数据访问层,与底层 MySQL进行数据交互。 - Listener:监听 `RocketMQ` 进行处理,有时候会监听`easyexcel`相关数据。 关于`FeignClient`,由于微服务之间存在互相调用,`Feign` 是http协议,理论上是为了解耦,而实际上提供方接口进行修改,调用方却没有进行修改的时候,会造成异常,所以我们抽取出来。还有就是对内暴露的接口,是很多地方都公用的,所以我们还将接口抽取了出了一个模块,方便引用。可以看到`mall4cloud-api`这个模块下是所有对内`feign`接口的信息。 ## 目录结构 ``` mall4cloud ├─mall4cloud-api -- 内网接口 │ ├─mall4cloud-api-auth -- 授权对内接口 │ ├─mall4cloud-api-biz -- biz对内接口 │ ├─mall4cloud-api-leaf -- 美团分布式id生成接口 │ ├─mall4cloud-api-multishop -- 店铺对内接口 │ ├─mall4cloud-api-order -- 订单对内接口 │ ├─mall4cloud-api-platform -- 平台对内接口 │ ├─mall4cloud-api-product -- 商品对内接口 │ ├─mall4cloud-api-rbac -- 用户角色权限对内接口 │ ├─mall4cloud-api-search -- 搜索对内接口 │ └─mall4cloud-api-user -- 用户对内接口 ├─mall4cloud-auth -- 授权校验模块 ├─mall4cloud-biz -- mall4cloud 业务代码。如图片上传/短信等 ├─mall4cloud-common -- 一些公共的方法 │ ├─mall4cloud-common-cache -- 缓存相关公共代码 │ ├─mall4cloud-common-core -- 公共模块核心(公共中的公共代码) │ ├─mall4cloud-common-database -- 数据库连接相关公共代码 │ ├─mall4cloud-common-order -- 订单相关公共代码 │ ├─mall4cloud-common-product -- 商品相关公共代码 │ ├─mall4cloud-common-rocketmq -- rocketmq相关公共代码 │ └─mall4cloud-common-security -- 安全相关公共代码 ├─mall4cloud-gateway -- 网关 ├─mall4cloud-leaf -- 基于美团leaf的生成id服务 ├─mall4cloud-multishop -- 商家端 ├─mall4cloud-order -- 订单服务 ├─mall4cloud-payment -- 支付服务 ├─mall4cloud-platform -- 平台端 ├─mall4cloud-product -- 商品服务 ├─mall4cloud-rbac -- 用户角色权限模块 ├─mall4cloud-search -- 搜索模块 └─mall4cloud-user -- 用户服务 ``` ## 技术选型 ![技术框架](doc/img/readme/技术框架.png) ## 系统架构图 ![架构图](doc/img/readme/架构图.png) ## 商城部署后 API 地址 | 服务 | 地址 | | ---------------------------------------------------- |-----------------------| | mall4cloud-gatway 网关服务 | http://127.0.0.1:8000 | | mall4cloud-auth 授权校验服务 | http://127.0.0.1:9101 | | mall4cloud-biz 业务代码服务(如图片上传/短信等) | http://127.0.0.1:9000 | | mall4cloud-leaf 基于美团leaf的生成id服务 | http://127.0.0.1:9100 | | mall4cloud-multishop 商家服务 | http://127.0.0.1:9103 | | mall4cloud-order 订单服务 | http://127.0.0.1:9106 | | mall4cloud-payment 支付服务 | http://127.0.0.1:9113 | | mall4cloud-product 商品服务 | http://127.0.0.1:9114 | | mall4cloud-rbac 用户角色服务 | http://127.0.0.1:9102 | | mall4cloud-search 搜索服务 | http://127.0.0.1:9108 | | mall4cloud-user 用户服务 | http://127.0.0.1:9105 | ## 部署教程 部署教程请参考该文件夹下的`/基本开发文档/mall4cloud开发环境搭建.md`以及`/开发环境搭建`目录下的中间件安装。 ## 代码运行相关截图 ### 1.后台截图 - 平台端 ![](doc/img/readme/image-20231130110607548.png) - 商家端 ![image-20210705151729559](doc/img/readme/image-20231130112350296.png) ![image-20210705151847270](doc/img/readme/image-20231130112429089.png) ### 2.小程序截图 ![小程序-1625472143277](doc/img/readme/小程序.png) ### 3.uni-app截图 ![uniapp-1625469707350](doc/img/readme/uniapp.png) ## 提交反馈 - Mall4j官网 https://www.mall4j.com - mall4cloud开源技术QQ群:561496886 - 如需购买商业版源码,请联系商务微信 ![输入图片说明](https://19838323.s21i.faiusr.com/4/4/ABUIABAEGAAgksmNlAYojomK2gIwrAI4rAI!160x160.png) ## springboot版本商城请点击 https://gitee.com/gz-yami/mall4j ## 你的点赞鼓励,是我们前进的动力~ ## 你的点赞鼓励,是我们前进的动力~ ## 你的点赞鼓励,是我们前进的动力~ ## 更多信息请查看官网 https://www.mall4j.com
0
apple/pkl
A configuration as code language with rich validation and tooling.
2024-01-19T17:28:45Z
null
null
0
confluentinc/ksql
The database purpose-built for stream processing applications.
2016-09-27T21:30:15Z
null
# ![KSQL rocket](ksql-rocket.png) ksqlDB ### The database purpose-built for stream processing applications # Overview ksqlDB is a database for building stream processing applications on top of Apache Kafka. It is **distributed**, **scalable**, **reliable**, and **real-time**. ksqlDB combines the power of real-time stream processing with the approachable feel of a relational database through a familiar, lightweight SQL syntax. ksqlDB offers these core primitives: * **[Streams](https://docs.ksqldb.io/en/latest/concepts/collections/streams/) and [tables](https://docs.ksqldb.io/en/latest/concepts/collections/tables/)** - Create relations with schemas over your Apache Kafka topic data * **[Materialized views](https://docs.ksqldb.io/en/latest/concepts/materialized-views/)** - Define real-time, incrementally updated materialized views over streams using SQL * **[Push queries](https://docs.ksqldb.io/en/latest/concepts/queries/push/)**- Continuous queries that push incremental results to clients in real time * **[Pull queries](https://docs.ksqldb.io/en/latest/concepts/queries/pull/)** - Query materialized views on demand, much like with a traditional database * **[Connect](https://docs.ksqldb.io/en/latest/concepts/connectors)** - Integrate with any [Kafka Connect](https://docs.confluent.io/current/connect/index.html) data source or sink, entirely from within ksqlDB Composing these powerful primitives enables you to build a complete streaming app with just SQL statements, minimizing complexity and operational overhead. ksqlDB supports a wide range of operations including aggregations, joins, windowing, sessionization, and much more. You can find more ksqlDB tutorials and resources [here](https://developer.confluent.io/tutorials/use-cases.html). # Getting Started * Follow the [ksqlDB quickstart](https://ksqldb.io/quickstart.html) to get started in just a few minutes. * Read through the [ksqlDB documentation](https://docs.ksqldb.io). * Take a look at some [ksqlDB use case recipes](https://developer.confluent.io/tutorials/use-cases.html) for examples of common patterns. # Documentation See the [ksqlDB documentation](https://docs.ksqldb.io/) for the latest stable release. # Use Cases and Examples ## Materialized views ksqlDB allows you to define materialized views over your streams and tables. Materialized views are defined by what is known as a "persistent query". These queries are known as persistent because they maintain their incrementally updated results using a table. ```sql CREATE TABLE hourly_metrics AS SELECT url, COUNT(*) FROM page_views WINDOW TUMBLING (SIZE 1 HOUR) GROUP BY url EMIT CHANGES; ``` Results may be **"pulled"** from materialized views on demand via `SELECT` queries. The following query will return a single row: ```sql SELECT * FROM hourly_metrics WHERE url = 'http://myurl.com' AND WINDOWSTART = '2019-11-20T19:00'; ``` Results may also be continuously **"pushed"** to clients via streaming `SELECT` queries. The following streaming query will push to the client all incremental changes made to the materialized view: ```sql SELECT * FROM hourly_metrics EMIT CHANGES; ``` Streaming queries will run perpetually until they are explicitly terminated. ## Streaming ETL Apache Kafka is a popular choice for powering data pipelines. ksqlDB makes it simple to transform data within the pipeline, readying messages to cleanly land in another system. ```sql CREATE STREAM vip_actions AS SELECT userid, page, action FROM clickstream c LEFT JOIN users u ON c.userid = u.user_id WHERE u.level = 'Platinum' EMIT CHANGES; ``` ## Anomaly Detection ksqlDB is a good fit for identifying patterns or anomalies on real-time data. By processing the stream as data arrives you can identify and properly surface out of the ordinary events with millisecond latency. ```sql CREATE TABLE possible_fraud AS SELECT card_number, count(*) FROM authorization_attempts WINDOW TUMBLING (SIZE 5 SECONDS) GROUP BY card_number HAVING count(*) > 3 EMIT CHANGES; ``` ## Monitoring Kafka's ability to provide scalable ordered records with stream processing make it a common solution for log data monitoring and alerting. ksqlDB lends a familiar syntax for tracking, understanding, and managing alerts. ```sql CREATE TABLE error_counts AS SELECT error_code, count(*) FROM monitoring_stream WINDOW TUMBLING (SIZE 1 MINUTE) WHERE type = 'ERROR' GROUP BY error_code EMIT CHANGES; ``` ## Integration with External Data Sources and Sinks ksqlDB includes native integration with [Kafka Connect](https://docs.ksqldb.io/en/latest/concepts/connectors) data sources and sinks, effectively providing a unified SQL interface over a [broad variety of external systems](https://www.confluent.io/hub). The following query is a simple persistent streaming query that will produce all of its output into a topic named `clicks_transformed`: ```sql CREATE STREAM clicks_transformed AS SELECT userid, page, action FROM clickstream c LEFT JOIN users u ON c.userid = u.user_id EMIT CHANGES; ``` Rather than simply send all continuous query output into a Kafka topic, it is often very useful to route the output into another datastore. ksqlDB's Kafka Connect integration makes this pattern very easy. The following statement will create a Kafka Connect sink connector that continuously sends all output from the above streaming ETL query directly into Elasticsearch: ```sql CREATE SINK CONNECTOR es_sink WITH ( 'connector.class' = 'io.confluent.connect.elasticsearch.ElasticsearchSinkConnector', 'key.converter' = 'org.apache.kafka.connect.storage.StringConverter', 'topics' = 'clicks_transformed', 'key.ignore' = 'true', 'schema.ignore' = 'true', 'type.name' = '', 'connection.url' = 'http://elasticsearch:9200'); ``` <a name="community"></a> # Join the Community For user help, questions or queries about ksqlDB please use our [user Google Group](https://groups.google.com/forum/#!forum/ksql-users) or our public Slack channel #ksqldb in [Confluent Community Slack](https://slackpass.io/confluentcommunity). Everyone is welcome! You can get help, learn how to contribute to ksqlDB, and find the latest news by [connecting with the Confluent community](https://www.confluent.io/contact-us-thank-you/). For more general questions about the Confluent Platform please post in the [Confluent Google group](https://groups.google.com/forum/#!forum/confluent-platform). # Contributing and building from source Contributions to the code, examples, documentation, etc. are very much appreciated. - Report issues and bugs directly in [this GitHub project](https://github.com/confluentinc/ksql/issues). - Learn how to work with the ksqlDB source code, including building and testing ksqlDB as well as contributing code changes to ksqlDB by reading our [Development and Contribution guidelines](CONTRIBUTING.md). - One good way to get started is by tackling a [newbie issue](https://github.com/confluentinc/ksql/labels/good%20first%20issue). # License The project is licensed under the [Confluent Community License](LICENSE). *Apache, Apache Kafka, Kafka, and associated open source project names are trademarks of the [Apache Software Foundation](https://www.apache.org/).*
0
SlimeKnights/TinkersConstruct
Tinker a little, build a little, tinker a little more...
2013-01-22T20:46:32Z
null
# [Tinkers' Construct](http://minecraft.curseforge.com/projects/tinkers-construct) Modify all the things, then do it again! Melt down any metals you find. Power the world with spinning wind! ### IMC Tinkers' Construct supports several IMCs to allow mods to integrate themselves. The [Wiki](https://github.com/SlimeKnights/TinkersConstruct/wiki/IMC) contains a page with further information. Anything that is not possible via IMC has to be integrated via Code through the API/library package. (old 1.7.10 IMCs can be found here: https://gist.github.com/bonii-xx/e46f9d9e81e29d796b1b) ## Setting up a Workspace/Compiling from Source Note: Git MUST be installed and in the system path to use our scripts. * Setup: Run [gradle]in the repository root: `gradlew[.bat] [setupDevWorkspace|setupDecompWorkspace] [eclipse|idea]` * Build: Run [gradle]in the repository root: `gradlew[.bat] build` * If obscure Gradle issues are found try running `gradlew clean` and `gradlew cleanCache` ## Issue reporting Please include the following: * Minecraft version * Tinkers' Construct version * Forge version/build * Versions of any mods potentially related to the issue * Any relevant screenshots are greatly appreciated. * For crashes: * Steps to reproduce * ForgeModLoader-client-0.log (the FML log) from the root folder of the client ## Licenses Code, Textures and binaries are licensed under the [MIT License](https://tldrlegal.com/license/mit-license). You are allowed to use the mod in your modpack. Any modpack which uses Tinkers' Construct takes **full** responsibility for user support queries. For anyone else, we only support official builds from the main CI server, not custom built jars. We also do not take bug reports for outdated builds of Minecraft. If you have queries about any license or the above support restrictions, please drop by our IRC channel, #TinkersConstruct on irc.esper.net Any alternate licenses are noted where appropriate. ## Jar Signing Some jars from our build servers may be signed. Under no circumstances does anyone have permission to verify the signatures on those jars from other mods. The signing is for informational purposes only.
0
baidu/uid-generator
UniqueID generator
2017-03-27T04:03:43Z
null
UidGenerator ========================== [In Chinese 中文版](README.zh_cn.md) UidGenerator is a Java implemented, [Snowflake](https://github.com/twitter/snowflake) based unique ID generator. It works as a component, and allows users to override workId bits and initialization strategy. As a result, it is much more suitable for virtualization environment, such as [docker](https://www.docker.com/). Besides these, it overcomes concurrency limitation of Snowflake algorithm by consuming future time; parallels UID produce and consume by caching UID with RingBuffer; eliminates CacheLine pseudo sharing, which comes from RingBuffer, via padding. And finally, it can offer over <font color=red>6 million</font> QPS per single instance. Requires:[Java8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)+, [MySQL](https://dev.mysql.com/downloads/mysql/)(Default implement as WorkerID assigner; If there are other implements, MySQL is not required) Snowflake ------------- ![Snowflake](doc/snowflake.png) ** Snowflake algorithm:** An unique id consists of worker node, timestamp and sequence within that timestamp. Usually, it is a 64 bits number(long), and the default bits of that three fields are as follows: * sign(1bit) The highest bit is always 0. * delta seconds (28 bits) The next 28 bits, represents delta seconds since a customer epoch(2016-05-20). The maximum time will be 8.7 years. * worker id (22 bits) The next 22 bits, represents the worker node id, maximum value will be 4.2 million. UidGenerator uses a build-in database based ```worker id assigner``` when startup by default, and it will dispose previous work node id after reboot. Other strategy such like 'reuse' is coming soon. * sequence (13 bits) the last 13 bits, represents sequence within the one second, maximum is 8192 per second by default. **The parameters above can be configured in spring bean** CachedUidGenerator ------------------- RingBuffer is an array,each item of that array is called 'slot', every slot keeps a uid or a flag(Double RingBuffer). The size of RingBuffer is 2^<sup>n</sup>, where n is positive integer and equal or greater than bits of ```sequence```. Assign bigger value to ```boostPower``` if you want to enlarge RingBuffer to improve throughput. ###### Tail & Cursor pointer * Tail Pointer Represents the latest produced UID. If it catches up with cursor, the ring buffer will be full, at that moment, no put operation should be allowed, you can specify a policy to handle it by assigning property ```rejectedPutBufferHandler```. * Cursor Pointer Represents the latest already consumed UID. If cursor catches up with tail, the ring buffer will be empty, and any take operation will be rejected. you can also specify a policy to handle it by assigning property ```rejectedTakeBufferHandler```. ![RingBuffer](doc/ringbuffer.png) CachedUidGenerator used double RingBuffer,one RingBuffer for UID, another for status(if valid for take or put) Array can improve performance of reading, due to the CUP cache mechanism. At the same time, it brought the side effect of 「False Sharing」, in order to solve it, cache line padding is applied. ![FalseSharing](doc/cacheline_padding.png) #### RingBuffer filling * Initialization padding During RingBuffer initializing,the entire RingBuffer will be filled. * In-time filling Whenever the percent of available UIDs is less than threshold ```paddingFactor```, the fill task is triggered. You can reassign that threshold in Spring bean configuration. * Periodic filling Filling periodically in a scheduled thread. The```scheduleInterval``` can be reassigned in Spring bean configuration. Quick Start ------------ Here we have a demo with 4 steps to introduce how to integrate UidGenerator into Spring based projects.<br/> ### Step 1: Install Java8, Maven, MySQL If you have already installed maven, jdk8+ and Mysql or other DB which supported by Mybatis, just skip to next.<br/> Download [Java8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html), [MySQL](https://dev.mysql.com/downloads/mysql/) and [Maven](https://maven.apache.org/download.cgi), and install jdk, mysql. For maven, extracting and setting MAVEN_HOME is enough. #### Set JAVA_HOME & MAVEN_HOME Here is a sample script to set JAVA_HOME and MAVEN_HOME ```shell export MAVEN_HOME=/xxx/xxx/software/maven/apache-maven-3.3.9 export PATH=$MAVEN_HOME/bin:$PATH JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home"; export JAVA_HOME; ``` ### Step 2: Create table WORKER_NODE Replace ```xxxxx``` with real database name, and run following script to create table, ```sql DROP DATABASE IF EXISTS `xxxx`; CREATE DATABASE `xxxx` ; use `xxxx`; DROP TABLE IF EXISTS WORKER_NODE; CREATE TABLE WORKER_NODE ( ID BIGINT NOT NULL AUTO_INCREMENT COMMENT 'auto increment id', HOST_NAME VARCHAR(64) NOT NULL COMMENT 'host name', PORT VARCHAR(64) NOT NULL COMMENT 'port', TYPE INT NOT NULL COMMENT 'node type: ACTUAL or CONTAINER', LAUNCH_DATE DATE NOT NULL COMMENT 'launch date', MODIFIED TIMESTAMP NOT NULL COMMENT 'modified time', CREATED TIMESTAMP NOT NULL COMMENT 'created time', PRIMARY KEY(ID) ) COMMENT='DB WorkerID Assigner for UID Generator',ENGINE = INNODB; ``` Reset property of 'jdbc.url', 'jdbc.username' and 'jdbc.password' in [mysql.properties](src/test/resources/uid/mysql.properties). ### Step 3: Spring configuration #### DefaultUidGenerator There are two implements of UidGenerator: [DefaultUidGenerator](src/main/java/com/baidu/fsg/uid/impl/DefaultUidGenerator.java), [CachedUidGenerator](src/main/java/com/baidu/fsg/uid/impl/CachedUidGenerator.java).<br/> For performance sensitive application, CachedUidGenerator is recommended. ```xml <!-- DefaultUidGenerator --> <bean id="defaultUidGenerator" class="com.baidu.fsg.uid.impl.DefaultUidGenerator" lazy-init="false"> <property name="workerIdAssigner" ref="disposableWorkerIdAssigner"/> <!-- Specified bits & epoch as your demand. No specified the default value will be used --> <property name="timeBits" value="29"/> <property name="workerBits" value="21"/> <property name="seqBits" value="13"/> <property name="epochStr" value="2016-09-20"/> </bean> <!-- Disposable WorkerIdAssigner based on Database --> <bean id="disposableWorkerIdAssigner" class="com.baidu.fsg.uid.worker.DisposableWorkerIdAssigner" /> ``` #### CachedUidGenerator Copy beans of CachedUidGenerator to 'test/resources/uid/cached-uid-spring.xml'. ```xml <!-- CachedUidGenerator --> <bean id="cachedUidGenerator" class="com.baidu.fsg.uid.impl.CachedUidGenerator"> <property name="workerIdAssigner" ref="disposableWorkerIdAssigner" /> <!-- The config below is option --> <!-- Specified bits & epoch as your demand. No specified the default value will be used --> <property name="timeBits" value="29"/> <property name="workerBits" value="21"/> <property name="seqBits" value="13"/> <property name="epochStr" value="2016-09-20"/> <!-- RingBuffer size, to improve the throughput. --> <!-- Default as 3. Sample: original bufferSize=8192, after boosting the new bufferSize= 8192 << 3 = 65536 --> <property name="boostPower" value="3"></property> <!-- In-time padding, available UIDs percentage(0, 100) of the RingBuffer, default as 50 --> <!-- Sample: bufferSize=1024, paddingFactor=50 -> threshold=1024 * 50 / 100 = 512. --> <!-- When the rest available UIDs < 512, RingBiffer will be padded in-time --> <property name="paddingFactor" value="50"></property> <!-- Periodic padding --> <!-- Default is disabled. Enable as below, scheduleInterval unit as Seconds. --> <property name="scheduleInterval" value="60"></property> <!-- Policy for rejecting put on RingBuffer --> <property name="rejectedPutBufferHandler" ref="XxxxYourPutRejectPolicy"></property> <!-- Policy for rejecting take from RingBuffer --> <property name="rejectedTakeBufferHandler" ref="XxxxYourTakeRejectPolicy"></property> </bean> <!-- Disposable WorkerIdAssigner based on Database --> <bean id="disposableWorkerIdAssigner" class="com.baidu.fsg.uid.worker.DisposableWorkerIdAssigner" /> <!-- Mybatis config... --> ``` #### Mybatis config [mybatis-spring.xml](src/test/resources/uid/mybatis-spring.xml) shows as below: ```xml <!-- Spring annotation scan --> <context:component-scan base-package="com.baidu.fsg.uid" /> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:/META-INF/mybatis/mapper/M_WORKER*.xml" /> </bean> <!-- transaction --> <tx:annotation-driven transaction-manager="transactionManager" order="1" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- Mybatis Mapper scan --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="annotationClass" value="org.springframework.stereotype.Repository" /> <property name="basePackage" value="com.baidu.fsg.uid.worker.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- datasource config --> <bean id="dataSource" parent="abstractDataSource"> <property name="driverClassName" value="${mysql.driver}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="abstractDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="filters" value="${datasource.filters}" /> <property name="defaultAutoCommit" value="${datasource.defaultAutoCommit}" /> <property name="initialSize" value="${datasource.initialSize}" /> <property name="minIdle" value="${datasource.minIdle}" /> <property name="maxWait" value="${datasource.maxWait}" /> <property name="testWhileIdle" value="${datasource.testWhileIdle}" /> <property name="testOnBorrow" value="${datasource.testOnBorrow}" /> <property name="testOnReturn" value="${datasource.testOnReturn}" /> <property name="validationQuery" value="${datasource.validationQuery}" /> <property name="timeBetweenEvictionRunsMillis" value="${datasource.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${datasource.minEvictableIdleTimeMillis}" /> <property name="logAbandoned" value="${datasource.logAbandoned}" /> <property name="removeAbandoned" value="${datasource.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${datasource.removeAbandonedTimeout}" /> </bean> <bean id="batchSqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <constructor-arg index="1" value="BATCH" /> </bean> ``` ### Step 4: Run UnitTest Run [CachedUidGeneratorTest](src/test/java/com/baidu/fsg/uid/CachedUidGeneratorTest.java), shows how to generate / parse UniqueID: ```java @Resource private UidGenerator uidGenerator; @Test public void testSerialGenerate() { // Generate UID long uid = uidGenerator.getUID(); // Parse UID into [Timestamp, WorkerId, Sequence] // {"UID":"180363646902239241","parsed":{ "timestamp":"2017-01-19 12:15:46", "workerId":"4", "sequence":"9" }} System.out.println(uidGenerator.parseUID(uid)); } ``` ### Tips For low concurrency and long term application, less ```seqBits``` but more ```timeBits``` is recommended. For example, if DisposableWorkerIdAssigner is adopted and the average reboot frequency is 12 per node per day, with the configuration ```{"workerBits":23,"timeBits":31,"seqBits":9}```, one project can run for 68 years with 28 nodes and entirely concurrency 14400 UID/s. For frequent reboot and long term application, less ```seqBits``` but more ```timeBits``` and ```workerBits``` is recommended. For example, if DisposableWorkerIdAssigner is adopted and the average reboot frequency is 24 * 12 per node per day, with the configuration ```{"workerBits":27,"timeBits":30,"seqBits":6}```, one project can run for 34 years with 37 nodes and entirely concurrency 2400 UID/s. #### Experiment for Throughput To figure out CachedUidGenerator's UID throughput, some experiments are carried out.<br/> Firstly, workerBits is arbitrarily fixed to 20, and change timeBits from 25(about 1 year) to 32(about 136 years),<br/> |timeBits|25|26|27|28|29|30|31|32| |:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| |throughput|6,831,465|7,007,279|6,679,625|6,499,205|6,534,971|7,617,440|6,186,930|6,364,997| ![throughput1](doc/throughput1.png) Then, timeBits is arbitrarily fixed to 31, and workerBits is changed from 20(about 1 million total reboots) to 29(about 500 million total reboots),<br/> |workerBits|20|21|22|23|24|25|26|27|28|29| |:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| |throughput|6,186,930|6,642,727|6,581,661|6,462,726|6,774,609|6,414,906|6,806,266|6,223,617|6,438,055|6,435,549| ![throughput2](doc/throughput2.png) It is obvious that whatever the configuration is, CachedUidGenerator always has the ability to provide **6 million** stable throughput, what sacrificed is just life expectancy, this is very cool. Finally, both timeBits and workerBits are fixed to 31 and 23 separately, and change the number of CachedUidGenerator consumer. Since our CPU only has 4 cores, \[1, 8\] is chosen.<br/> |consumers|1|2|3|4|5|6|7|8| |:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:| |throughput|6,462,726|6,542,259|6,077,717|6,377,958|7,002,410|6,599,113|7,360,934|6,490,969| ![throughput3](doc/throughput3.png)
0
apache/flink-cdc
Flink CDC is a streaming data integration tool
2020-07-27T19:23:33Z
null
<p align="center"> <a href="https://nightlies.apache.org/flink/flink-cdc-docs-stable/"><img src="docs/static/fig/flinkcdc-logo.png" alt="Flink CDC" style="width: 375px;"></a> </p> <p align="center"> <a href="https://github.com/apache/flink-cdc/" target="_blank"> <img src="https://img.shields.io/github/stars/apache/flink-cdc?style=social&label=Star&maxAge=2592000" alt="Test"> </a> <a href="https://github.com/apache/flink-cdc/releases" target="_blank"> <img src="https://img.shields.io/github/v/release/apache/flink-cdc?color=yellow" alt="Release"> </a> <a href="https://github.com/apache/flink-cdc/actions/workflows/flink_cdc.yml" target="_blank"> <img src="https://img.shields.io/github/actions/workflow/status/apache/flink-cdc/flink_cdc.yml?branch=master" alt="Build"> </a> <a href="https://github.com/apache/flink-cdc/tree/master/LICENSE" target="_blank"> <img src="https://img.shields.io/static/v1?label=license&message=Apache License 2.0&color=white" alt="License"> </a> </p> Flink CDC is a distributed data integration tool for real time data and batch data. Flink CDC brings the simplicity and elegance of data integration via YAML to describe the data movement and transformation in a [Data Pipeline](docs/content/docs/core-concept/data-pipeline.md). The Flink CDC prioritizes efficient end-to-end data integration and offers enhanced functionalities such as full database synchronization, sharding table synchronization, schema evolution and data transformation. ![Flink CDC framework desigin](docs/static/fig/architecture.png) ### Getting Started 1. Prepare a [Apache Flink](https://nightlies.apache.org/flink/flink-docs-master/docs/try-flink/local_installation/#starting-and-stopping-a-local-cluster) cluster and set up `FLINK_HOME` environment variable. 2. [Download](https://github.com/apache/flink-cdc/releases) Flink CDC tar, unzip it and put jars of pipeline connector to Flink `lib` directory. 3. Create a **YAML** file to describe the data source and data sink, the following example synchronizes all tables under MySQL app_db database to Doris : ```yaml source: type: mysql name: MySQL Source hostname: 127.0.0.1 port: 3306 username: admin password: pass tables: adb.\.* server-id: 5401-5404 sink: type: doris name: Doris Sink fenodes: 127.0.0.1:8030 username: root password: pass pipeline: name: MySQL to Doris Pipeline parallelism: 4 ``` 4. Submit pipeline job using `flink-cdc.sh` script. ```shell bash bin/flink-cdc.sh /path/mysql-to-doris.yaml ``` 5. View job execution status through Flink WebUI or downstream database. Try it out yourself with our more detailed [tutorial](docs/content/docs/get-started/quickstart/mysql-to-doris.md). You can also see [connector overview](docs/content/docs/connectors/pipeline-connectors/overview.md) to view a comprehensive catalog of the connectors currently provided and understand more detailed configurations. ### Join the Community There are many ways to participate in the Apache Flink CDC community. The [mailing lists](https://flink.apache.org/what-is-flink/community/#mailing-lists) are the primary place where all Flink committers are present. For user support and questions use the user mailing list. If you've found a problem of Flink CDC, please create a [Flink jira](https://issues.apache.org/jira/projects/FLINK/summary) and tag it with the `Flink CDC` tag. Bugs and feature requests can either be discussed on the dev mailing list or on Jira. ### Contributing Welcome to contribute to Flink CDC, please see our [Developer Guide](docs/content/docs/developer-guide/contribute-to-flink-cdc.md) and [APIs Guide](docs/content/docs/developer-guide/understand-flink-cdc-api.md). ### License [Apache 2.0 License](LICENSE). ### Special Thanks The Flink CDC community welcomes everyone who is willing to contribute, whether it's through submitting bug reports, enhancing the documentation, or submitting code contributions for bug fixes, test additions, or new feature development. Thanks to all contributors for their enthusiastic contributions. <a href="https://github.com/apache/flink-cdc/graphs/contributors"> <img src="https://contrib.rocks/image?repo=apache/flink-cdc"/> </a>
0
seaswalker/spring-analysis
Spring源码阅读
2016-09-09T07:46:32Z
null
# Spring Spring相关组件阅读笔记. # 传送门 - [spring-core](https://github.com/seaswalker/Spring/blob/master/note/Spring.md) - [spring-aop](https://github.com/seaswalker/Spring/blob/master/note/spring-aop.md) - [spring-context](https://github.com/seaswalker/Spring/blob/master/note/spring-context.md) - [spring-task](https://github.com/seaswalker/Spring/blob/master/note/spring-task.md) - [spring-transaction](https://github.com/seaswalker/Spring/blob/master/note/spring-transaction.md) - [spring-mvc](https://github.com/seaswalker/Spring/blob/master/note/spring-mvc.md) - [guava-cache](https://github.com/seaswalker/Spring/blob/master/note/guava-cache.md)
0
stevenhalim/cpbook-code
CP4 Free Source Code Project (C++17, Java11, Python3 and OCaml)
2018-11-27T05:30:10Z
null
# cpbook-code CP4 Free Source Code Project (cpp/gnu++17, java/java11, py/python3, and ml/ocaml). This repo is expected to be much more up-to-date than CP4 itself, that will go out to public on 19 July 2020. All code in this repo are mostly (reasonably good, hopefully :) implementation of many well-known data structures and algorithms, so you are free to copy, adapt, use the code (in your next programming contest or any other coding project). Note to Computer Science educators worldwide: please include all the code discussed here in your plagiarism checker system as "excluded". Please do NOT test your students to just (re-)code these basic data structures/algorithms verbatim as that is just reinventing the wheel. Please test them with higher order thinking questions/problems that use these code instead. We will be thankful if you cite us (Steven Halim, Felix Halim, Suhendry Effendy) when you use code in this repo. This license is probably the most suitable: https://opensource.org/licenses/UPL
0
ReChronoRain/HyperCeiler
MIUI & HyperOS enhancement module - Make MIUI & HyperOS Great Again!
2023-10-27T17:17:42Z
null
<div align="center"> <img src="/imgs/icon.png" width="160" height="160" style="display: block; margin: 0 auto;" alt="icon"> # HyperCeiler ### Make HyperOS/MIUI Great Again! 简体中文&nbsp;&nbsp;|&nbsp;&nbsp;[English](/README_en-US.md)&nbsp;&nbsp;|&nbsp;&nbsp;[Português (Brasil)](/README_pt-BR.md) </div> ## 当前支持的版本 Android 13-14 的 MIUI 和 HyperOS ## 使用前说明 请在 [LSPosed](https://github.com/LSPosed/LSPosed/releases) 中启用 HyperCeiler, 然后在 HyperCeiler 应用内启用对应的功能,重启作用域 (需要 Root 权限); 本模块<b>不支持</b> `修改较多的第三方 MIUI/Xiaomi HyperOS ROM`、`修改较多的系统软件`,以及`部分国际 MIUI/Xiaomi HyperOS ROM`; 目前 HyperCeiler 是基于 Android 14 的 Xiaomi HyperOS1.0 的手机端设备进行适配,覆盖不是很完整,需要不断测试和改进 提交反馈前请注意是否已有相同反馈,避免给开发者造成困扰。花相同精力看相同反馈是一件很浪费时间的事情 HyperCeiler 已停止维护 Android 11-12 的 MIUI ROM,如需使用请停留[此版本](https://github.com/ReChronoRain/Cemiuiler/releases/tag/1.3.130) ## 作用域包含的应用 <details> <summary>点击展开折叠的内容</summary> | 应用名 | 包名 | |:----------------------|:-----------------------------------| | 系统框架 | system | | 系统界面 | com.android.systemui | | 系统桌面 | com.miui.home | | 系统更新 | com.android.updater | | Joyose | com.xiaomi.joyose | | 小米设置 | com.xiaomi.misettings | | 安全服务 (手机管家、平板管家) | com.miui.securitycenter | | 笔记 | com.miui.notes | | 壁纸 | com.miui.miwallpaper | | 传送门 | com.miui.contentextension | | 弹幕通知 | com.xiaomi.barrage | | 电话 | com.android.incallui | | 电话服务 | com.android.phone | | 电量与性能 | com.miui.powerkeeper | | 短信 | com.android.mms | | 截屏 | com.miui.screenshot | | 日历 | com.android.calendar | | 浏览器 | com.android.browser | | 鲁班(MTB) | com.xiaomi.mtb | | 屏幕录制 | com.miui.screenrecorder | | 权限管理服务 | com.lbe.security.miui | | 设置 | com.android.settings | | 搜狗输入法小米版 | com.sohu.inputmethod.sogou.xiaomi | | 天气 | com.miui.weather2 | | 互联互通服务 (投屏) | com.milink.service | | 外部存储设备 | com.android.externalstorage | | 息屏与锁屏编辑 (万象息屏) | com.miui.aod | | 文件管理 | com.android.fileexplorer | | 系统服务组件 | com.miui.securityadd | | 下载管理 | com.android.providers.downloads.ui | | 下载管理程序 | com.android.providers.downloads | | 相册 | com.miui.gallery | | 小米创作 | com.miui.creation | | 小米互传 | com.miui.mishare.connectivity | | 小米相册 - 编辑 | com.miui.mediaeditor | | 小米云服务 | com.miui.cloudservice | | 小米智能卡 | com.miui.tsmclient | | 讯飞输入法小米版 | com.iflytek.inputmethod.miui | | 应用包管理组件 | com.miui.packageinstaller | | 应用商店 | com.xiaomi.market | | 智能助理 | com.miui.personalassistant | | 主题商店 (主题壁纸、壁纸与个性化) | com.android.thememanager | | 系统安全组件 | com.miui.guardprovider | | 相机 | com.android.camera | | 小爱翻译 | com.xiaomi.aiasst.vision | | 小爱视觉 | com.xiaomi.scanner | | 小爱同学 | com.miui.voiceassist | | NFC 服务 | com.android.nfc | | 音质音效 | com.miui.misound | | 备份 | com.miui.backup | | 小米换机 | com.miui.huanji | | MiTrustService | com.xiaomi.trustservice | </details> > 与 LSPosed 中推荐的作用域相同 ## 交流 & 反馈群组 加入我们所创建的群组以反馈问题或是了解最新情况。 [![badge_qgroup]][qgroup_url] [![badge_qguild]][qguild_url] [![badge_telegram]][telegram_url] ## 为 HyperCeiler 贡献翻译 [![Crowdin](https://badges.crowdin.net/cemiuiler/localized.svg)](https://crowdin.com/project/cemiuiler) 您可以在[这里](https://crwd.in/cemiuiler)为 HyperCeiler 项目贡献翻译。 注:当新语言翻译进度大于或等于 90% 时,将会进入合并流程,如果已添加的语言,翻译进度小于或等于源文本的 30%,将会暂时被移除,直到重新满足翻译进度大于或等于 90% ## 感谢 > HyperCeiler 使用了以下开源项目的部分或全部内容,感谢这些项目的开发者提供的大力支持(排名顺序不分先后)。 - [「Accompanist」 by Android Open Source Project, Google Inc.](https://google.github.io/accompanist) - [「Android」 by Android Open Source Project, Google Inc.](https://source.android.google.cn/license) - [「AndroidHiddenApiBypass」 by LSPosed](https://github.com/LSPosed/AndroidHiddenApiBypass) - [「AndroidX」 by Android Open Source Project, Google Inc.](https://github.com/androidx/androidx) - [「AntiAntiDefraud」 by MinaMichita](https://github.com/MinaMichita/AntiAntiDefraud) - [「Auto NFC」 by GSWXXN](https://github.com/GSWXXN/AutoNFC) - [「BypassSignCheck」 by Weverses](https://github.com/Weverses/BypassSignCheck) - [「CorePatch」 by LSPosed](https://github.com/LSPosed/CorePatch) - [「CustoMIUIzer」 by MonwF](https://github.com/MonwF/customiuizer) - [「CustoMIUIzerMod」 by liyafe1997](https://github.com/liyafe1997/CustoMIUIzerMod) - [「ClipboardList」 by 焕晨HChen](https://github.com/HChenX/ClipboardList) - [「DexKit」 by LuckyPray](https://github.com/LuckyPray/DexKit) - [「Disable app link verify」 by tehcneko](https://github.com/Xposed-Modules-Repo/io.github.tehcneko.applinkverify) - [「DisableFlagSecure」 by LSPosed](https://github.com/LSPosed/DisableFlagSecure) - [「DisableLogRequest」 by QueallyTech](https://github.com/QueallyTech/DisableLogRequest) - [「EzXHelper」 by KyuubiRan](https://github.com/KyuubiRan/EzXHelper) - [「FixMiuiMediaControlPanel」 by qqlittleice](https://github.com/qqlittleice/FixMiuiMediaControlPanel) - [「FuckNFC」 by xiaowine](https://github.com/xiaowine/FuckNFC) - [「ForegroundPin」 by 焕晨HChen](https://github.com/HChenX/ForegroundPin) - [「Gson」 by Android Open Source Project, Google Inc.](https://github.com/google/gson) - [「Hyper Helper」 by HowieHChen](https://github.com/HowieHChen/XiaomiHelper) - [「HideMiuiClipboardDialog」 by zerorooot](https://github.com/zerorooot/HideMiuiClipboardDialog) - [「HyperSmartCharge」 by buffcow](https://github.com/buffcow/HyperSmartCharge) - [「Kotlin」 by JetBrains](https://github.com/JetBrains/kotlin) - [「MaxFreeForm」 by YifePlayte](https://github.com/YifePlayte/MaxFreeForm) - [「MediaControl-BlurBg」 by YuKongA](https://github.com/YuKongA/MediaControl-BlurBg) - [「Miui Feature」 by MoralNorm](https://github.com/moralnorm/miui_feature) - [「MiuiHomeR」 by qqlittleice](https://github.com/qqlittleice/MiuiHome_R) - [「MIUI IME Unlock」 by RC1844](https://github.com/RC1844/MIUI_IME_Unlock) - [「MIUI QOL」 by chsbuffer](https://github.com/chsbuffer/MIUIQOL) - [「Miui XXL」 by Wine-Network](https://github.com/Wine-Network/Miui_XXL) - [「Miui XXL」 by YuKongA](https://github.com/YuKongA/Miui_XXL) - [「MIUI 通知修复」 by tehcneko](https://github.com/Xposed-Modules-Repo/io.github.tehcneko.miuinotificationfix) - [「ModemPro」 by Weverse](https://github.com/Weverses/ModemPro) - [「NoStorageRestrict」 by DanGLES3](https://github.com/Xposed-Modules-Repo/com.github.dan.nostoragerestrict) - [「Portal Hook」 by Haocen2004](https://github.com/Haocen2004/PortalHook) - [「PinningApp」 by 焕晨HChen](https://github.com/HChenX/PinningApp) - [「RemoveMiuiSystemSelfProtection」 by gfbjngjibn](https://github.com/gfbjngjibn/RemoveMiuiSystemSelfProtection) - [「SettingsDontThroughTheList」 by weixiansen574](https://github.com/weixiansen574/settingsdontthroughthelist) - [「StarVoyager」 by hosizoraru](https://github.com/hosizoraru/StarVoyager) - [「WINI」 by ouhoukyo](https://github.com/ouhoukyo/WINI) - [「WOMMO」 by YifePlayte](https://github.com/YifePlayte/WOMMO) - [「Woobox For MIUI」 by hosizoraru](https://github.com/hosizoraru/WooBoxForMIUI) - [「Woobox For MIUI」 by Simplicity-Team](https://github.com/Simplicity-Team/WooBoxForMIUI) - [「Xposed」 by rovo89, Tungstwenty](https://github.com/rovo89/XposedBridge) - [「XposedBridge」 by rovo89](https://github.com/rovo89/XposedBridge) - [「.xlDownload」 by Kr328](https://github.com/Kr328/.xlDownload) [qgroup_url]: https://jq.qq.com/?_wv=1027&k=TedCJq8V [badge_qgroup]: https://img.shields.io/badge/QQ-群组-4DB8FF?style=for-the-badge&logo=tencentqq [qguild_url]: https://pd.qq.com/s/35ooe0ssj [badge_qguild]: https://img.shields.io/badge/QQ-频道-4991D3?style=for-the-badge&logo=tencentqq [telegram_url]: https://t.me/cemiuiler [badge_telegram]: https://img.shields.io/badge/dynamic/json?style=for-the-badge&color=2CA5E0&label=Telegram&logo=telegram&query=%24.data.totalSubs&url=https%3A%2F%2Fapi.spencerwoo.com%2Fsubstats%2F%3Fsource%3Dtelegram%26queryKey%3Dcemiuiler
0
alibaba/Sentinel
A powerful flow control component enabling reliability, resilience and monitoring for microservices. (面向云原生微服务的高可用流控防护组件)
2018-04-04T06:37:33Z
null
# Sentinel: The Sentinel of Your Microservices <img src="https://user-images.githubusercontent.com/9434884/43697219-3cb4ef3a-9975-11e8-9a9c-73f4f537442d.png" alt="Sentinel Logo" width="50%"> [![Sentinel CI](https://github.com/alibaba/Sentinel/actions/workflows/ci.yml/badge.svg)](https://github.com/alibaba/Sentinel/actions/workflows/ci.yml) [![Codecov](https://codecov.io/gh/alibaba/Sentinel/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/Sentinel) [![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.csp/sentinel-core.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:com.alibaba.csp%20AND%20a:sentinel-core) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Gitter](https://badges.gitter.im/alibaba/Sentinel.svg)](https://gitter.im/alibaba/Sentinel) [![Leaderboard](https://img.shields.io/badge/Sentinel-Check%20Your%20Contribution-orange)](https://opensource.alibaba.com/contribution_leaderboard/details?projectValue=sentinel) ## Introduction As distributed systems become increasingly popular, the reliability between services is becoming more important than ever before. Sentinel takes "flow" as breakthrough point, and works on multiple fields including **flow control**, **traffic shaping**, **concurrency limiting**, **circuit breaking** and **system adaptive overload protection**, to guarantee reliability and resilience for microservices. Sentinel has the following features: - **Rich applicable scenarios**: Sentinel has been wildly used in Alibaba, and has covered almost all the core-scenarios in Double-11 (11.11) Shopping Festivals in the past 10 years, such as “Second Kill” which needs to limit burst flow traffic to meet the system capacity, message peak clipping and valley fills, circuit breaking for unreliable downstream services, cluster flow control, etc. - **Real-time monitoring**: Sentinel also provides real-time monitoring ability. You can see the runtime information of a single machine in real-time, and the aggregated runtime info of a cluster with less than 500 nodes. - **Widespread open-source ecosystem**: Sentinel provides out-of-box integrations with commonly-used frameworks and libraries such as Spring Cloud, gRPC, Apache Dubbo and Quarkus. You can easily use Sentinel by simply add the adapter dependency to your services. - **Polyglot support**: Sentinel has provided native support for Java, [Go](https://github.com/alibaba/sentinel-golang), [C++](https://github.com/alibaba/sentinel-cpp) and [Rust](https://github.com/sentinel-group/sentinel-rust). - **Various SPI extensions**: Sentinel provides easy-to-use SPI extension interfaces that allow you to quickly customize your logic, for example, custom rule management, adapting data sources, and so on. Features overview: ![features-of-sentinel](./doc/image/sentinel-features-overview-en.png) The community is also working on **the specification of traffic governance and fault-tolerance**. Please refer to [OpenSergo](https://opensergo.io/) for details. ## Documentation See the [Sentinel Website](https://sentinelguard.io/) for the official website of Sentinel. See the [中文文档](https://sentinelguard.io/zh-cn/docs/introduction.html) for document in Chinese. See the [Wiki](https://github.com/alibaba/Sentinel/wiki) for full documentation, examples, blog posts, operational details and other information. Sentinel provides integration modules for various open-source frameworks (e.g. Spring Cloud, Apache Dubbo, gRPC, Quarkus, Spring WebFlux, Reactor) and service mesh. You can refer to [the document](https://sentinelguard.io/en-us/docs/open-source-framework-integrations.html) for more information. If you are using Sentinel, please [**leave a comment here**](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better. It's also encouraged to add the link of your blog post, tutorial, demo or customized components to [**Awesome Sentinel**](./doc/awesome-sentinel.md). ## Ecosystem Landscape ![ecosystem-landscape](./doc/image/sentinel-opensource-eco-landscape-en.png) ## Quick Start Below is a simple demo that guides new users to use Sentinel in just 3 steps. It also shows how to monitor this demo using the dashboard. ### 1. Add Dependency **Note:** Sentinel requires JDK 1.8 or later. If you're using Maven, just add the following dependency in `pom.xml`. ```xml <!-- replace here with the latest version --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> <version>1.8.7</version> </dependency> ``` If not, you can download JAR in [Maven Center Repository](https://mvnrepository.com/artifact/com.alibaba.csp/sentinel-core). ### 2. Define Resource Wrap your code snippet via Sentinel API: `SphU.entry(resourceName)`. In below example, it is `System.out.println("hello world");`: ```java try (Entry entry = SphU.entry("HelloWorld")) { // Your business logic here. System.out.println("hello world"); } catch (BlockException e) { // Handle rejected request. e.printStackTrace(); } // try-with-resources auto exit ``` So far the code modification is done. We've also provided [annotation support module](https://github.com/alibaba/Sentinel/blob/master/sentinel-extension/sentinel-annotation-aspectj/README.md) to define resource easier. ### 3. Define Rules If we want to limit the access times of the resource, we can **set rules to the resource**. The following code defines a rule that limits access to the resource to 20 times per second at the maximum. ```java List<FlowRule> rules = new ArrayList<>(); FlowRule rule = new FlowRule(); rule.setResource("HelloWorld"); // set limit qps to 20 rule.setCount(20); rule.setGrade(RuleConstant.FLOW_GRADE_QPS); rules.add(rule); FlowRuleManager.loadRules(rules); ``` For more information, please refer to [How To Use](https://sentinelguard.io/en-us/docs/basic-api-resource-rule.html). ### 4. Check the Result After running the demo for a while, you can see the following records in `~/logs/csp/${appName}-metrics.log.{date}` (When using the default `DateFileLogHandler`). ```plaintext |--timestamp-|------date time----|-resource-|p |block|s |e|rt |occupied 1529998904000|2018-06-26 15:41:44|HelloWorld|20|0 |20|0|0 |0 1529998905000|2018-06-26 15:41:45|HelloWorld|20|5579 |20|0|728 |0 1529998906000|2018-06-26 15:41:46|HelloWorld|20|15698|20|0|0 |0 1529998907000|2018-06-26 15:41:47|HelloWorld|20|19262|20|0|0 |0 1529998908000|2018-06-26 15:41:48|HelloWorld|20|19502|20|0|0 |0 1529998909000|2018-06-26 15:41:49|HelloWorld|20|18386|20|0|0 |0 p stands for incoming request, block for blocked by rules, s for success handled by Sentinel, e for exception count, rt for average response time (ms), occupied stands for occupiedPassQps since 1.5.0 which enable us booking more than 1 shot when entering. ``` This shows that the demo can print "hello world" 20 times per second. More examples and information can be found in the [How To Use](https://sentinelguard.io/en-us/docs/basic-api-resource-rule.html) section. The working principles of Sentinel can be found in [How it works](https://sentinelguard.io/en-us/docs/basic-implementation.html) section. Samples can be found in the [sentinel-demo](https://github.com/alibaba/Sentinel/tree/master/sentinel-demo) module. ### 5. Start Dashboard > Note: Java 8 is required for building or running the dashboard. Sentinel also provides a simple dashboard application, on which you can monitor the clients and configure the rules in real time. ![dashboard](https://user-images.githubusercontent.com/9434884/55449295-84866d80-55fd-11e9-94e5-d3441f4a2b63.png) For details please refer to [Dashboard](https://github.com/alibaba/Sentinel/wiki/Dashboard). ## Trouble Shooting and Logs Sentinel will generate logs for troubleshooting and real-time monitoring. All the information can be found in [logs](https://sentinelguard.io/en-us/docs/logs.html). ## Bugs and Feedback For bug report, questions and discussions please submit [GitHub Issues](https://github.com/alibaba/sentinel/issues). Contact us via [Gitter](https://gitter.im/alibaba/Sentinel) or [Email](mailto:sentinel@linux.alibaba.com). ## Contributing Contributions are always welcomed! Please refer to [CONTRIBUTING](./CONTRIBUTING.md) for detailed guidelines. You can start with the issues labeled with [`good first issue`](https://github.com/alibaba/Sentinel/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). ## Enterprise Service If you need Sentinel enterprise service support (Sentinel 企业版), or purchase cloud product services, you can join the discussion by the DingTalk group (34754806). It can also be directly activated and used through the [microservice engine (MSE 微服务引擎) provided by Alibaba Cloud](https://cn.aliyun.com/product/aliware/mse?spm=sentinel-github.index.0.0.0). ## Credits Thanks [Guava](https://github.com/google/guava), which provides some inspiration on rate limiting. And thanks for all [contributors](https://github.com/alibaba/Sentinel/graphs/contributors) of Sentinel! ## Who is using These are only part of the companies using Sentinel, for reference only. If you are using Sentinel, please [add your company here](https://github.com/alibaba/Sentinel/issues/18) to tell us your scenario to make Sentinel better :) ![Alibaba Group](https://docs.alibabagroup.com/assets2/images/en/global/logo_header.png) ![AntFin](https://user-images.githubusercontent.com/9434884/90598732-30961c00-e226-11ea-8c86-0b1d7f7875c7.png) ![Taiping Renshou](http://www.cntaiping.com/tplresource/cms/www/taiping/img/home_new/tp_logo_img.png) ![拼多多](http://cdn.pinduoduo.com/assets/img/pdd_logo_v3.png) ![爱奇艺](https://user-images.githubusercontent.com/9434884/90598445-a51c8b00-e225-11ea-9327-3543525f3f2a.png) ![Shunfeng Technology](https://user-images.githubusercontent.com/9434884/48463502-2f48eb80-e817-11e8-984f-2f9b1b789e2d.png) ![二维火](https://user-images.githubusercontent.com/9434884/49358468-bc43de00-f70d-11e8-97fe-0bf05865f29f.png) ![Mandao](https://user-images.githubusercontent.com/9434884/48463559-6cad7900-e817-11e8-87e4-42952b074837.png) ![文轩在线](http://static.winxuancdn.com/css/v2/images/logo.png) ![客如云](https://www.keruyun.com/static/krynew/images/logo.png) ![亲宝宝](https://stlib.qbb6.com/wclt/img/home_hd/version1/title_logo.png) ![金汇金融](https://res.jinhui365.com/r/images/logo2.png?v=1.527) ![闪电购](http://cdn.52shangou.com/shandianbang/official-source/3.1.1/build/images/logo.png)
0
fesh0r/fernflower
Unofficial mirror of FernFlower Java decompiler (All pulls should be submitted upstream)
2014-10-03T05:00:15Z
null
### About Fernflower Fernflower is the first actually working analytical decompiler for Java and probably for a high-level programming language in general. Naturally it is still under development, please send your bug reports and improvement suggestions to the [issue tracker](https://youtrack.jetbrains.com/newIssue?project=IDEA&clearDraft=true&c=Subsystem+Decompiler). ### Licence Fernflower is licenced under the [Apache Licence Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). ### Running from command line `java -jar fernflower.jar [-<option>=<value>]* [<source>]+ <destination>` \* means 0 or more times\ \+ means 1 or more times \<source>: file or directory with files to be decompiled. Directories are recursively scanned. Allowed file extensions are class, zip and jar. Sources prefixed with -e= mean "library" files that won't be decompiled, but taken into account when analysing relationships between classes or methods. Especially renaming of identifiers (s. option 'ren') can benefit from information about external classes. \<destination>: destination directory \<option>, \<value>: a command-line option with the corresponding value (see "Command-line options" below). ##### Examples: `java -jar fernflower.jar -hes=0 -hdc=0 c:\Temp\binary\ -e=c:\Java\rt.jar c:\Temp\source\` `java -jar fernflower.jar -dgs=1 c:\Temp\binary\library.jar c:\Temp\binary\Boot.class c:\Temp\source\` ### Command-line options With the exception of mpm and urc the value of 1 means the option is activated, 0 - deactivated. Default value, if any, is given between parentheses. Typically, the following options will be changed by user, if any: hes, hdc, dgs, mpm, ren, urc The rest of options can be left as they are: they are aimed at professional reverse engineers. - rbr (1): hide bridge methods - rsy (0): hide synthetic class members - din (1): decompile inner classes - dc4 (1): collapse 1.4 class references - das (1): decompile assertions - hes (1): hide empty super invocation - hdc (1): hide empty default constructor - dgs (0): decompile generic signatures - ner (1): assume return not throwing exceptions - den (1): decompile enumerations - rgn (1): remove getClass() invocation, when it is part of a qualified new statement - lit (0): output numeric literals "as-is" - asc (0): encode non-ASCII characters in string and character literals as Unicode escapes - bto (1): interpret int 1 as boolean true (workaround to a compiler bug) - nns (0): allow for not set synthetic attribute (workaround to a compiler bug) - uto (1): consider nameless types as java.lang.Object (workaround to a compiler architecture flaw) - udv (1): reconstruct variable names from debug information, if present - ump (1): reconstruct parameter names from corresponding attributes, if present - rer (1): remove empty exception ranges - fdi (1): de-inline finally structures - mpm (0): maximum allowed processing time per decompiled method, in seconds. 0 means no upper limit - ren (0): rename ambiguous (resp. obfuscated) classes and class elements - urc (-): full name of a user-supplied class implementing IIdentifierRenamer interface. It is used to determine which class identifiers should be renamed and provides new identifier names (see "Renaming identifiers") - inn (1): check for IntelliJ IDEA-specific @NotNull annotation and remove inserted code if found - lac (0): decompile lambda expressions to anonymous classes - nls (0): define new line character to be used for output. 0 - '\r\n' (Windows), 1 - '\n' (Unix), default is OS-dependent - ind: indentation string (default is 3 spaces) - crp (0): use record patterns where it is possible - cps (0): use switch with patterns where it is possible - log (INFO): a logging level, possible values are TRACE, INFO, WARN, ERROR ### Renaming identifiers Some obfuscators give classes and their member elements short, meaningless and above all ambiguous names. Recompiling of such code leads to a great number of conflicts. Therefore it is advisable to let the decompiler rename elements in its turn, ensuring uniqueness of each identifier. Option 'ren' (i.e. -ren=1) activates renaming functionality. Default renaming strategy goes as follows: - rename an element if its name is a reserved word or is shorter than 3 characters - new names are built according to a simple pattern: (class|method|field)_\<consecutive unique number> You can overwrite this rules by providing your own implementation of the 4 key methods invoked by the decompiler while renaming. Simply pass a class that implements org.jetbrains.java.decompiler.main.extern.IIdentifierRenamer in the option 'urc' (e.g. -urc=com.example.MyRenamer) to Fernflower. The class must be available on the application classpath. The meaning of each method should be clear from naming: toBeRenamed determine whether the element will be renamed, while the other three provide new names for classes, methods and fields respectively.
0
itwanger/toBeBetterJavaer
一份通俗易懂、风趣幽默的Java学习指南,内容涵盖Java基础、Java并发编程、Java虚拟机、Java企业级开发、Java面试等核心知识点。学Java,就认准二哥的Java进阶之路😄
2018-11-08T00:35:56Z
null
<p align="center"> <a href="https://javabetter.cn"> <img src="https://cdn.tobebetterjavaer.com/tobebetterjavaer/images/logo.png" width="200px" alt="二哥的Java进阶之路"> </a> </p> <p align="center"> <a href="https://javabetter.cn/blog.html" target="_blank"><img src="https://img.shields.io/badge/博客-在线阅读-green.svg?style=for-the-badge"></a> <a href="#联系方式" target="_blank"><img src="https://img.shields.io/badge/公众号-沉默王二-brightgreen.svg?style=for-the-badge"></a> <a href="https://javabetter.cn/zhishixingqiu/" target="_blank"><img src="https://img.shields.io/badge/学习圈子-立即加入-critical?style=for-the-badge"></a> <a href="https://javabetter.cn/download/java.html" target="_blank"><img src="https://img.shields.io/badge/计算机经典电子书-下载-yellow.svg?style=for-the-badge" alt="无套路下载"></a> <a href="https://github.com/itwanger/toBeBetterJavaer" target="_blank"><img alt="二哥的Java进阶之路" src="https://img.shields.io/github/stars/itwanger/toBeBetterJavaer?style=for-the-badge"></a><br><br> <a href="https://github.com/itwanger/toBeBetterJavaer">Github</a> | <a href="https://gitee.com/itwanger/toBeBetterJavaer">Gitee</a> </p> # 为什么会有这个开源知识库 > 知识库取名 **toBeBetterJavaer**,即 **To Be Better Javaer**,意为「成为一名更好的 Java 程序员」,是我自学 Java 以来所有原创文章和学习资料的大聚合。内容包括 Java 基础、Java 并发编程、Java 虚拟机、Java 企业级开发、Java 面试等核心知识点。据说每一个优秀的 Java 程序员都喜欢她,风趣幽默、通俗易懂。学 Java,就认准 二哥的Java进阶之路😄。 > > 知识库旨在为学习 Java 的小伙伴提供一系列: > - **优质的原创 Java 教程** > - **全面清晰的 Java 学习路线** > - **免费但靠谱的 Java 学习资料** > - **精选的 Java 岗求职面试指南** > - **Java 企业级开发所需的必备技术** > > 赠人玫瑰手有余香。知识库会持续保持**更新**,欢迎收藏品鉴! > > **转载须知** :以下所有文章如非文首说明为转载皆为我(沉默王二)的原创,转载在文首注明出处,如发现恶意抄袭/搬运,会动用法律武器维护自己的权益。让我们一起维护一个良好的技术创作环境! > > 推荐你通过在线阅读网站进行阅读,体验更好,速度更快! > > - [**二哥的Java进阶之路在线网站(新域名:javabetter.cn 好记,推荐👍)**](https://javabetter.cn) > - [老版 Java 程序员进阶之路在线网址(老域名 tobebetterjavaer.com 难记)](https://tobebetterjavaer.com) > - [技术派之二哥的Java进阶之路专栏](https://paicoding.com/column/5/1) > > 如果你更喜欢离线的 PDF 版本,戳这个链接获取[👍二哥的 Java 进阶之路.pdf](docs/overview/readme.md) # 知识库地图 > 知识库收录的核心内容就全在这里面了,大类分为 Java 核心、Java 企业级开发、数据库、计算机基础、求职面试、学习资源、程序人生,几乎你需要的这里都有。 ![](https://cdn.tobebetterjavaer.com/tobebetterjavaer/images/tobebetterjavaer-map.png) 一个人可以走得很快,但一群人才能走得更远。[二哥的编程星球](https://javabetter.cn/zhishixingqiu/)已经有 **5000 多名** 球友加入了(戳[链接](https://javabetter.cn/zhishixingqiu/)了解详情),如果你也需要一个良好的学习环境,扫描下方的优惠券加入我们吧。新人可免费体验 3 天,不满意可全额退款(只能帮你到这里了😄)。 <p align="center"> <a href="https://javabetter.cn/zhishixingqiu/"> <kbd> <img src="https://cdn.tobebetterjavaer.com/stutymore/home-20240104101824.png" width="400px" alt="星球优惠券"> </kbd> </a> </p> 这是一个**编程学习指南 + Java 项目实战 + LeetCode 刷题的私密圈子**,你可以阅读星球专栏、向二哥提问、帮你制定学习计划、和球友一起打卡成长。两个置顶帖「球友必看」和「知识图谱」里已经沉淀了非常多优质的内容,**相信能帮助你走的更快、更稳、更远**。 - [Java面试指南专栏,面试必备✌️](https://javabetter.cn/zhishixingqiu/mianshi.html) - [技术派,秋招项目经历必备✌️](https://javabetter.cn/zhishixingqiu/paicoding.html) - [简历修改服务✌️](https://javabetter.cn/zhishixingqiu/jianli.html) # 学习路线 > 除了 Java 学习路线,还有 MySQL、Redis、C语言、C++、Python、Go 语言、操作系统、前端、数据结构与算法、蓝桥杯、大数据、Android、.NET等硬核学习路线,欢迎收藏品鉴! * [Java学习路线一条龙版(建议收藏🔥)](docs/xuexiluxian/java/yitiaolong.md) * [Java并发编程学习路线(建议收藏🔥)](docs/xuexiluxian/java/thread.md) * [Java虚拟机学习路线(建议收藏🔥)](docs/xuexiluxian/java/jvm.md) * [MySQL 学习路线(建议收藏🔥)](docs/xuexiluxian/mysql.md) * [Redis 学习路线(建议收藏🔥)](docs/xuexiluxian/redis.md) * [C语言学习路线(建议收藏🔥)](docs/xuexiluxian/c.md) * [C++学习路线(建议收藏🔥)](docs/xuexiluxian/ccc.md) * [Python学习路线(建议收藏🔥)](docs/xuexiluxian/python.md) * [Go语言学习路线(建议收藏🔥)](docs/xuexiluxian/go.md) * [操作系统学习路线(建议收藏🔥)](docs/xuexiluxian/os.md) * [前端学习路线(建议收藏🔥)](docs/xuexiluxian/qianduan.md) * [算法和数据结构学习路线(建议收藏🔥)](docs/xuexiluxian/algorithm.md) * [蓝桥杯学习路线(建议收藏🔥)](docs/xuexiluxian/lanqiaobei.md) * [大数据学习路线(建议收藏🔥)](docs/xuexiluxian/bigdata.md) * [Android 安卓学习路线(建议收藏🔥)](docs/xuexiluxian/android.md) * [.NET 学习路线(建议收藏🔥)](docs/xuexiluxian/donet.md) * [Linux 学习路线(建议收藏🔥)](docs/xuexiluxian/linux.md) # 面渣逆袭 > **面试前必读系列**!包括 Java 基础、Java 集合框架、Java 并发编程、Java 虚拟机、Spring、Redis、MyBatis、MySQL、操作系统、计算机网络、RocketMQ、分布式、微服务、设计模式、Linux 等等。 - [面渣逆袭(Java 基础篇八股文面试题)必看👍](docs/sidebar/sanfene/javase.md) - [面渣逆袭(Java 集合框架篇八股文面试题)必看👍](docs/sidebar/sanfene/collection.md) - [面渣逆袭(Java 并发编程篇八股文面试题)必看👍](docs/sidebar/sanfene/javathread.md) - [面渣逆袭(Java 虚拟机篇八股文面试题)必看👍](docs/sidebar/sanfene/jvm.md) - [面渣逆袭(Spring八股文面试题)必看👍](docs/sidebar/sanfene/spring.md) - [面渣逆袭(MySQL八股文面试题)必看👍](docs/sidebar/sanfene/mysql.md) - [面渣逆袭(Redis八股文面试题)必看👍](docs/sidebar/sanfene/redis.md) - [面渣逆袭(MyBatis八股文面试题)必看👍](docs/sidebar/sanfene/mybatis.md) - [面渣逆袭(操作系统八股文面试题)必看👍](docs/sidebar/sanfene/os.md) - [面渣逆袭(计算机网络八股文面试题)必看👍](docs/sidebar/sanfene/network.md) - [面渣逆袭(RocketMQ八股文面试题)必看👍](docs/sidebar/sanfene/rocketmq.md) - [面渣逆袭(分布式面试题八股文)必看👍](docs/sidebar/sanfene/fenbushi.md) - [面渣逆袭(微服务面试题八股文)必看👍](docs/sidebar/sanfene/weifuwu.md) - [面渣逆袭(设计模式面试题八股文)必看👍](docs/sidebar/sanfene/shejimoshi.md) - [面渣逆袭(Linux面试题八股文)必看👍](docs/sidebar/sanfene/linux.md) # Java基础 > **Java基础非常重要**!包括基础语法、面向对象、集合框架、异常处理、Java IO、网络编程、NIO、并发编程和 JVM。 ## Java概述及环境配置 - [《二哥的Java进阶之路》小册简介](docs/overview/readme.md) - [Java简史、特性、前景](docs/overview/what-is-java.md) - [Windows和macOS下安装JDK教程](docs/overview/jdk-install-config.md) - [在macOS和Windows上安装Intellij IDEA](docs/overview/IDEA-install-config.md) - [编写第一个程序Hello World](docs/overview/hello-world.md) ## Java基础语法 - [48个关键字及2个保留字全解析](docs/basic-extra-meal/48-keywords.md) - [了解Java注释](docs/basic-grammar/javadoc.md) - [基本数据类型与引用数据类型](docs/basic-grammar/basic-data-type.md) - [自动类型转换与强制类型转换](docs/basic-grammar/type-cast.md) - [Java基本数据类型缓存池剖析(IntegerCache)](docs/basic-extra-meal/int-cache.md) - [Java运算符详解](docs/basic-grammar/operator.md) - [Java流程控制语句详解](docs/basic-grammar/flow-control.md) - [Java 语法基础练习题](docs/basic-grammar/basic-exercise.md) ## 数组&字符串 - [掌握Java数组](docs/array/array.md) - [掌握 Java二维数组](docs/array/double-array.md) - [如何优雅地打印Java数组?](docs/array/print.md) - [深入解读String类源码](docs/string/string-source.md) - [为什么Java字符串是不可变的?](docs/string/immutable.md) - [深入理解Java字符串常量池](docs/string/constant-pool.md) - [详解 String.intern() 方法](docs/string/intern.md) - [String、StringBuilder、StringBuffer](docs/string/builder-buffer.md) - [Java中equals()与==的区别](docs/string/equals.md) - [最优雅的Java字符串拼接是哪种方式?](docs/string/join.md) - [如何在Java中拆分字符串?](docs/string/split.md) ## Java面向对象编程 - [类和对象](docs/oo/object-class.md) - [Java中的包](docs/oo/package.md) - [Java变量](docs/oo/var.md) - [Java方法](docs/oo/method.md) - [Java可变参数详解](docs/basic-extra-meal/varables.md) - [手把手教你用 C语言实现 Java native 本地方法](docs/oo/native-method.md) - [Java构造方法](docs/oo/construct.md) - [Java访问权限修饰符](docs/oo/access-control.md) - [Java代码初始化块](docs/oo/code-init.md) - [Java抽象类](docs/oo/abstract.md) - [Java接口](docs/oo/interface.md) - [Java内部类](docs/oo/inner-class.md) - [深入理解Java三大特性:封装、继承和多态](docs/oo/encapsulation-inheritance-polymorphism.md) - [详解Java this与super关键字](docs/oo/this-super.md) - [详解Java static 关键字](docs/oo/static.md) - [详解Java final 关键字](docs/oo/final.md) - [掌握Java instanceof关键字](docs/basic-extra-meal/instanceof.md) - [聊聊Java中的不可变对象](docs/basic-extra-meal/immutable.md) - [方法重写 Override 和方法重载 Overload 有什么区别?](docs/basic-extra-meal/override-overload.md) - [深入理解Java中的注解](docs/basic-extra-meal/annotation.md) - [Java枚举:小小enum,优雅而干净](docs/basic-extra-meal/enum.md) ## 集合框架(容器) - [Java集合框架概览,包括List、Set、Map、队列](docs/collection/gailan.md) - [深入探讨 Java ArrayList](docs/collection/arraylist.md) - [深入探讨 Java LinkedList](docs/collection/linkedlist.md) - [Java Stack详解](docs/collection/stack.md) - [Java HashMap详解](docs/collection/hashmap.md) - [Java LinkedHashMap详解](docs/collection/linkedhashmap.md) - [Java TreeMap详解](docs/collection/treemap.md) - [Java 双端队列 ArrayDeque详解](docs/collection/arraydeque.md) - [Java 优先级队列PriorityQueue详解](docs/collection/PriorityQueue.md) - [Java Comparable和Comparator的区别](docs/collection/comparable-omparator.md) - [时间复杂度,评估ArrayList和LinkedList的执行效率](docs/collection/time-complexity.md) - [ArrayList和LinkedList的区别](docs/collection/list-war-2.md) - [Java 泛型深入解析](docs/basic-extra-meal/generic.md) - [Java迭代器Iterator和Iterable有什么区别?](docs/collection/iterator-iterable.md) - [为什么禁止在foreach里执行元素的删除操作?](docs/collection/fail-fast.md) ## Java IO - [深入了解 Java IO](docs/io/shangtou.md) - [Java File:IO 流的起点与终点](docs/io/file-path.md) - [Java 字节流:Java IO 的基石](docs/io/stream.md) - [Java 字符流:Reader和Writer的故事](docs/io/reader-writer.md) - [Java 缓冲流:Java IO 的读写效率有了质的飞升](docs/io/buffer.md) - [Java 转换流:Java 字节流和字符流的桥梁](docs/io/char-byte.md) - [Java 打印流:PrintStream & PrintWriter](docs/io/print.md) - [Java 序列流:Java 对象的序列化和反序列化](docs/io/serialize.md) - [Java Serializable 接口:明明就一个空的接口嘛](docs/io/Serializbale.md) - [深入探讨 Java transient 关键字](docs/io/transient.md) ## 异常处理 - [一文彻底搞懂Java异常处理,YYDS](docs/exception/gailan.md) - [深入理解 Java 中的 try-with-resources](docs/exception/try-with-resources.md) - [Java异常处理的20个最佳实践](docs/exception/shijian.md) - [空指针NullPointerException的传说](docs/exception/npe.md) - [try-catch 捕获异常真的会影响性能吗?](docs/exception/try-catch-xingneng.md) ## 常用工具类 - [Java Scanner:扫描控制台输入的工具类](docs/common-tool/scanner.md) - [Java Arrays:专为数组而生的工具类](docs/common-tool/arrays.md) - [Apache StringUtils:专为Java字符串而生的工具类](docs/common-tool/StringUtils.md) - [Objects:专为操作Java对象而生的工具类](docs/common-tool/Objects.md) - [Java Collections:专为集合而生的工具类](docs/common-tool/collections.md) - [Hutool:国产良心工具包,让你的Java变得更甜](docs/common-tool/hutool.md) - [Guava:Google开源的Java工具库,太强大了](docs/common-tool/guava.md) - [其他常用Java工具类:IpUtil、MDC、ClassUtils、BeanUtils、ReflectionUtils](docs/common-tool/utils.md) ## Java新特性 - [Java 8 Stream流:掌握流式编程的精髓](docs/java8/stream.md) - [Java 8 Optional最佳指南:解决空指针问题的优雅之选](docs/java8/optional.md) - [深入浅出Java 8 Lambda表达式:探索函数式编程的魅力](docs/java8/Lambda.md) - [Java 14 开箱,新特性Record、instanceof、switch香香香香](docs/java8/java14.md) ## Java网络编程 - [Java网络编程的基础:计算机网络](docs/socket/network-base.md) - [Java Socket:飞鸽传书的网络套接字](docs/socket/socket.md) - [牛逼,用Java Socket手撸了一个HTTP服务器](docs/socket/http.md) ## Java NIO - [Java NIO 比传统 IO 强在哪里?](docs/nio/nio-better-io.md) - [一文彻底解释清楚Java 中的NIO、BIO和AIO](docs/nio/BIONIOAIO.md) - [详解Java NIO的Buffer缓冲区和Channel通道](docs/nio/buffer-channel.md) - [聊聊 Java NIO中的Paths、Files](docs/nio/paths-files.md) - [Java NIO 网络编程实践:从入门到精通](docs/nio/network-connect.md) - [一文彻底理解Java IO模型](docs/nio/moxing.md) ## 重要知识点 - [Java命名规范:编写可读性强的代码](docs/basic-extra-meal/java-naming.md) - [解决中文乱码:字符编码全攻略 - ASCII、Unicode、UTF-8、GB2312详解](docs/basic-extra-meal/java-unicode.md) - [深入浅出Java拆箱与装箱](docs/basic-extra-meal/box.md) - [深入理解Java浅拷贝与深拷贝](docs/basic-extra-meal/deep-copy.md) - [Java hashCode方法解析](docs/basic-extra-meal/hashcode.md) - [Java到底是值传递还是引用传递?](docs/basic-extra-meal/pass-by-value.md) - [为什么无法实现真正的泛型?](docs/basic-extra-meal/true-generic.md) - [Java 反射详解](docs/basic-extra-meal/fanshe.md) ## Java并发编程 - [并发编程小册简介](docs/thread/readme.md) - [Java多线程入门](docs/thread/wangzhe-thread.md) - [获取线程的执行结果](docs/thread/callable-future-futuretask.md) - [Java线程的6种状态及切换](docs/thread/thread-state-and-method.md) - [线程组和线程优先级](docs/thread/thread-group-and-thread-priority.md) - [进程与线程的区别](docs/thread/why-need-thread.md) - [多线程带来了哪些问题?](docs/thread/thread-bring-some-problem.md) - [Java的内存模型(JMM)](docs/thread/jmm.md) - [volatile关键字解析](docs/thread/volatile.md) - [synchronized关键字解析](docs/thread/synchronized-1.md) - [synchronized的四种锁状态](docs/thread/synchronized.md) - [深入浅出偏向锁](docs/thread/pianxiangsuo.md) - [CAS详解](docs/thread/cas.md) - [AQS详解](docs/thread/aqs.md) - [锁分类和 JUC](docs/thread/lock.md) - [重入锁ReentrantLock](docs/thread/reentrantLock.md) - [读写锁ReentrantReadWriteLock](docs/thread/ReentrantReadWriteLock.md) - [等待通知条件Condition](docs/thread/condition.md) - [线程阻塞唤醒类LockSupport](docs/thread/LockSupport.md) - [Java的并发容器](docs/thread/map.md) - [并发容器ConcurrentHashMap](docs/thread/ConcurrentHashMap.md) - [非阻塞队列ConcurrentLinkedQueue](docs/thread/ConcurrentLinkedQueue.md) - [阻塞队列BlockingQueue](docs/thread/BlockingQueue.md) - [并发容器CopyOnWriteArrayList](docs/thread/CopyOnWriteArrayList.md) - [本地变量ThreadLocal](docs/thread/ThreadLocal.md) - [线程池](docs/thread/pool.md) - [定时任务ScheduledThreadPoolExecutor](docs/thread/ScheduledThreadPoolExecutor.md) - [原子操作类Atomic](docs/thread/atomic.md) - [魔法类 Unsafe](docs/thread/Unsafe.md) - [通信工具类](docs/thread/CountDownLatch.md) - [Fork/Join](docs/thread/fork-join.md) - [生产者-消费者模式](docs/thread/shengchanzhe-xiaofeizhe.md) ## Java虚拟机 - [JVM小册简介](docs/jvm/readme.md) - [大白话带你认识JVM](docs/jvm/what-is-jvm.md) - [JVM是如何运行Java代码的?](docs/jvm/how-run-java-code.md) - [Java的类加载机制(付费)](docs/jvm/class-load.md) - [Java的类文件结构](docs/jvm/class-file-jiegou.md) - [从javap的角度轻松看懂字节码](docs/jvm/bytecode.md) - [栈虚拟机与寄存器虚拟机](docs/jvm/vm-stack-register.md) - [字节码指令详解](docs/jvm/zijiema-zhiling.md) - [深入理解JVM的栈帧结构](docs/jvm/stack-frame.md) - [深入理解JVM的运行时数据区](docs/jvm/neicun-jiegou.md) - [深入理解JVM的垃圾回收机制](docs/jvm/gc.md) - [深入理解 JVM 的垃圾收集器:CMS、G1、ZGC](docs/jvm/gc-collector.md) - [Java 创建的对象到底放在哪?](docs/jvm/whereis-the-object.md) - [深入理解JIT(即时编译)](docs/jvm/jit.md) - [JVM 性能监控之命令行篇](docs/jvm/console-tools.md) - [JVM 性能监控之可视化篇](docs/jvm/view-tools.md) - [阿里开源的 Java 诊断神器 Arthas](docs/jvm/arthas.md) - [内存溢出排查优化实战](docs/jvm/oom.md) - [CPU 100% 排查优化实践](docs/jvm/cpu-percent-100.md) - [JVM 核心知识点总结](docs/jvm/zongjie.md) # Java进阶 > - **到底能不能成为一名合格的 Java 程序员,从理论走向实战?Java进阶这部分内容就是一个分水岭**! > - 纸上得来终觉浅,须知此事要躬行。 ## 开发/构建工具 > 工欲善其事必先利其器,这句话大家都耳熟能详了,熟练使用开发/构建工具可以让我们极大提升开发效率,解放生产力。 - [5分钟带你深入浅出搞懂Nginx](docs/nginx/nginx.md) ### IDEA > 集成开发环境,Java 党主要就是 Intellij IDEA 了,号称史上最强大的 Java 开发工具,没有之一。 - [分享 4 个阅读源码必备的 IDEA 调试技巧](docs/ide/4-debug-skill.md) - [分享 1 个可以在 IDEA 里下五子棋的插件](docs/ide/xechat.md) - [分享 10 个可以一站式开发的 IDEA 神级插件](docs/ide/shenji-chajian-10.md) ### Maven > Maven 是目前比较流行的一个项目构建工具,基于 pom 坐标来帮助我们管理第三方依赖,以及项目打包。 - [终于把项目构建神器Maven捋清楚了~](docs/maven/maven.md) ### Git > Git 是一个分布式版本控制系统,缔造者是大名鼎鼎的林纳斯·托瓦茲 (Linus Torvalds),Git 最初的目的是为了能更好的管理 Linux 内核源码。如今,Git 已经成为全球软件开发者的标配。如果说 Linux 项目促成了开源软件的成功并改写了软件行业的格局,那么 Git 则是改变了全世界开发者的工作方式和写作方式。 - [1小时彻底掌握Git](docs/git/git-qiyuan.md) - [GitHub 远程仓库端口切换](docs/git/port-22-to-443.md) ## Spring - [Spring AOP扫盲](docs/springboot/aop-log.md) - [Spring IoC扫盲](docs/springboot/ioc.md) ## SpringBoot - [一分钟快速搭建Spring Boot项目](docs/springboot/initializr.md) - [Spring Boot 整合 lombok](docs/springboot/lombok.md) - [Spring Boot 整合 MySQL 和 Druid](docs/springboot/mysql-druid.md) - [Spring Boot 整合 JPA](docs/springboot/jpa.md) - [Spring Boot 整合 Thymeleaf 模板引擎](docs/springboot/thymeleaf.md) - [Spring Boot 如何开启事务支持?](docs/springboot/transaction.md) - [Spring Boot 中使用过滤器、拦截器、监听器](docs/springboot/Filter-Interceptor-Listener.md) - [Spring Boot 整合 Redis 实现缓存](docs/redis/redis-springboot.md) - [Spring Boot 整合 Logback 定制日志框架](docs/springboot/logback.md) - [Spring Boot 整合 Swagger-UI 实现在线API文档](docs/springboot/swagger.md) - [Spring Boot 整合 Knife4j,美化强化丑陋的Swagger](docs/gongju/knife4j.md) - [Spring Boot 整合 Spring Task 实现定时任务](docs/springboot/springtask.md) - [Spring Boot 整合 MyBatis-Plus AutoGenerator 生成编程喵项目骨架代码](docs/kaiyuan/auto-generator.md) - [Spring Boot 整合Quartz实现编程喵定时发布文章](docs/springboot/quartz.md) - [Spring Boot 整合 MyBatis](docs/springboot/mybatis.md) - [一键部署 Spring Boot 到远程 Docker 容器](docs/springboot/docker.md) - [如何在本地(macOS环境)跑起来编程喵(Spring Boot+Vue)项目源码?](docs/springboot/macos-codingmore-run.md) - [如何在本地(Windows环境)跑起来编程喵(Spring Boot+Vue)项目源码?](docs/springboot/windows-codingmore-run.md) - [编程喵🐱实战项目如何在云服务器上跑起来?](docs/springboot/linux-codingmore-run.md) - [SpringBoot中处理校验逻辑的两种方式:Hibernate Validator+全局异常处理](docs/springboot/validator.md) ## Netty - [超详细Netty入门,看这篇就够了!](docs/netty/rumen.md) ## 辅助工具 - [Chocolatey:一款GitHub星标8.2k+的Windows命令行软件管理器,好用到爆!](docs/gongju/choco.md) - [Homebrew,GitHub 星标 32.5k+的 macOS 命令行软件管理神器,功能真心强大!](docs/gongju/brew.md) - [Tabby:一款逼格更高的开源终端工具,GitHub 星标 21.4k](docs/gongju/tabby.md) - [Warp:号称下一代终端神器,GitHub星标2.8k+,用完爱不释手](docs/gongju/warp.md) - [WindTerm:新一代开源免费的终端工具,GitHub星标6.6k+,太酷了!](docs/gongju/windterm.md) - [chiner:干掉 PowerDesigner,国人开源的数据库设计工具,界面漂亮,功能强大](docs/gongju/chiner.md) - [DBeaver:干掉付费的 Navicat,操作所有数据库就靠它了!](docs/gongju/DBeaver.md) ## 开源轮子 - [Forest:一款极简的声明式HTTP调用API框架](docs/gongju/forest.md) - [Junit:一个开源的Java单元测试框架](docs/gongju/junit.md) - [fastjson:阿里巴巴开源的JSON解析库](docs/gongju/fastjson.md) - [Gson:Google开源的JSON解析库](docs/gongju/gson.md) - [Jackson:GitHub上star数最多的JSON解析库](docs/gongju/jackson.md) - [Log4j:Java日志框架的鼻祖](docs/gongju/log4j.md) - [Log4j 2:Apache维护的一款高性能日志记录工具](docs/gongju/log4j2.md) - [Logback:Spring Boot内置的日志处理框架](docs/gongju/logback.md) - [SLF4J:阿里巴巴强制使用的日志门面担当](docs/gongju/slf4j.md) ## 分布式 - [全文搜索引擎Elasticsearch入门教程](docs/elasticsearch/rumen.md) - [可能是把ZooKeeper概念讲的最清楚的一篇文章](docs/zookeeper/jibenjieshao.md) - [微服务网关:从对比到选型,由理论到实践](docs/microservice/api-wangguan.md) ## 消息队列 - [RabbitMQ入门教程(概念、应用场景、安装、使用)](docs/mq/rabbitmq-rumen.md) - [怎么确保消息100%不丢失?](docs/mq/100-budiushi.md) - [Kafka核心知识点大梳理](docs/mq/kafka.md) # 数据库 > - **简而言之,就是按照数据结构来组织、存储和管理数据的仓库**。几乎所有的 Java 后端开发都要学习数据库这块的知识,包括关系型数据库 MySQL,缓存中间件 Redis,非关系型数据库 MongoDB 等。 ## MySQL - [MySQL 的安装和连接,结合技术派实战项目来讲](docs/mysql/install.md) - [MySQL 的数据库操作,利用 Spring Boot 实现数据库的自动创建](docs/mysql/database.md) - [MySQL 表的基本操作,结合技术派的表自动初始化来讲](docs/mysql/table.md) - [MySQL 的数据类型,4000 字 20 张手绘图,彻底掌握](docs/mysql/data-type.md) - [MySQL 的字符集和比较规则,从跟上掌握](docs/mysql/charset.md) - [MySQL bin目录下的那些可执行文件,包括备份数据库、导入 CSV 等](docs/mysql/bin.md) - [MySQL 的字段属性,默认值、是否为空、主键、自增、ZEROLFILL等一网打尽](docs/mysql/column.md) - [MySQL 的简单查询,开始踏上 SELECT 之旅](docs/mysql/select-simple.md) - [MySQL 的 WEHRE 条件查询,重点搞懂 % 通配符](docs/mysql/select-where.md) - [如何保障MySQL和Redis的数据一致性?](docs/mysql/redis-shuju-yizhixing.md) - [从根上理解 MySQL 的事务](docs/mysql/lijie-shiwu.md) - [浅入深出 MySQL 中事务的实现](docs/mysql/shiwu-shixian.md) ## Redis - [Redis入门(适合新手)](docs/redis/rumen.md) - [聊聊缓存雪崩、穿透、击穿](docs/redis/xuebeng-chuantou-jichuan.md) ## MongoDB - [MongoDB最基础入门教程](docs/mongodb/rumen.md) # 计算机基础 > - **计算机基础包括操作系统、计算机网络、计算机组成原理、数据结构与算法等**。对于任何一名想要走得更远的 Java 后端开发来说,都是必须要花时间和精力去夯实的。 > - 万丈高露平地起,勿在浮沙筑高台。 - [操作系统核心知识点大梳理](docs/cs/os.md) - [计算机网络核心知识点大梳理](docs/cs/wangluo.md) # 求职面试 > - **学习了那么多 Java 知识,耗费了无数的脑细胞,熬掉了无数根秀发,为的是什么?当然是谋取一份心仪的 offer 了**。那八股文、面试题、城市选择、优质面经又怎能少得了呢? > - 千淘万漉虽辛苦,吹尽狂沙始到金。 ## 面试题&八股文 - [34 道 Java 精选面试题👍](docs/interview/java-34.md) - [13 道 Java HashMap 精选面试题👍](docs/interview/java-hashmap-13.md) - [60 道 MySQL 精选面试题👍](docs/interview/mysql-60.md) - [15 道 MySQL 索引精选面试题👍](docs/interview/mysql-suoyin-15.md) - [12 道 Redis 精选面试题👍](docs/interview/redis-12.md) - [40 道 Nginx 精选面试题👍](docs/interview/nginx-40.md) - [17 道 Dubbo 精选面试题👍](docs/interview/dubbo-17.md) - [40 道 Kafka 精选面试题👍](docs/interview/kafka-40.md) - [Java 基础背诵版八股文必看🍉](docs/interview/java-basic-baguwen.md) - [Java 并发编程背诵版八股文必看🍉](docs/interview/java-thread-baguwen.md) - [Java 虚拟机背诵版八股文必看🍉](docs/interview/java-jvm-baguwen.md) - [携程面试官👤:大文件上传时如何做到秒传?](docs/interview/mianshiguan-bigfile-miaochuan.md) - [阿里面试官👤:为什么要分库分表?](docs/interview/mianshiguan-fenkufenbiao.md) - [淘宝面试官👤:优惠券系统该如何设计?](docs/interview/mianshiguan-youhuiquan.md) ## 优质面经 - [硕士读者春招斩获深圳腾讯PCG和杭州阿里云 offer✌️](docs/mianjing/shanganaliyun.md) - [本科读者小公司一年工作经验社招拿下阿里美团头条京东滴滴等 offer✌️](docs/mianjing/shezynmjfxhelmtttjddd.md) - [非科班读者,用一年时间社招拿下阿里 Offer✌️](docs/mianjing/xuelybdzheloffer.md) - [二本读者社招两年半10家公司28轮面试面经✌️](docs/mianjing/huanxgzl.md) - [双非一本秋招收获腾讯ieg、百度、字节等6家大厂offer✌️](docs/mianjing/quzjlsspdx.md) - [双非学弟收割阿里、字节、B站校招 offer,附大学四年硬核经验总结✌️](docs/mianjing/zheisnylzldhzd.md) - [深漂 6 年了,回西安的一波面经总结✌️](docs/mianjing/chengxyspnhxagzl.md) ## 面试准备 - [面试常见词汇扫盲+大厂面试特点分享💪](docs/nice-article/weixin/miansmtgl.md) - [有无实习/暑期实习 offer 如何准备秋招?💪](docs/nice-article/weixin/zijxjjdyfqzgl.md) - [简历如何优化,简历如何投递,面试如何准备?💪](docs/nice-article/weixin/luoczbmsddyb.md) - [校招时间节点、简历编写、笔试、HR面、实习等注意事项💪](docs/nice-article/weixin/youdxzhhmjzlycfx.md) ## 城市选择 - [武汉都有哪些值得加入的IT互联网公司?](docs/cityselect/wuhan.md) - [北京都有哪些值得加入的IT互联网公司?](docs/cityselect/beijing.md) - [广州都有哪些值得加入的IT互联网公司?](docs/cityselect/guangzhou.md) - [深圳都有哪些值得加入的IT互联网公司?](docs/cityselect/shenzhen.md) - [西安都有哪些值得加入的IT互联网公司?](docs/cityselect/xian.md) - [青岛都有哪些值得加入的IT互联网公司?](docs/cityselect/qingdao.md) - [郑州都有哪些值得加入的IT互联网公司?](docs/cityselect/zhengzhou.md) - [苏州都有哪些值得加入的IT互联网公司?](docs/cityselect/suzhou.md) - [南京都有哪些值得加入的IT互联网公司?](docs/cityselect/nanjing.md) - [杭州都有哪些值得加入的IT互联网公司?](docs/cityselect/hangzhou.md) - [成都都有哪些值得加入的IT互联网公司?](docs/cityselect/chengdu.md) - [济南都有哪些值得加入的IT互联网公司?](docs/cityselect/jinan.md) # 学习资源 > - **不知道学什么?不知道该怎么学?找不到优质的学习资源**?这些问题在这里统统都可以找到答案。 > - 我会把自己十多年的编程经验和学习资源毫不保留的分享出来。 ## PDF下载 - [👏下载→Linux速查备忘手册.pdf](docs/pdf/linux.md) - [👏下载→超1000本计算机经典书籍分享](docs/pdf/java.md) - [👏下载→2022年全网最全关于程序员学习和找工作的PDF资源](docs/pdf/programmer-111.md) - [👏下载→深入浅出Java多线程PDF](docs/pdf/java-concurrent.md) - [👏下载→GitHub星标115k+的Java教程](docs/pdf/github-java-jiaocheng-115-star.md) - [👏下载→重学Java设计模式PDF](docs/pdf/shejimoshi.md) - [👏下载→Java版LeetCode刷题笔记](docs/pdf/java-leetcode.md) - [👏下载→阿里巴巴Java开发手册](docs/pdf/ali-java-shouce.md) - [👏下载→阮一峰C语言入门教程](docs/pdf/yuanyifeng-c-language.md) - [👏下载→BAT大佬的刷题笔记](docs/pdf/bat-shuati.md) - [👏下载→给操作系统捋条线PDF](docs/pdf/os.md) - [👏下载→豆瓣9.1分的Pro Git中文版](docs/pdf/progit.md) - [👏下载→简历模板](docs/pdf/jianli.md) ## 学习建议 - [计算机专业该如何自学编程,看哪些书籍哪些视频哪些教程?](docs/xuexijianyi/LearnCS-ByYourself.md) - [如何阅读《深入理解计算机系统》这本书?](docs/xuexijianyi/read-csapp.md) - [电子信息工程最好的出路的是什么?](docs/xuexijianyi/electron-information-engineering.md) - [如何填报计算机大类高考填志愿,计科、人工智能、软工、大数据、物联网、网络工程该怎么选?](docs/xuexijianyi/gaokao-zhiyuan-cs.md) - [测试开发工程师必读经典书籍有哪些?](docs/xuexijianyi/test-programmer-read-books.md) - [校招 Java 后端开发应该掌握到什么程度?](docs/xuexijianyi/xiaozhao-java-should-master.md) - [大裁员下,程序员如何做“副业”?](docs/xuexijianyi/chengxuyuan-fuye.md) - [如何在繁重的工作中持续成长?](docs/xuexijianyi/ruhzfzdgzzcxcz.md) - [如何获得高并发的经验?](docs/xuexijianyi/gaobingfa-jingyan-hsmcomputer.md) - [怎么跟 HR 谈薪资?](docs/xuexijianyi/hr-xinzi.md) - [程序员 35 岁危机,如何破局?](docs/xuexijianyi/35-weiji.md) - [不到 20 人的 IT 公司该去吗?](docs/xuexijianyi/20ren-it-quma.md) - [本科生如何才能进入腾讯、阿里等一流的互联网公司?](docs/xuexijianyi/benkesheng-ali-tengxun.md) - [计算机考研 408 统考该如何准备?](docs/xuexijianyi/408.md) # 知识库搭建 > 从购买阿里云服务器+域名购买+域名备案+HTTP 升级到 HTTPS,全方面记录《二哥的Java进阶之路》知识库的诞生和改进过程,涉及到 docsify、Git、Linux 命令、GitHub 仓库等实用知识点。 - [购买云服务器](docs/szjy/buy-cloud-server.md) - [安装宝塔面板](docs/szjy/install-baota-mianban.md) - [购买域名&域名解析](docs/szjy/buy-domain.md) - [备案域名](docs/szjy/record-domain.md) - [给域名配置HTTPS证书](docs/szjy/https-domain.md) - [使用docsify+Git+GitHub+码云+阿里云服务器搭建知识库网站](docs/szjy/tobebetterjavaer-wangzhan-shangxian.md) 本知识库使用 VuePress 搭建,并基于[VuePress Theme Hope](https://theme-hope.vuejs.press/zh/)主题,你可以把[仓库](https://github.com/itwanger/toBeBetterJavaer)拉到本地后直接通过 `npm run docs:dev` 跑起来。 >前提是你已经安装好 node.js 和 npm 环境。 ![](https://cdn.tobebetterjavaer.com/stutymore/README-20230829162211.png) 点击链接就可以在本地看到运行后的效果了。 ![](https://cdn.tobebetterjavaer.com/stutymore/README-20230829162301.png) # 联系作者 >- 作者是一名普通普通普通普通三连的 Java 后端开发者,热爱学习,热爱分享 >- 参加工作以后越来越理解交流和分享的重要性,在不停地汲取营养的同时,也希望帮助到更多的小伙伴们 >- 二哥的Java进阶之路,不仅是作者自学 Java 以来所有的原创文章和学习资料的大聚合,更是作者向这个世界传播知识的一个窗口。 ## 心路历程 - [走近作者:个人介绍 Q&A](docs/about-the-author/readme.md) - [我的第一个,10 万(B站视频播放)](docs/about-the-author/bzhan-10wan.md) - [我的第一个,一千万!知乎阅读](docs/about-the-author/zhihu-1000wan.md) - [我的第二个,一千万!CSDN阅读](docs/about-the-author/csdn-1000wan.md) ## 联系方式 ### 原创公众号 GitHub 上标星 10000+ 的开源知识库《[二哥的 Java 进阶之路](https://github.com/itwanger/toBeBetterJavaer)》第一版 PDF 终于来了!包括Java基础语法、数组&字符串、OOP、集合框架、Java IO、异常处理、Java 新特性、网络编程、NIO、并发编程、JVM等等,共计 32 万余字,可以说是通俗易懂、风趣幽默……详情戳:[太赞了,GitHub 上标星 10000+ 的 Java 教程](https://javabetter.cn/overview/) 微信搜 **沉默王二** 或扫描下方二维码关注二哥的原创公众号沉默王二,回复 **222** 即可免费领取。 ![](https://cdn.tobebetterjavaer.com/tobebetterjavaer/images/gongzhonghao.png) ### star趋势图 [![Star History Chart](https://api.star-history.com/svg?repos=itwanger/toBeBetterJavaer&type=Date)](https://star-history.com/#itwanger/toBeBetterJavaer&Date) ### 友情链接 - [paicoding](https://github.com/itwanger/paicoding),⭐️一款好用又强大的开源社区,附详细教程,包括Java、Spring、MySQL、Redis、微服务&分布式、消息队列、操作系统、计算机网络、数据结构与算法等计算机专业核心知识点。学编程,就上技术派😁。 - [Hippo4J](https://github.com/acmenlt/dynamic-threadpool),🔥 强大的动态线程池,附带监控报警功能(没有依赖中间件),完全遵循阿里巴巴编码规范。 - [JavaGuide](https://github.com/Snailclimb/JavaGuide),「Java学习+面试指南」一份涵盖大部分 Java 程序员所需要掌握的核心知识。准备 Java 面试,首选 JavaGuide! ### 捐赠鼓励 开源不易,如果《二哥的Java进阶之路》对你有些帮助,可以请作者喝杯咖啡,算是对开源做出的一点点鼓励吧! <div align="left"> <img src="https://cdn.tobebetterjavaer.com/tobebetterjavaer/images/weixin-zhifu.png" width="260px"> </div> :gift_heart: 感谢大家对我资金的赞赏,每隔一个月会统计一次。 时间|小伙伴|赞赏金额 ---|---|--- 2024-02-29|r*y|6元 2024-02-23|*~|9.99元 2024-02-21|从头再来|5元 2024-02-15|*斗|10元 2024-02-02|*切|2元 2024-02-01|*康|9元 2024-01-31|*康|1元 2024-01-22|*妙|10元 2024-01-17|*清|9.9元 2024-01-12|*奥|5元 2024-01-04|*👈🏻|1元 2024-01-03|*|3元 2024-01-03|Y*o|2元 2023-12-22|*逗|50元 2023-11-25|*君|2元 2023-10-23|*🐻|6.66元 2023-10-17|*哈|5元 2023-10-12|0*7|7.77元 2023-10-03|S*d|0.5元 2023-09-27|*1|1元 2023-09-25|L*e|10.24元 2023-09-19|*人|2元 2023-09-15|L*D|2元 2023-09-15|*暖|5元 2023-09-11|A*B|1元 2023-08-21|*氏|2元 2023-08-18|*寻|1元 2023-08-03|*案|10.24元 2023-08-02|*,|1元 2023-07-24|m*l|3元 2023-07-20|lzy|6元 2023-07-14|s*!|2元 2023-07-02|*晴|1元 2023-06-26|*雨|6.66元 2023-06-21|*航|6元 2023-06-21|*狼|3元 2023-06-19|*定|2元 2023-06-18|*道|5元 2023-06-16|* 文|1元 2023-06-14|G*e|66.6元 2023-06-07|*.|0.5元 2023-05-23|*W|5元 2023-05-19|*飞|6元 2023-05-10|c*r|1元 2023-04-26|r*J|10.24元 2023-04-22|*明|1元 2023-04-09|* 刀|10元 2023-04-03|*意|0.02元 2023--03-17|*昌|8 元 2023-03-16|~*~|66.6 元 2023-03-15|*枫|6.6 元 2023-03-10|十年|1 元 2023-03-04|*风|5 元 2023-02-26|一个表情(emoji)|1 元 2023-02-23|曹*n|5元 2023-02-11|昵称加载中.|6.6元 2023-02-09|*明|10元 2023-02-09|*风|5元 2023-02-09|*z|3元 2023-02-09|*夫|10元 2023-02-08|*宝|5 元 2023-01-18|*念|0.01元 2023-01-18|*来|1元 2023-01-10|*A*t|1元 2023-01-07|*忠|5元 2023-12-02|g*g|0.1元 2022-11-13|*王|5元 2022-11-10|*车|1元 2022-11-10|F*k|1元 2022-11-05|*H|3元 2022-11-04|*金|0.02元 2022-11-04|*尘|15元 2022-11-02|*峰|1元 2022-10-29|~*~|6元 2022-10-28|k*k|1元 2022-10-20|*电|2元 2022-10-15|*深|5元 2022-09-30|*君|1元 2022-09-28|*懂|1元 2022-09-27|*府|1元 2022-09-23|*问号(emogji)|5元 2022-09-23|H*n|1元 2022-09-23|*a|0.01元 2022-09-08|*👀|20元 2022-09-07|丹*1|20元 2022-08-27|*夹|40元 2022-07-06|体*P|2元 2022-07-05|*谦|5元 2022-06-18|*杰|2元 2022-06-15|L*c|15元 2022-06-10|*❤|1元 2022-06-09|'*'|1元 2022-06-07|*勇|1元 2022-06-03|*鸭|1元 2022-05-12|*烟|10元 2022-04-25|*思|5元 2022-04-20|w*n|1元 2022-04-12|E*e|10 元 2022-03-19|*风|9.9元 2022-03-04|袁晓波|99元 2022-02-17|*色|1元 2022-02-17|M*y|1元 2022-01-28|G*R|6.6元 2022-01-20|*光|50元 2022-01-14|*浩|1元 2022-01-01|刚*好|3.6元 2022-01-01|马*谊|6.6元 2021-12-20|t*1|5 元 2021-10-26|*猫|28 元 2021-10-11|*人|28 元 2021-09-28|*人|1 元 2021-09-05|N*a|3 元 2021-09-02|S*n|6.6 元 2021-08-21|z*s|3 元 2021-08-20|A*g|10 元 2021-08-09|*滚|0.1 元 2021-08-02|*秒|1 元 2021-06-13|*7| 28 元 2021-05-04|*学|169 元 2021-04-29|p*e|2 元 2021-04-28|追风筝的神|1 元 ### 参与贡献 1. 如果你对本项目有任何建议或发现文中内容有误的,欢迎提交 issues 进行指正。 2. 对于文中我没有涉及到知识点,欢迎提交 PR。
0
Heeexy/SpringBoot-Shiro-Vue
提供一套基于Spring Boot-Shiro-Vue的权限管理思路.前后端都加以控制,做到按钮/接口级别的权限。(当前新版本已移除shiro依赖,简化了配置)
2017-11-17T18:49:06Z
null
# Spring Boot-Shiro-Vue 提供一套基于SpringBoot-shiro-vue的权限管理思路. 前后端都加以控制,做到按钮/接口级别的权限 # DEMO [测试地址](https://g.heeexy.com) admin/123456 管理员身份登录,可以新增用户,角色. 角色可以分配权限 控制菜单是否显示,新增/删除按钮是否显示 # 更新记录 v2.0.0 2021.05.09 1. 支持一个用户多个角色 2. 使用token作为登录凭证,不使用session,避免跨域问题 3. 使用自定义注解+aop 替代shiro的功能,简化了配置,增强了可拓展性 # 设计思路 ### 核心 每个登录用户拥有各自的N条权限,比如 文章:查看/编辑/发布/删除 ### 后端 基于 [RBAC新解](http://globeeip.iteye.com/blog/1236167) . 通常我们的权限设计都是 用户--角色--权限 ,其中**角色**是我们写代码的人没法控制的,它可以有多条权限,每个用户又可以设计为拥有多个角色.因此如果从角色着手进行权限验证,系统都必须根据用户的配置动起来,非常复杂. 所以我们后台设计的关键点就在于: **后台接口只验证权限,不看角色.** 角色的作用其实只是用来管理分配权限的,真正的验证只验证**权限** ,而不去管你是否是那种角色.体现在代码上就是接口上注解为 ```java @RequiresPermissions("article:add") ``` 而不是 ```java @RequiresRoles(value = {"admin","manager","writer"}, logical = Logical.OR) ``` ![api权限](https://img.heeexy.com/api-permission.png) ### 前端 采用了[vueAdmin-template](https://github.com/PanJiaChen/vueAdmin-template) , [ElementUI](https://github.com/ElemeFE/element) , 权限设计思路也是参考了 vueAdmin 的动态路由的设计. 后端负责了接口的安全性,而前端之所以要做权限处理,最主要的目的就是**隐藏掉不具有权限的菜单(路由)和按钮**. 登录系统后,后端返回此用户的权限信息,比如 ```json "userPermission":{ "menuList":[ "role", "user", "article" ], "roleId":1, "nickname":"超级用户", "roleName":"管理员", "permissionList":[ "article:list", "article:add", "user:list", ], "userId":10003 } ``` 根据**menuList**判断给此用户生成哪些路由, 根据**permissionList**判断给用户显示哪些按钮,能请求哪些接口. ### 数据库 最主要的是要有一张本系统内的全部权限明细表,比如下面这样 ![权限表](https://img.heeexy.com/permissionDatabase.png) ![权限数据](https://img.heeexy.com/permissionData.png) 如果某用户拥有表格中前五条权限,就可以查出他就拥有article和user两个菜单,至于页面内是否显示(新增)(修改)按钮,就根据他的permissionList来判断. ## 具体实现 有了思路,就可以根据各自的业务进行实现,本项目在此进行了简单的实现,后端代码在back文件夹,前端代码在vue文件夹.前端启动只需 ``` npm install npm run dev ``` 后端就是常规的shiro配置,前端代码如果看不明白,可以参考[前端权限代码说明](./explain-frontend.md) ## 分配权限页面效果 ![分配权限页面](https://img.heeexy.com/role_permission.png)
0
MisterBooo/LeetCodeAnimation
Demonstrate all the questions on LeetCode in the form of animation.(用动画的形式呈现解LeetCode题目的思路)
2018-12-06T08:01:22Z
null
null
0
hibernate/hibernate-orm
Hibernate's core Object/Relational Mapping functionality
2010-10-04T16:15:52Z
null
null
0
geoserver/geoserver
Official GeoServer repository
2011-11-10T19:56:06Z
null
<img src="/doc/en/themes/geoserver/static/GeoServer_500.png" width="353"> [![Gitter](https://badges.gitter.im/geoserver/geoserver.svg)](https://gitter.im/geoserver/geoserver?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![DOI](https://zenodo.org/badge/2751199.svg)](https://zenodo.org/badge/latestdoi/2751199) [GeoServer](https://geoserver.org) is an open source software server written in Java that allows users to share and edit geospatial data. Designed for interoperability, it publishes data from any major spatial data source using open standards. Being a community-driven project, GeoServer is developed, tested, and supported by a diverse group of individuals and organizations from around the world. GeoServer is the reference implementation of the Open Geospatial Consortium (OGC) Web Feature Service (WFS) and Web Coverage Service (WCS) standards, as well as a high performance certified compliant Web Map Service (WMS), compliant Catalog Service for the Web (CSW) and implementing Web Processing Service (WPS). GeoServer forms a core component of the Geospatial Web. ## License GeoServer licensed under the [GPL](https://docs.geoserver.org/latest/en/user/introduction/license.html). ## Using Please refer to the [user guide](https://docs.geoserver.org/latest/en/user/) for information on how to install and use GeoServer. ## Building GeoServer uses [Apache Maven](https://maven.apache.org/) for a build system. To build the application run maven from the ```src``` directory. mvn clean install See the [developer guide](https://docs.geoserver.org/latest/en/developer/) for more details. ## Bugs GeoServer uses [JIRA](https://osgeo-org.atlassian.net/projects/GEOS), hosted by [Atlassian](https://www.atlassian.com/), for issue tracking. ## Mailing Lists The [mailing list page](https://geoserver.org/comm/) on the GeoServer web site provides access to the various mailing list, as well as some indication of the [code of conduct](https://geoserver.org/comm/userlist-guidelines.html) when posting to the lists ## Contributing Please read [the contribution guidelines](https://github.com/geoserver/geoserver/blob/main/CONTRIBUTING.md) before contributing pull requests to the GeoServer project. ## More Information Visit the [website](https://geoserver.org/) or read the [docs](https://docs.geoserver.org/).
0
bazelbuild/bazel
a fast, scalable, multi-language and extensible build system
2014-06-12T16:00:38Z
null
# [Bazel](https://bazel.build) *{Fast, Correct} - Choose two* Build and test software of any size, quickly and reliably. * **Speed up your builds and tests**: Bazel rebuilds only what is necessary. With advanced local and distributed caching, optimized dependency analysis and parallel execution, you get fast and incremental builds. * **One tool, multiple languages**: Build and test Java, C++, Android, iOS, Go, and a wide variety of other language platforms. Bazel runs on Windows, macOS, and Linux. * **Scalable**: Bazel helps you scale your organization, codebase, and continuous integration solution. It handles codebases of any size, in multiple repositories or a huge monorepo. * **Extensible to your needs**: Easily add support for new languages and platforms with Bazel's familiar extension language. Share and re-use language rules written by the growing Bazel community. ## Getting Started * [Install Bazel](https://bazel.build/install) * [Get started with Bazel](https://bazel.build/start) * Follow our tutorials: - [Build C++](https://bazel.build/tutorials/cpp) - [Build Java](https://bazel.build/tutorials/java) - [Android](https://bazel.build/tutorials/android-app) - [iOS](https://github.com/bazelbuild/rules_apple/blob/master/doc/tutorials/ios-app.md) ## Documentation * [Bazel command line](https://bazel.build/docs/user-manual) * [Rule reference](https://bazel.build/reference/be/overview) * [Use the query command](https://bazel.build/reference/query) * [Extend Bazel](https://bazel.build/rules/concepts) * [Write tests](https://bazel.build/reference/test-encyclopedia) * [Roadmap](https://bazel.build/community/roadmaps) * [Who is using Bazel?](https://bazel.build/community/users) ## Reporting a Vulnerability To report a security issue, please email security@bazel.build with a description of the issue, the steps you took to create the issue, affected versions, and, if known, mitigations for the issue. Our vulnerability management team will respond within 3 working days of your email. If the issue is confirmed as a vulnerability, we will open a Security Advisory. This project follows a 90 day disclosure timeline. ## Contributing to Bazel See [CONTRIBUTING.md](CONTRIBUTING.md) [![Build status](https://badge.buildkite.com/1fd282f8ad98c3fb10758a821e5313576356709dd7d11e9618.svg?status=master)](https://buildkite.com/bazel/bazel-bazel)
0
apache/fineract
Apache Fineract
2015-12-22T08:00:06Z
null
Apache Fineract: A Platform for Microfinance ============ [![Swagger Validation](https://validator.swagger.io/validator?url=https://sandbox.mifos.community/fineract-provider/swagger-ui/fineract.yaml)](https://validator.swagger.io/validator/debug?url=https://sandbox.mifos.community/fineract-provider/swagger-ui/fineract.yaml) [![build](https://github.com/apache/fineract/actions/workflows/build.yml/badge.svg)](https://github.com/apache/fineract/actions/workflows/build.yml) [![Docker Hub](https://img.shields.io/docker/pulls/apache/fineract.svg?logo=Docker)](https://hub.docker.com/r/apache/fineract) [![Docker Build](https://img.shields.io/docker/cloud/build/apache/fineract.svg?logo=Docker)](https://hub.docker.com/r/apache/fineract/builds) [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=apache_fineract&metric=sqale_index)](https://sonarcloud.io/summary/new_code?id=apache_fineract) </b> Fineract is a mature platform with open APIs that provides a reliable, robust, and affordable core banking solution for financial institutions offering services to the world’s 3 billion underbanked and unbanked. [Have a look at the FAQ on our Wiki at apache.org](https://cwiki.apache.org/confluence/display/FINERACT/FAQ) if this README does not answer what you are looking for. [Visit our JIRA Dashboard](https://issues.apache.org/jira/secure/Dashboard.jspa?selectPageId=12335824) to find issues to work on, see what others are working on, or open new issues. [![Code Now! (Gitpod)](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/apache/fineract) to start contributing to this project in the online web-based IDE GitPod.io right away! (You may initially have to press F1 to Find Command and run "Java: Start Language Server".) It's of course also possible to contribute with a "traditional" local development environment (see below). COMMUNITY ========= If you are interested in contributing to this project, but perhaps don't quite know how and where to get started, please [join our developer mailing list](http://fineract.apache.org/#contribute), listen into our conversations, chime into threads, and just send us a "Hello!" introduction email; we're a friendly bunch, and look forward to hearing from you. REQUIREMENTS ============ * `Java >= 17` (Azul Zulu JVM is tested by our CI on GitHub Actions) * MariaDB `11.2` You can run the required version of the database server in a container, instead of having to install it, like this: docker run --name mariadb-11.2 -p 3306:3306 -e MARIADB_ROOT_PASSWORD=mysql -d mariadb:11.2 and stop and destroy it like this: docker rm -f mariadb-11.2 <br>Beware that this database container database keeps its state inside the container and not on the host filesystem. It is lost when you destroy (rm) this container. This is typically fine for development. See [Caveats: Where to Store Data on the database container documentation](https://hub.docker.com/_/mariadb) re. how to make it persistent instead of ephemeral.<br> Tomcat v9 is only required if you wish to deploy the Fineract WAR to a separate external servlet container. Note that you do not require to install Tomcat to develop Fineract, or to run it in production if you use the self-contained JAR, which transparently embeds a servlet container using Spring Boot. (Until FINERACT-730, Tomcat 7/8 were also supported, but now Tomcat 9 is required.) <br>IMPORTANT: If you use MySQL or MariaDB ============ Recently (after release `1.7.0`), we introduced improved date time handling in Fineract. Date time is from now on stored in UTC and we are enforcing UTC timezone even on the JDBC driver, e. g. for MySQL: ``` serverTimezone=UTC&useLegacyDatetimeCode=false&sessionVariables=time_zone=‘-00:00’ ``` __DO__: If you do use MySQL as your Fineract database then the following configuration is highly recommended: * Run the application in UTC (the default command line in our Docker image has the necessary parameters already set) * Run the MySQL database server in UTC (if you use managed services like AWS RDS then this should be the default anyway, but it would be good to double-check) __DON'T__: In case the Fineract instance and the MySQL server are __not__ running in UTC then the following could happen: * MySQL is saving date time values differently from PostgreSQL * Example scenario: if the Fineract instance runs in timezone: GMT+2, and the local date time is 2022-08-11 17:15 ... * ... then __PostgreSQL saves__ the LocalDateTime as is: __2022-08-11 17:15__ * ... and __MySQL saves__ the LocalDateTime in UTC: __2022-08-11 15:15__ * ... but when we __read__ the date time from PostgreSQL __or__ from MySQL, then both systems give us the same values: __2022-08-11 17:15 GMT+2__ If a previously used Fineract instance didn't run in UTC (backward compatibility), then all prior dates will be read wrongly by MySQL/MariaDB. This can cause issues when you run the database migration scripts. __RECOMMENDATION__: you need to shift all dates in your database by the timezone offset that your Fineract instance used. <br>INSTRUCTIONS: How to run for local development ============ Run the following commands: 1. `./gradlew createDB -PdbName=fineract_tenants` 1. `./gradlew createDB -PdbName=fineract_default` 1. `./gradlew bootRun` <br>INSTRUCTIONS: How to build the JAR file ============ 1. Clone the repository or download and extract the archive file to your local directory. 2. Run `./gradlew clean bootJar` to build a modern cloud native fully self contained JAR file which will be created at `fineract-provider/build/libs` directory. 3. As we are not allowed to include a JDBC driver in the built JAR, download a JDBC driver of your choice. For example: `wget https://downloads.mariadb.com/Connectors/java/connector-java-3.3.2/mariadb-java-client-3.3.2.jar` 4. Start the jar and pass the directory where you have downloaded the JDBC driver as loader.path, for example: `java -Dloader.path=. -jar fineract-provider/build/libs/fineract-provider.jar` (does not require external Tomcat) NOTE: we cannot upgrade to version 3.0.x of the MariaDB driver just yet; have to wait until 3.0.4 is out for a bug fix. The tenants database connection details are configured [via environment variables (as with Docker container)](#instructions-to-run-using-docker-and-docker-compose), e.g. like this: export FINERACT_HIKARI_PASSWORD=verysecret ... java -jar fineract-provider.jar <br>SECURITY ============ NOTE: The HTTP Basic and OAuth2 authentication schemes are mutually exclusive. You can't enable them both at the same time. Fineract checks these settings on startup and will fail if more than one authentication scheme is enabled. HTTP Basic Authentication ------------ By default Fineract is configured with a HTTP Basic Authentication scheme, so you actually don't have to do anything if you want to use it. But if you would like to explicitly choose this authentication scheme then there are two ways to enable it: 1. Use environment variables (best choice if you run with Docker Compose): ``` FINERACT_SECURITY_BASICAUTH_ENABLED=true FINERACT_SECURITY_OAUTH_ENABLED=false ``` 2. Use JVM parameters (best choice if you run the Spring Boot JAR): ``` java -Dfineract.security.basicauth.enabled=true -Dfineract.security.oauth.enabled=false -jar fineract-provider.jar ``` <br>OAuth2 AUTHENTICATION ------------ There is also an OAuth2 authentication scheme available. Again, two ways to enable it: 1. Use environment variables (best choice if you run with Docker Compose): ``` FINERACT_SECURITY_BASICAUTH_ENABLED=false FINERACT_SECURITY_OAUTH_ENABLED=true ``` 2. Use JVM parameters (best choice if you run the Spring Boot JAR): ``` java -Dfineract.security.basicauth.enabled=false -Dfineract.security.oauth.enabled=true -jar fineract-provider.jar ``` TWO FACTOR AUTHENTICATION (2FA) ------------ You can also enable 2FA authentication. Depending on how you start Fineract add the following: 1. Use environment variable (best choice if you run with Docker Compose): ``` FINERACT_SECURITY_2FA_ENABLED=true ``` 2. Use JVM parameter (best choice if you run the Spring Boot JAR): ``` -Dfineract.security.2fa.enabled=true ``` <br>INSTRUCTIONS: How to build a WAR file ============ 1. Clone the repository or download and extract the archive file to your local directory. 2. Run `./gradlew :fineract-war:clean :fineract-war:war` to build a traditional WAR file which will be created at `fineract-war/build/libs` directory. 3. Deploy this WAR to your Tomcat v9 Servlet Container. We recommend using the JAR instead of the WAR file deployment, because it's much easier. Note that with the 1.4 release the tenants database pool configuration changed from Tomcat DBCP in XML to an embedded Hikari, configured by environment variables, see above. INSTRUCTIONS: How to execute Integration Tests ============ > Note that if this is the first time to access MySQL DB, then you may need to reset your password. Run the following commands: 1. `./gradlew createDB -PdbName=fineract_tenants` 1. `./gradlew createDB -PdbName=fineract_default` 1. `./gradlew clean test` INSTRUCTIONS: How to run and debug in Eclipse IDE ============ It is possible to run Fineract in Eclipse IDE and also to debug Fineract using Eclipse's debugging facilities. To do this, you need to create the Eclipse project files and import the project into an Eclipse workspace: 1. Create Eclipse project files into the Fineract project by running `./gradlew cleanEclipse eclipse` 2. Import the fineract-provider project into your Eclipse workspace (File->Import->General->Existing Projects into Workspace, choose root directory fineract/fineract-provider) 3. Do a clean build of the project in Eclipse (Project->Clean...) 3. Run / debug Fineract by right clicking on org.apache.fineract.ServerApplication class and choosing Run As / Debug As -> Java Application. All normal Eclipse debugging features (breakpoints, watchpoints etc) should work as expected. If you change the project settings (dependencies etc) in Gradle, you should redo step 1 and refresh the project in Eclipse. You can also use Eclipse Junit support to run tests in Eclipse (Run As->Junit Test) Finally, modifying source code in Eclipse automatically triggers hot code replace to a running instance, allowing you to immediately test your changes INSTRUCTIONS: How to run using Docker and docker-compose =================================================== It is possible to do a 'one-touch' installation of Fineract using containers (AKA "Docker"). Fineract now packs the mifos community-app web UI in it's docker deploy. You can now run and test fineract with a GUI directly from the combined docker builds. This includes the database running in a container. As Prerequisites, you must have `docker` and `docker-compose` installed on your machine; see [Docker Install](https://docs.docker.com/install/) and [Docker Compose Install](https://docs.docker.com/compose/install/). Alternatively, you can also use [Podman](https://github.com/containers/libpod) (e.g. via `dnf install podman-docker`), and [Podman Compose](https://github.com/containers/podman-compose/) (e.g. via `pip3 install podman-compose`) instead of Docker. Now to run a new Fineract instance you can simply: 1. `git clone https://github.com/apache/fineract.git ; cd fineract` 1. for windows, use `git clone https://github.com/apache/fineract.git --config core.autocrlf=input ; cd fineract` 1. `./gradlew :fineract-provider:jibDockerBuild -x test` 1. install the Loki log driver with `docker plugin install grafana/loki-docker-driver:latest --alias loki --grant-all-permissions` 1. `docker compose -f docker-compose-development.yml up -d` 1. fineract (back-end) is running at https://localhost:8443/fineract-provider/ 1. wait for https://localhost:8443/fineract-provider/actuator/health to return `{"status":"UP"}` 1. you must go to https://localhost:8443 and remember to accept the self-signed SSL certificate of the API once in your browser, otherwise you get a message that is rather misleading from the UI. 1. community-app (UI) is running at http://localhost:9090/?baseApiUrl=https://localhost:8443/fineract-provider&tenantIdentifier=default 1. login using default _username_ `mifos` and _password_ `password` https://hub.docker.com/r/apache/fineract has a pre-built container image of this project, built continuously. You must specify the MySQL tenants database JDBC URL by passing it to the `fineract` container via environment variables; please consult the [`docker-compose.yml`](docker-compose.yml) for exact details how to specify those. _(Note that in previous versions, the `mysqlserver` environment variable used at `docker build` time instead of at `docker run` time did something similar; this has changed in [FINERACT-773](https://issues.apache.org/jira/browse/FINERACT-773)), and the `mysqlserver` environment variable is now no longer supported.)_ The logfiles and the Java Flight Recorder output are available in `PROJECT_ROOT/build/fineract/logs`. If you use IntelliJ then you can double-click on the `.jfr` file and open it with the IDE. You can also download Azul Mission Control from here https://www.azul.com/products/components/azul-mission-control/ to analyze the Java Flight Recorder file. NOTE: If you have issues with the file permissions and Docker Compose then you might need to change the variable values for `FINERACT_USER` and `FINERACT_GROUP` in `PROJECT_ROOT/config/docker/env/fineract-common.env`. You can find out what values you need to put there with the following commands: ``` id -u ${USER} id -u ${GROUP} ``` Please make sure that you are not checking in your changed values. The defaults should normally work for most people. Connection pool configuration ============================= Please check `application.properties` to see which connection pool settings can be tweaked. The associated environment variables are prefixed with `FINERACT_HIKARI_*`. You can find more information about specific connection pool settings (Hikari) at https://github.com/brettwooldridge/HikariCP#configuration-knobs-baby NOTE: we'll keep backwards compatibility until one of the next releases to ensure that things are working as expected. Environment variables prefixed `fineract_tenants_*` can still be used to configure the database connection, but we strongly encourage using `FINERACT_HIKARI_*` with more options. <br>SSL CONFIGURATION ================= Read also [the HTTPS related doc](fineract-doc/src/docs/en/deployment.adoc#https). By default SSL is enabled, but all SSL related properties are now tunable. SSL can be turned off by setting the environment variable `FINERACT_SERVER_SSL_ENABLED` to false. If you do that then please make sure to also change the server port to `8080` via the variable `FINERACT_SERVER_PORT`, just for the sake of keeping the conventions. You can choose now easily a different SSL keystore by setting `FINERACT_SERVER_SSL_KEY_STORE` with a path to a different (not embedded) keystore. The password can be set via `FINERACT_SERVER_SSL_KEY_STORE_PASSWORD`. See the `application.properties` file and the latest Spring Boot documentation (https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html) for more details. <br>TOMCAT CONFIGURATION ==================== Please refer to the `application.properties` and the official Spring Boot documentation (https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html) on how to do performance tuning for Tomcat. Note: you can set now the acceptable form POST size (default is 2MB) via environment variable `FINERACT_SERVER_TOMCAT_MAX_HTTP_FORM_POST_SIZE`. <br>INSTRUCTIONS: How to run on Kubernetes ================================= <br>General Clusters ---------------- You can also run Fineract using containers on a Kubernetes cluster. Make sure you set up and connect to your Kubernetes cluster. You can follow [this](https://cwiki.apache.org/confluence/display/FINERACT/Install+and+configure+kubectl+and+Google+Cloud+SDK+on+ubuntu+16.04) guide to set up a Kubernetes cluster on GKE. Make sure to replace `apache-fineract-cn` with `apache-fineract` Now e.g. from your Google Cloud shell, run the following commands: 1. `git clone https://github.com/apache/fineract.git ; cd fineract/kubernetes` 1. `./kubectl-startup.sh` To shutdown and reset your Cluster, run: ./kubectl-shutdown.sh Using Minikube -------------- Alternatively, you can run fineract on a local kubernetes cluster using [minikube](https://minikube.sigs.k8s.io/docs/). As Prerequisites, you must have `minikube` and `kubectl` installed on your machine; see [Minikube & Kubectl install](https://kubernetes.io/docs/tasks/tools/install-minikube/). Now to run a new Fineract instance on Minikube you can simply: 1. `git clone https://github.com/apache/fineract.git ; cd fineract/kubernetes` 1. `minikube start` 1. `./kubectl-startup.sh` 1. `minikube service fineract-server --url --https` 1. Fineract is now running at the printed URL (note HTTP), which you can check e.g. using: http --verify=no --timeout 240 --check-status get $(minikube service fineract-server --url --https)/fineract-provider/actuator/health To check the status of your containers on your local minikube Kubernetes cluster, run: minikube dashboard You can check Fineract logs using: kubectl logs deployment/fineract-server To shutdown and reset your cluster, run: ./kubectl-shutdown.sh To shutdown and reset your cluster, run: minikube ssh sudo rm -rf /mnt/data/ We have [some open issues in JIRA with Kubernetes related enhancement ideas](https://jira.apache.org/jira/browse/FINERACT-783?jql=labels%20%3D%20kubernetes%20AND%20project%20%3D%20%22Apache%20Fineract%22%20) which you are welcome to contribute to. INSTRUCTIONS: How to download Gradle wrapper ============ The file gradle/wrapper/gradle-wrapper.jar binary is checked into this projects Git source repository, but won't exist in your copy of the Fineract codebase if you downloaded a released source archive from apache.org. In that case, you need to download it using the commands below: wget --no-check-certificate -P gradle/wrapper https://github.com/apache/fineract/raw/develop/gradle/wrapper/gradle-wrapper.jar (or) curl --insecure -L https://github.com/apache/fineract/raw/develop/gradle/wrapper/gradle-wrapper.jar > gradle/wrapper/gradle-wrapper.jar INSTRUCTIONS: How to run Apache RAT (Release Audit Tool) ============ 1. Extract the archive file to your local directory. 2. Run `./gradlew rat`. A report will be generated under build/reports/rat/rat-report.txt INSTRUCTIONS: How to enable External Message Broker (ActiveMQ or Apache Kafka) ============ There are two use-cases where external message broker is needed: - External Business Events / Reliable Event Framework - Executing Partitioned Spring Batch Jobs External Events are business events, e.g.: `ClientCreated`, which might be important for third party systems. Apache Fineract supports ActiveMQ (or other JMS compliant brokers) and Apache Kafka endpoints for sending out Business Events. By default, they are not emitted. In case of a large deployment with millions of accounts, the Close of Business Day Spring Batch job may run several hours. In order to speed up this task, remote partitioning of the job is supported. The Manager node partitions (breaks up) the COB job into smaller pieces (sub tasks) which then can be executed on multiple Worker nodes in parallel. The worker nodes are notified either by ActiveMQ or Kafka regarding their new sub tasks. ### Active MQ JMS based messaging is disabled by default. In `docker-compose-postgresql-activemq.yml` an example is shown where ActiveMQ is enabled. In that configuration one Spring Batch Manager instance and two Spring Batch Worker instances are created. Spring based events should be disabled and jms based event handling should be enabled. Furthermore, proper broker JMS URL should be configured. ``` FINERACT_REMOTE_JOB_MESSAGE_HANDLER_JMS_ENABLED=true FINERACT_REMOTE_JOB_MESSAGE_HANDLER_SPRING_EVENTS_ENABLED=false FINERACT_REMOTE_JOB_MESSAGE_HANDLER_JMS_BROKER_URL=tcp://activemq:61616 ``` For additional ActiveMQ related configuration please take a look to the `application.properties` where the supported configuration parameters are listed with their default values. ### Kafka Kafka support also disabled by default. In `docker-compose-postgresql-kafka.yml` an example is shown where self-hosted Kafka is enabled for both External Events and Spring Batch Remote Job execution. During the development Fineract was tested with PLAINTEXT Kafka brokers without authentication and with AWS MSK using IAM authentication. The extra [jar file](https://github.com/aws/aws-msk-iam-auth/releases) required for IAM authentication is already added to the classpath. An example MSK setup can be found in `docker-compose-postgresql-kafka-msk.yml`. The full list of supported Kafka related properties are documented here: https://fineract.apache.org/docs/current/ Checkstyle and Spotless ============ This project enforces its code conventions using [checkstyle.xml](config/checkstyle/checkstyle.xml) through Checkstyle and [fineract-formatting-preferences.xml](config/fineract-formatting-preferences.xml) through Spotless. They are configured to run automatically during the normal Gradle build, and fail if there are any violations detected. You can run the following command to automatically fix spotless violations: `./gradlew spotlessApply` Since some checks are present in both Checkstyle and Spotless, the same command can help you fix some of the Checkstyle violations (but not all, other Checkstyle violations need to fixed manually). You can also check for Spotless violations (only; but normally don't have to, because the regular build full already includes this anyway): `./gradlew spotlessCheck` We recommend that you configure your favourite Java IDE to match those conventions. For Eclipse, you can go to Window > Java > Code Style and import our [config/fineractdev-formatter.xml](config/fineractdev-formatter.xml) under formatter section and [config/fineractdev-cleanup.xml](config/fineractdev-cleanup.xml) under Clean up section. The same fineractdev-formatter.xml configuration file (that can be used in Eclipse IDE) is also used by Spotless to both check for violations and autoformat code on the CLI. You could also use Checkstyle directly in your IDE (but you don't neccesarily have to, it may just be more convenient for you). For Eclipse, use https://checkstyle.org/eclipse-cs/ and load our checkstyle.xml into it, for IntelliJ you can use [CheckStyle-IDEA](https://plugins.jetbrains.com/plugin/1065-checkstyle-idea). Code Coverage Reports ============ The project uses Jacoco to measure unit tests code coverage, to generate a report run the following command: `./gradlew clean build jacocoTestReport` Generated reports can be found in build/code-coverage directory. Versions ============ The latest stable release can be viewed on the develop branch: [Latest Release on Develop](https://github.com/apache/fineract/tree/develop "Latest Release"). The progress of this project can be viewed here: [View change log](https://github.com/apache/fineract/blob/develop/CHANGELOG.md "Latest release change log") License ============ This project is licensed under Apache License Version 2.0. See <https://github.com/apache/incubator-fineract/blob/develop/LICENSE.md> for reference. The Connector/J JDBC Driver client library from MariaDB.org, which is licensed under the LGPL, is used in development when running integration tests that use the Liquibase library. That JDBC driver is however not included in and distributed with the Fineract product and is not required to use the product. If you are developer and object to using the LGPL licensed Connector/J JDBC driver, simply do not run the integration tests that use the Liquibase library and/or use another JDBC driver. As discussed in [LEGAL-462](https://issues.apache.org/jira/browse/LEGAL-462), this project therefore complies with the [Apache Software Foundation third-party license policy](https://www.apache.org/legal/resolved.html). <br><br>APACHE FINERACT PLATFORM API ============ The API for Fineract is documented in [apiLive.htm](fineract-provider/src/main/resources/static/legacy-docs/apiLive.htm), and the [apiLive.htm can be viewed on fineract.apache.org](https://fineract.apache.org/docs/legacy/ "API Documentation"). If you have your own Fineract instance running, you can find this documentation under [/fineract-provider/legacy-docs/apiLive.htm](https://localhost:8443/fineract-provider/legacy-docs/apiLive.htm). The Swagger documentation (work in progress; see [FINERACT-733](https://issues.apache.org/jira/browse/FINERACT-733)) can be accessed under [/fineract-provider/swagger-ui/index.html](https://localhost:8443/fineract-provider/swagger-ui/index.html) and [live Swagger UI here on Fineract.dev](https://sandbox.mifos.community/fineract-provider/swagger-ui/index.html). Apache Fineract supports client code generation using [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) based on the [OpenAPI Specification](https://swagger.io/specification/). For more instructions on how to generate the client code, check [docs/developers/swagger/client.md](docs/developers/swagger/client.md). <br>API CLIENTS (Web UIs, Mobile, etc.) ============ * https://github.com/openMF/community-app/ is the "traditional" Reference Client App Web UI for the API offered by this project * https://github.com/openMF/web-app is the next generation UI rewrite also using this project's API * https://github.com/openMF/android-client is an Android Mobile App client for this project's API * https://github.com/openMF has more related proejcts <br>ONLINE DEMOS ============ * [sandbox.mifos.community](https://sandbox.mifos.community) always runs the latest version of this code * [demo.mifos.io](https://demo.mifos.io) A demo account is provided for users to experience the functionality of the Community App. Users can use "mifos" for USERNAME and "password" for PASSWORD (without quotation marks). * [Swagger-UI Demo video](https://www.youtube.com/watch?v=FlVd-0YAo6c) This is a demo video for Swagger-UI documentation, more information [here](https://github.com/apache/fineract#swagger-ui-documentation). <br>DEVELOPERS ============ Please see <https://cwiki.apache.org/confluence/display/FINERACT/Contributor%27s+Zone> for the developers wiki page. Please refer to <https://cwiki.apache.org/confluence/display/FINERACT/Fineract+101> for the first-time contribution to this project. Please see <https://cwiki.apache.org/confluence/display/FINERACT/How-to+articles> for technical details to get started. Please visit [our JIRA Dashboard](https://issues.apache.org/jira/secure/Dashboard.jspa?selectPageId=12335824) to find issues to work on, see what others are working on, or open new issues. <br>VIDEO DEMONSTRATION ============ Apache Fineract / Mifos X Demo (November 2016) - <https://www.youtube.com/watch?v=h61g9TptMBo> <br>SWAGGER UI DEMONSTRATION ============ We use Swagger-UI to generate and maintain our API documentation, you can see the demo video [here](https://www.youtube.com/watch?v=FlVd-0YAo6c) or a live version [here](https://sandbox.mifos.community/fineract-provider/swagger-ui/index.html). If you interested to know more about Swagger-UI you can check their [website](https://swagger.io/). <br>GORVENANCE AND POLICIES ======================= [Becoming a Committer](https://cwiki.apache.org/confluence/display/FINERACT/Becoming+a+Committer) documents the process through which you can become a committer in this project. <br>ERROR HANDLING GUIDELINES ------------------ * When catching exceptions, either rethrow them, or log them. Either way, include the root cause by using `catch (SomeException e)` and then either `throw AnotherException("..details..", e)` or `LOG.error("...context...", e)`. * Completely empty catch blocks are VERY suspicous! Are you sure that you want to just "swallow" an exception? Really, 100% totally absolutely sure?? ;-) Such "normal exceptions which just happen sometimes but are actually not really errors" are almost always a bad idea, can be a performance issue, and typically are an indication of another problem - e.g. the use of a wrong API which throws an Exception for an expected condition, when really you would want to use another API that instead returns something empty or optional. * In tests, you'll typically never catch exceptions, but just propagate them, with `@Test void testXYZ() throws SomeException, AnotherException`..., so that the test fails if the exception happens. Unless you actually really want to test for the occurence of a problem - in that case, use [JUnit's Assert.assertThrows()](https://github.com/junit-team/junit4/wiki/Exception-testing) (but not `@Test(expected = SomeException.class)`). * Never catch `NullPointerException` & Co. <br>LOGGING GUIDELINES ------------------ * We use [SLF4J](http://www.slf4j.org) as our logging API. * Never, ever, use `System.out` and `System.err` or `printStackTrace()` anywhere, but always `LOG.info()` or `LOG.error()` instead. * Use placeholder (`LOG.error("Could not... details: {}", something, exception)`) and never String concatenation (`LOG.error("Could not... details: " + something, exception)`) * Which Log Level is appropriate? * `LOG.error()` should be used to inform an "operator" running Fineract who supervises error logs of an unexpected condition. This includes technical problems with an external "environment" (e.g. can't reach a database), and situations which are likely bugs which need to be fixed in the code. They do NOT include e.g. validation errors for incoming API requests - that is signaled through the API response - and does (should) not be logged as an error. (Note that there is no _FATAL_ level in SLF4J; a "FATAL" event should just be logged as an _ERROR_.) * `LOG.warn()` should be using sparingly. Make up your mind if it's an error (above) - or not! * `LOG.info()` can be used notably for one-time actions taken during start-up. It should typically NOT be used to print out "regular" application usage information. The default logging configuration always outputs the application INFO logs, and in production under load, there's really no point to constantly spew out lots of information from frequently traversed paths in the code about what's going on. (Metrics are a better way.) `LOG.info()` *can* be used freely in tests though. * `LOG.debug()` can be used anywhere in the code to log things that may be useful during investigations of specific problems. They are not shown in the default logging configuration, but can be enabled for troubleshooting. Developers should typically "turn down" most `LOG.info()` which they used while writing a new feature to "follow along what happens during local testing" to `LOG.debug()` for production before we merge their PRs. * `LOG.trace()` is not used in Fineract. Pull Requests ------------- We request that your commit message include a FINERACT JIRA issue, recommended to be put in parentheses at the end of the first line. Start with an upper case imperative verb (not past form), and a short but concise clear description. (E.g. _Add enforced HideUtilityClassConstructor checkstyle (FINERACT-821)_ or _Fix inability to reschedule when interest accrued larger than EMI (FINERACT-1109)_ etc.). If your PR is failing to pass our CI build due to a test failure, then: 1. Understand if the failure is due to your PR or an unrelated unstable test. 1. If you suspect it is because of a "flaky" test, and not due to a change in your PR, then please do not simply wait for an active maintainer to come and help you, but instead be a proactive contributor to the project - see next steps. Do understand that we may not review PRs that are not green - it is the contributor's (that's you!) responsability to get a proposed PR to pass the build, not primarily the maintainers. 1. Search for the name of the failed test on https://issues.apache.org/jira/, e.g. for `AccountingScenarioIntegrationTest` you would find [FINERACT-899](https://issues.apache.org/jira/browse/FINERACT-899). 1. If you happen to read in such bugs that tests were just recently fixed, or ignored, then rebase your PR to pick up that change. 1. If you find previous comments "proving" that the same test has arbitrarily failed in at least 3 past PRs, then please do yourself raise a small separate new PR proposing to add an `@Disabled // TODO FINERACT-123` to the respective unstable test (e.g. [#774](https://github.com/apache/fineract/pull/774)) with the commit message mentioning said JIRA, as always. (Please do NOT just `@Disabled` any existing tests mixed in as part of your larger PR.) 1. If there is no existing JIRA for the test, then first please evaluate whether the failure couldn't be a (perhaps strange) impact of the change you are proposing after all. If it's not, then please raise a new JIRA to document the suspected Flaky Test, and link it to [FINERACT-850](https://issues.apache.org/jira/browse/FINERACT-850). This will allow the next person coming along hitting the same test failure to easily find it, and eventually propose to ignore the unstable test. 1. Then (only) Close and Reopen your PR, which will cause a new build, to see if it passes. 1. Of course, we very much appreciate you then jumping onto any such bugs and helping us figure out how to fix all ignored tests! [Pull Request Size Limit](https://cwiki.apache.org/confluence/display/FINERACT/Pull+Request+Size+Limit) documents that we cannot accept huge "code dump" Pull Requests, with some related suggestions. Guideline for new Feature commits involving Refactoring: If you are submitting PR for a new Feature, and it involves refactoring, try to differentiate "new Feature code" with "Refactored" by placing them in different commits. This helps review to review your code faster. We have an automated Bot which marks pull requests as "stale" after a while, and ultimately automatically closes them. Merge Strategy -------------- This project's committers typically prefer to bring your Pull Requests in through _Rebase and Merge_ instead of _Create a Merge Commit_. (If you are unfamiliar with GitHub's UI re. this, note the somewhat hidden little triangle drop-down at the bottom of PR, visible only to committers, not contributors.) This avoids the "merge commits" which we consider to be somewhat "polluting" the projects commits log history view. We understand this doesn't give an easy automatic reference to the original PR (which GitHub automatically adds to the Merge Commit message it generates), but we consider this an only very minor inconvenience; it's typically relatively easy to find the original PR even just from the commit message, and JIRA. We expect most proposed PRs to typically consist of a single commit. Committers may use _Squash and merge_ to combine your commits at merge time, and if they do so will rewrite your commit message as they see fit. Neither of these two are hard absolute rules, but mere conventions. Multiple commits in single PR make sense in certain cases (e.g. branch backports). Dependency Upgrades ------------------- This project uses a number of 3rd-party libraries, and this section provides some guidance for their updates. We have set-up [Renovate's bot](https://renovate.whitesourcesoftware.com) to automatically raise Pull Requests for our review when new dependencies are available [FINERACT-962](https://issues.apache.org/jira/browse/FINERACT-962). Upgrades sometimes require package name changes. Changed code should ideally have test coverage. Our `ClasspathHellDuplicatesCheckRuleTest` detects classes that appear in more than 1 JAR. If a version bump in [`build.gradle`](https://github.com/search?q=repo%3Aapache%2Ffineract+filename%3Abuild.gradle&type=Code&ref=advsearch&l=&l=) causes changes in transitives dependencies, then you may have to add related `exclude` to our [`dependencies.gradle`](https://github.com/apache/fineract/search?q=dependencies.gradle). Running `./gradlew dependencies` helps to understand what is required. More Information ============ More details of the project can be found at <https://cwiki.apache.org/confluence/display/FINERACT>.
0
wkeyuan/DWSurvey
Survey System. 最好用的开源问卷调查系统、表单系统。
2017-06-11T06:54:35Z
null
# 调问开源问卷系统(DWSurvey) 此代码仓库为基于 Spring Boot、Vue 实现的后端仓库 [![star](https://gitee.com/wkeyuan/DWSurvey/badge/star.svg?theme=dark)](https://gitee.com/wkeyuan/DWSurvey/stargazers) [![fork](https://gitee.com/wkeyuan/DWSurvey/badge/fork.svg?theme=dark)](https://gitee.com/wkeyuan/DWSurvey/members) ![GitHub Repo stars](https://img.shields.io/github/stars/wkeyuan/DWSurvey?style=social) ![GitHub forks](https://img.shields.io/github/forks/wkeyuan/DWSurvey?style=social) DWSurvey是一款简单、高效、成熟、稳定、专业的开源问卷系统,自2012年启动至今经过9年的积累,已经形成一套完善的基于 JAVA WEB 的开源问卷表单解决方案。 <div style="padding: 10px;border-left:solid 6px #278bee;background: #f3f5f7;font-size: 16px;color: #2c3e50;"> <div style="font-weight: 600;padding: 10px;"> 🎉🎉🎉 企业版 </div> <div> 全新的 <strong>企业版</strong> 已经发布,前后端分别采用 React(Ant design)、VUE(Element)、Spring Boot,详情可前往体验 <p>调问网官网地址:<a href="https://www.diaowen.net">https://www.diaowen.net</a></p> <p><strong>企业版体验地址</strong></p> <p><strong>新版本:<a href="https://element-ent.surveyform.cn">https://element-ent.surveyform.cn</a></strong>账号密码(service@diaowen.net/123456)</p> <p><strong>原版本:<a href="https://ent.surveyform.cn">https://ent.surveyform.cn</a></strong></p> </div> </div> <hr/> <div style="padding: 10px;border-left:solid 6px #278bee;background: #f3f5f7;font-size: 16px;color: #2c3e50;"> <div style="font-weight: 600;padding: 10px;"> 🎉🎉🎉 专业版 </div> <div> 新一代的 <strong>专业版</strong> 即将发布,前端采用<strong>纯VUE实现</strong>(Element)、后端使用 Spring Boot、Elasticsearch,敬请关注 <p>调问网官网地址:<a href="https://www.diaowen.net">https://www.diaowen.net</a></p> </div> </div> <hr/> <div style="padding: 10px;border-left:solid 6px #42b983;background: #f3f5f7;font-size: 16px;color: #2c3e50;"> <div style="font-weight: 600;padding: 10px;"> ☀️☀️☀️ 社区版 </div> <div> ️ 全新的 <strong>社区版</strong> 也已经发布,前后端分别采用Vue、ElementUI、Spring Boot,详情可前往体验。 <p>社区版文档地址:<a href="https://www.diaowen.net/docs">https://www.diaowen.net/docs</a></p> [comment]: <> (<p>社区版体验地址:<a href="https://oss.surveyform.cn">https://oss.surveyform.cn</a></p>) </div> </div> <p style="color: #333;">后续我们将持续迭代更新,<strong>并有专人维护</strong>,敬请关注,别忘了<a href="https://gitee.com/wkeyuan/DWSurvey">点下源码仓库</a> 右上角Star关注,便于下次查找。</p> ### 快速安装(一行命令完成) 1、下载调问问卷社区版安装包 最新的JAR包放在QQ群3(`811287103`已满),请加群4(`398556555`),加群备注`安装包`。 2、输入启动命令 ``` cmd java -Dfile.encoding=utf-8 -jar dwsurvey-oss-vue-v.*.*.jar --server.port=8080 --spring.datasource.username=root --spring.datasource.password=123456 ``` 3、打开浏览器访问 http://localhost:8080,输入账号密码: service@diaowen.net/123456 ``` js //可选,文件编码,windows上如果有乱码则使用,linux一般不会出现 -Dfile.encoding=utf-8 //必填,安装包名称, 后面的v.*.*.jar依据您下载的最新安装包来定。 dwsurvey-oss-vue-v.*.*.jar //可选,指定启动服务占用的端口,默认值8080 --server.port=8080 //可选,数据库账号,默认值为root --spring.datasource.username=root //可选,数据库账密码,默认值123456,. --spring.datasource.password=123456 ``` 更详细参数说明请查看[配置说明文档](http://www.diaowen.net/docs/) ## 特性 ![输入图片说明](https://images.gitee.com/uploads/images/2021/0416/132431_5d99a296_1401416.gif "dwsurvey-2.gif") ### 汇总 * 多种技术方案,满足不同的技术选型需求 * 完善的浏览器兼容、保证传统客户也能正常使用 * 部署简单,一行命令完成部署 * 更新方便,直接替换原安装文件不用担心数据被覆盖 * 最高支持多达40多种题型,如单选题、多选题、填空题、评分题、排序题、分页、分段... * 可见即所得设计理念、所有内容支持快速富文本编辑 * 多种端适配,不管是PC还是移动端同一个地址系统自动适配 * 支持答卷密码、结束跳转、仅微信答卷限制等 * 数据实时统计,答卷的数据以可视化的方案展现,不同的统计图表 * 后端满足JPA规范,为未来支持更多数据库提供条件 * 成熟稳定,经过多年技术发展,技术体系完善 * 完善的支持服务,QQ群,微信群全天24小时技术服务 ### 完善的浏览器兼容 **支持现代浏览器和IE6** 在实际收集问卷过程中,不是所有用户都会安装最新的浏览器,DWSurvey在答卷端支持所有的浏览器环境,方案B、方案C更是全站完全支持 | IE / Edge | Firefox | Chrome | Safari | Opera | | :-----| ----: | :----: | :----: | :----: | | IE6+,Edge | 支持 | 支持 | 支持 | 支持 | ### 各技术方案简介 <table> <tr><th><strong>方案A</strong></th><th colspan="2" align="left"><strong>前后端分离,基于 Vue、Element ui、Spring Boot</strong></th></tr> <tr><td colspan="3">方案特性:基于VUE、前后分离开发更容易,部署维护更简单</td></tr> <tr><td rowspan="2">前端</td><td>Gitee</td><td><a href="https://gitee.com/wkeyuan/dwsurvey-vue">https://gitee.com/wkeyuan/dwsurvey-vue</a></td></tr> <tr><td>GitHub</td><td><a href="https://github.com/wkeyuan/DWSurvey_Vue">https://github.com/wkeyuan/DWSurvey_Vue</a></td></tr> <tr><td rowspan="2">后端</td><td>Gitee</td><td><a href="https://gitee.com/wkeyuan/DWSurvey">https://gitee.com/wkeyuan/DWSurvey</a></td></tr> <tr><td>GitHub</td><td><a href="https://github.com/wkeyuan/DWSurvey">https://github.com/wkeyuan/DWSurvey</a></td></tr> <tr><th><strong>方案B</strong></th><th colspan="2" align="left"><strong>Spring Boot + JSP</strong></th></tr> <tr><td colspan="3">方案特性: 原生JS+HTML技术,支持更多浏览器,如IE6</td></tr> <tr><td colspan="1">Gitee</td><td colspan="2"><a href="https://gitee.com/wkeyuan/dwsurvey-springboot-jsp">https://gitee.com/wkeyuan/dwsurvey-springboot-jsp</a></td></tr> <tr><td colspan="1">GitHub</td><td colspan="2"><a href="https://gitee.com/wkeyuan/dwsurvey-springboot-jsp">https://gitee.com/wkeyuan/dwsurvey-springboot-jsp</a></td></tr> <tr><th><strong>方案C</strong></th><th colspan="2" align="left"><strong>Struts2 + JSP</strong></th></tr> <tr><td colspan="3">方案特性: 原生JS+HTML技术,支持更多浏览器,如IE6 |</td></tr> <tr><td colspan="1">Gitee</td><td colspan="2"><a href="https://gitee.com/wkeyuan/dwsurvey-struts2-jsp">https://gitee.com/wkeyuan/dwsurvey-struts2-jsp</a></td></tr> <tr><td colspan="1">GitHub</td><td colspan="2"><a href="https://gitee.com/wkeyuan/dwsurvey-struts2-jsp">https://gitee.com/wkeyuan/dwsurvey-struts2-jsp</a></td></tr> </table> ## 各版本简介 我们提供各种不版本及服务,保证您不同场景的需求都得到满足 | 版本 | 特性及地址 | | :-----| ---- | | 社区版 | 源码全量开源,可独立部署,可二次开发 | | 官网地址 | [http://www.diaowen.net](http://www.diaowen.net) | | 企业版 | 源码全量开源,前后端分离,可独立部署,可二次开发 | | 企业版地址 | [http://ent.surveyform.cn](http://ent.surveyform.cn) | | 在线平台 | 提供标准API,可快速集成到应用中,功能更丰富,不需要部署,可直接发布问卷收集 | | 平台地址 | [https://www.surveyform.cn](https://www.surveyform.cn) | 下面是如何使用Spring Boot方案的快速指南。 ## 本地开发 环境版本:jdk1.8, tomcat8.5.59 ### 基本步骤 1、下载代码后 具体代码地址参考[多种技术方案](#多种技术方案) 2、创建数据库进行初始化 数据库脚本在resources/sql/目录下的dwsurvey.sql数据库脚本文件,如下: https://gitee.com/wkeyuan/DWSurvey/blob/master/src/main/resources/conf/sql/ 说明:升级后的数据库与老版本兼容 3、用IDEA打开,进行本地开发 现在您可以进行本地开发了 4、开发完成,编译打包 进入 `cd DWSurvey`: ```bash mvn package ``` 配置文件地址 源码配置文件地址 resources/application-***.yml war包配置文件地址 /dwsurvey-oss-v.4.0/WEB-INF/classes/application-dev.yml #database settings datasource: url: jdbc:mysql://localhost:3306/dwsurvey_21test?useUnicode=true&characterEncoding=utf8 username: root password: 123456,. 分别修改```url、username、password``` 5、启动浏览器访问 输入 http://localhost:8080 初始账号:```service@diaowen.net``` 密码:```123456``` ## 特色 ### 全新体验、流程简单 以一种全新的设计体验,告别繁琐的设计流程,通过简单有趣的方式,轻轻松松完成问卷设计,多种技术方案,只为呈现更精美的表单问卷. 丰富的题型支持,通过拖拽即可完成题目选择,并可以随意拖动其位置,还可置入所需图片、企业LOGO、设置答题逻辑,一份优美的问卷就是这么简单。 ![我的问卷](src/main/resources/static/img/WX20211203-092339@2x.png) ![问卷编辑](src/main/resources/static/img/WX20211203-092358@2x.png) ![问卷预览](src/main/resources/static/img/WX20211203-092406@2x.png) ![答卷地址](src/main/resources/static/img/WX20211203-092416@2x.png) ![答卷规则](src/main/resources/static/img/WX20211203-092427@2x.png) ![数据统计](src/main/resources/static/img/WX20211203-092439@2x.png) ![原始数据](src/main/resources/static/img/WX20211203-092458@2x.png) ## 有问题怎么办? 对于调问网问卷系统安装及使用的问题,可以在用户交流群里,向作者或其它同学提问。 调问网交流QQ群 ```群1:635994795(满)```,```群2:301105635(满)```, ```群3:811287103(满)```,群4:398556555(可加)(加群时请说明来由) 微信公众号 <img src="http://www.diaowen.net/images/dw_ewm.png" alt="图片替换文本" width="200" height="200" align="top" /> ## 源代码地址 gitee: http://gitee.com/wkeyuan/DWSurvey github: https://github.com/wkeyuan/DWSurvey ## 开源协议 DWSurvey以通用公共许可证AGPL3.0为开源协议,需要更优质的服务可以购买我们的商业版与企业版! - - - ## 关于调问网 没事喜欢瞎折腾,业余时间也想做点有意思的事情,同时对产品也比较感兴趣,一翻调研之后就决定来做个问卷系统。 于是便利用业余时间来做这款问卷表单平台,因为在2012的时候,国内的问卷系统都还比较初级,问卷设计流程复杂,页面也不美观。 所以就开始边调研、边画原型、边写前后端代码,最初的想法是一定要好用美观,在这之后的一年里就不断的设计开发,前前后后修改过3个版本。 - - - ## 作者 柯远 ```keyuan258@gmail.com``` ### 谢谢您的支持 觉得不错就点下右上角的star,随时关注我们的动态,非常感谢!
0
cryptomator/cryptomator
Multi-platform transparent client-side encryption of your files in the cloud
2014-02-02T00:43:47Z
null
[![cryptomator](cryptomator.png)](https://cryptomator.org/) [![Build](https://github.com/cryptomator/cryptomator/workflows/Build/badge.svg)](https://github.com/cryptomator/cryptomator/actions?query=workflow%3ABuild) [![Known Vulnerabilities](https://snyk.io/test/github/cryptomator/cryptomator/badge.svg)](https://snyk.io/test/github/cryptomator/cryptomator) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=cryptomator_cryptomator&metric=alert_status)](https://sonarcloud.io/dashboard?id=cryptomator_cryptomator) [![Twitter](https://img.shields.io/badge/twitter-@Cryptomator-blue.svg?style=flat)](http://twitter.com/Cryptomator) [![Crowdin](https://badges.crowdin.net/cryptomator/localized.svg)](https://translate.cryptomator.org/) [![Latest Release](https://img.shields.io/github/release/cryptomator/cryptomator.svg)](https://github.com/cryptomator/cryptomator/releases/latest) [![Community](https://img.shields.io/badge/help-Community-orange.svg)](https://community.cryptomator.org) ## Supporting Cryptomator Cryptomator is provided free of charge as an open-source project despite the high development effort and is therefore dependent on donations. If you are also interested in further development, we offer you the opportunity to support us: - [One-time or recurring donation via Cryptomator's website.](https://cryptomator.org/#donate) - [Become a sponsor via Cryptomator's sponsors website.](https://cryptomator.org/sponsors/) ### Gold Sponsors <table> <tbody> <tr> <td><a href="https://www.gee-whiz.de/"><img src="https://cryptomator.org/img/sponsors/geewhiz.svg" alt="gee-whiz" height="80"></a></td> </tr> </tbody> </table> ### Silver Sponsors <table> <tbody> <tr> <td><a href="https://mowcapital.com/"><img src="https://cryptomator.org/img/sponsors/mowcapital.svg" alt="Mow Capital" height="28"></a></td> <td><a href="https://www.easeus.com/"><img src="https://cryptomator.org/img/sponsors/easeus.png" alt="EaseUS" height="40"></a></td> <td><a href="https://www.hassmann-it-forensik.de/"><img src="https://cryptomator.org/img/sponsors/hassmannitforensik.png" alt="Hassmann IT-Forensik" height="40"></a></td> </tr> </tbody> </table> ### Special Shoutout Continuous integration hosting for ARM64 builds is provided by [MacStadium](https://www.macstadium.com/opensource). <a href="https://www.macstadium.com/opensource"><img src="https://uploads-ssl.webflow.com/5ac3c046c82724970fc60918/5c019d917bba312af7553b49_MacStadium-developerlogo.png" alt="MacStadium" height="100"></a> --- ## Introduction Cryptomator offers multi-platform transparent client-side encryption of your files in the cloud. Download native binaries of Cryptomator on [cryptomator.org](https://cryptomator.org/) or clone and build Cryptomator using Maven (instructions below). ## Features - Works with Dropbox, Google Drive, OneDrive, MEGA, pCloud, ownCloud, Nextcloud and any other cloud storage service which synchronizes with a local directory - Open Source means: No backdoors, control is better than trust - Client-side: No accounts, no data shared with any online service - Totally transparent: Just work on the virtual drive as if it were a USB flash drive - AES encryption with 256-bit key length - File names get encrypted - Folder structure gets obfuscated - Use as many vaults in your Dropbox as you want, each having individual passwords - Four thousand commits for the security of your data!! :tada: ### Privacy - 256-bit keys (unlimited strength policy bundled with native binaries) - Scrypt key derivation - Cryptographically secure random numbers for salts, IVs and the masterkey of course - Sensitive data is wiped from the heap asap - Lightweight: [Complexity kills security](https://www.schneier.com/essays/archives/1999/11/a_plea_for_simplicit.html) ### Consistency - Authenticated encryption is used for file content to recognize changed ciphertext before decryption - I/O operations are transactional and atomic, if the filesystems support it - Each file contains all information needed for decryption (except for the key of course), no common metadata means no [SPOF](http://en.wikipedia.org/wiki/Single_point_of_failure) ### Security Architecture For more information on the security details visit [cryptomator.org](https://docs.cryptomator.org/en/latest/security/architecture/). ## Building ### Dependencies * JDK 21 (e.g. temurin, zulu) * Maven 3 ### Run Maven ``` mvn clean install # or mvn clean install -Pwin # or mvn clean install -Pmac # or mvn clean install -Plinux ``` This will build all the jars and bundle them together with their OS-specific dependencies under `target`. This can now be used to build native packages. ## License This project is dual-licensed under the GPLv3 for FOSS projects as well as a commercial license for independent software vendors and resellers. If you want to modify this application under different conditions, feel free to contact our support team.
0
mywalkb/LSPosed_mod
My changes to LSPosed
2022-03-28T08:05:38Z
null
# LSPosed Framework [![Build](https://img.shields.io/github/actions/workflow/status/mywalkb/LSPosed_mod/core.yml?branch=main&event=push&logo=github&label=Build)](https://github.com/mywalkb/LSPosed_mod/actions/workflows/core.yml?query=event%3Apush+branch%3Amain+is%3Acompleted) [![Crowdin](https://img.shields.io/badge/Localization-Crowdin-blueviolet?logo=Crowdin)](https://crowdin.com/project/lsposedmod) [![Download](https://img.shields.io/github/v/release/mywalkb/LSPosed_mod?color=orange&logoColor=orange&label=Download&logo=DocuSign)](https://github.com/mywalkb/LSPosed_mod/releases/latest) [![Total](https://shields.io/github/downloads/mywalkb/LSPosed_mod/total?logo=Bookmeter&label=Counts&logoColor=yellow&color=yellow)](https://github.com/mywalkb/LSPosed_mod/releases) [![TotalLatest](https://img.shields.io/github/downloads/mywalkb/LSPosed_mod/latest/total?label=Counts%20for%20latest&logo=Bookmeter)](https://github.com/mywalkb/LSPosed_mod/releases/latest) ## Introduction LSPosed is a great XPosed Framework, but it has a big problem, only manager can manage scope. LSPosed team don't accept PR for CLI or API Module, the TODO issues are old more one year and never completed, is more important the GUI changed many times but not CLI or API Module. In my fork API Module and CLI are implemented. CLI require root user because must access files readable only by root. A Riru / Zygisk module trying to provide an ART hooking framework which delivers consistent APIs with the OG Xposed, leveraging LSPlant hooking framework. > Xposed is a framework for modules that can change the behavior of the system and apps without touching any APKs. That's great because it means that modules can work for different versions and even ROMs without any changes (as long as the original code was not changed too much). It's also easy to undo. As all changes are done in the memory, you just need to deactivate the module and reboot to get your original system back. There are many other advantages, but here is just one more: multiple modules can do changes to the same part of the system or app. With modified APKs, you have to choose one. No way to combine them, unless the author builds multiple APKs with different combinations. ## Supported Versions Android 8.1 ~ 15 Beta 1 ## Install 1. Install Magisk v24+ (For Zygisk flavor) or Magisk 23 (For Riru flavor) 2. (For Riru flavor) Install [Riru](https://github.com/RikkaApps/Riru/releases/latest) v26.1.7+ 3. [Download](#download) and install LSPosed in Magisk app 4. Reboot 5. Open LSPosed manager from notification 6. Have fun :) ## Download - For stable releases, please go to [Github Releases page](https://github.com/mywalkb/LSPosed_mod/releases) - For canary build, please check [Github Actions](https://github.com/mywalkb/LSPosed_mod/actions/workflows/core.yml?query=branch%3Amain) Note: debug builds are only available in Github Actions. ## Migration You can install LSPosed_mod on top of official LSPosed installation If the app is installed and not parasitic, the app must be reinstalled from apk distribuited with LSPosed_mod ## Get Help **Only bug reports from **THE LATEST DEBUG BUILD** will be accepted.** - GitHub issues: [Issues](https://github.com/mywalkb/LSPosed_mod/issues/) - [Wiki](https://github.com/mywalkb/LSPosed_mod/wiki) - (For Chinese speakers) 本项目只接受英语**标题**的issue。如果您不懂英语,请使用[翻译工具](https://www.deepl.com/zh/translator) ## For Developers Developers are welcome to write Xposed modules with hooks based on LSPosed Framework. A module based on LSPosed framework is fully compatible with the original Xposed Framework, and vice versa, a Xposed Framework-based module will work well with LSPosed framework too. - [Xposed Framework API](https://api.xposed.info/) We use our own module repository. We welcome developers to submit modules to our repository, and then modules can be downloaded in LSPosed. - [LSPosed Module Repository](https://github.com/Xposed-Modules-Repo) ## Translation Contributing You can contribute translation [here](https://crowdin.com/project/lsposedmod). ## Credits - [LSPosed](https://github.com/LSPosed/LSPosed): fork source (makes all these possible) - [Magisk](https://github.com/topjohnwu/Magisk/): makes all these possible - [Riru](https://github.com/RikkaApps/Riru): provides a way to inject code into zygote process - [XposedBridge](https://github.com/rovo89/XposedBridge): the OG Xposed framework APIs - [Dobby](https://github.com/jmpews/Dobby): used for inline hooking - [LSPlant](https://github.com/LSPosed/LSPlant): the core ART hooking framework - [EdXposed](https://github.com/ElderDrivers/EdXposed): fork source - [XZ Embedded](https://git.tukaani.org/xz-embedded.git): for decompress debug_info section into stripped libraries - ~[SandHook](https://github.com/ganyao114/SandHook/): ART hooking framework for SandHook variant~ - ~[YAHFA](https://github.com/rk700/YAHFA): previous ART hooking framework~ - ~[dexmaker](https://github.com/linkedin/dexmaker) and [dalvikdx](https://github.com/JakeWharton/dalvik-dx): to dynamically generate YAHFA hooker classes~ - ~[DexBuilder](https://github.com/LSPosed/DexBuilder): to dynamically generate YAHFA hooker classes~ ## License LSPosed is licensed under the **GNU General Public License v3 (GPL-3)** (http://www.gnu.org/copyleft/gpl.html).
0
eoinfogarty/Onboarding
A beautiful way to introduce users to your app
2016-08-08T10:52:58Z
null
[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Onboarding-green.svg?style=true)](https://android-arsenal.com/details/3/4094) Onboarding ========== A beautiful way to introduce users to you app ![Demo](graphics/example.gif) Using a regular `ViewPager` with a custom transformer with callbacks we can achieve this effect [Sample Apk](https://dl.dropboxusercontent.com/u/31880748/onboarding-sample.apk) ### Interface ```java public interface SceneChangeListener { void enterScene(@Nullable ImageView sharedElement, float position); void centerScene(@Nullable ImageView sharedElement); void exitScene(@Nullable ImageView sharedElement, float position); void notInScene(); } ``` We then a fragment class that implements the callbacks to react to movement ### Fragment ```java public abstract class BaseSceneFragment extends Fragment implements SceneTransformer.SceneChangeListener { protected static final String KEY_POSITION = "KEY_POSITION"; // we have to set a position tag to the root layout of every scene fragment // this is so the transformer will know who to make a callback to protected void setRootPositionTag(@NonNull View root) { root.setTag(getArguments().getInt(KEY_POSITION)); } @Override public abstract void enterScene(@Nullable ImageView sharedElement, float position); @Override public abstract void centerScene(@Nullable ImageView sharedElement); @Override public abstract void exitScene(@Nullable ImageView sharedElement, float position); @Override public abstract void notInScene(); ... } ``` #License ``` Copyright (C) 2016 Eoin Fogarty 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. ```
0
nshmura/RecyclerTabLayout
An efficient TabLayout library implemented with RecyclerView.
2015-07-27T10:44:25Z
null
# RecyclerTabLayout [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-RecyclerTabLayout-green.svg?style=flat)](https://android-arsenal.com/details/1/2220) An efficient TabLayout library implemented with RecyclerView. ## Features - Efficient when having many tabs - Easy setup with ViewPager (same as [TabLayout](http://developer.android.com/intl/ja/reference/android/support/design/widget/TabLayout.html) of Android Design Support Library) - RTL layout support ## UseCase - Many tabs layout - Infinite loop scrolling (imitated) ## Demos ![Years](art/years.gif) ![Loop](art/loop.gif) ![Basic](art/basic.gif) ![Icon](art/icon.gif) ## Samples <a href="https://play.google.com/store/apps/details?id=com.nshmura.recyclertablayout.demo"><img src="art/googleplay.png"/></a> ## Getting started In your build.gradle: ``` repositories { jcenter() } dependencies { compile 'com.nshmura:recyclertablayout:1.5.0' } ``` Define `RecyclerTabLayout` in xml layout with custom attributes. ```xml <com.nshmura.recyclertablayout.RecyclerTabLayout android:id="@+id/recycler_tab_layout" android:layout_width="match_parent" android:layout_height="48dp" rtl_tabIndicatorColor="?attr/colorAccent" rtl_tabIndicatorHeight="2dp" rtl_tabBackground="?attr/selectableItemBackground" rtl_tabTextAppearance="@android:style/TextAppearance.Small" rtl_tabSelectedTextColor="?android:textColorPrimary" rtl_tabMinWidth="72dp" rtl_tabMaxWidth="264dp" rtl_tabPaddingStart="12dp" rtl_tabPaddingTop="0dp" rtl_tabPaddingEnd="12dp" rtl_tabPaddingBottom="0dp" rtl_tabPadding="0dp"/> ``` Set up with the ViewPager. ```java ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); viewPager.setAdapter(adapter); RecyclerTabLayout recyclerTabLayout = (RecyclerTabLayout) findViewById(R.id.recycler_tab_layout); recyclerTabLayout.setUpWithViewPager(viewPager); ``` Or set up with ViewPager and Custom RecyclerView.Adapter that's extends `RecyclerTabLayout.Adapter`. ```java ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager); viewPager.setAdapter(adapter); RecyclerTabLayout recyclerTabLayout = (RecyclerTabLayout) findViewById(R.id.recycler_tab_layout); recyclerTabLayout.setUpWithAdapter(new CustomRecyclerViewAdapter(viewPager)); ``` Here's sample of custom RecyclerView adapter. ```java public class CustomRecyclerViewAdapter extends RecyclerTabLayout.Adapter<CustomRecyclerViewAdapter.ViewHolder> { public DemoCustomView01Adapter(ViewPager viewPager) { super(viewPager); ... } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // Inflate your view. View view = ...; return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { // Bind data ... if (position == getCurrentIndicatorPosition()) { //Highlight view } } public class ViewHolder extends RecyclerView.ViewHolder { ... public ViewHolder(View itemView) { super(itemView); ... } } } ``` ## Attributes | attr | description | | ------------- | ------------- | | rtl_tabIndicatorColor | Indicator color | | rtl_tabIndicatorHeight | Indicator height | | rtl_tabBackground | Background drawable of each tab | | rtl_tabTextAppearance | TextAppearence of each tab | | rtl_tabSelectedTextColor | Text color of selected tab | | rtl_tabOnScreenLimit | The number of OnScreen tabs. If this value is larger than 0, `rtl_tabMinWidth` and `rtl_tabMaxWidth` are ignored. | | rtl_tabMinWidth | Minimum width of each tab | | rtl_tabMaxWidth | Maximum width of each tab | | rtl_tabPaddingStart | The padding of the start edge of each tab | | rtl_tabPaddingTop | The padding of the top edge of each tab | | rtl_tabPaddingEnd | The padding of the end edge of each tab | | rtl_tabPaddingBottom | The padding of the bottom edge of each tab | | rtl_tabPadding | The padding of all four edges of each tab | | rtl_scrollEnabled | Sets whether tab scrolling is enabled | [default attribute](library/src/main/res/values/styles.xml) ## Thanks The demo app uses the following resources. color-names by codebrainz<br/> https://github.com/codebrainz/color-names Material Design icons by Google<br/> https://github.com/google/material-design-icons ## License ``` Copyright (C) 2017 nshmura 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. ```
0
xmuSistone/VerticalSlideFragment
vertical slide to switch to the next fragment page, looks like vertical viewpager
2015-09-01T08:31:03Z
null
# android-vertical-slide-view vertical slide to switch to the next fragment page. 仿照淘宝和聚美优品,在商品详情页,向上拖动时,可以加载下一页。使用ViewDragHelper,滑动比较流畅。<br><br> scrollView滑动到底部的时候,再行向上拖动时,添加了一些阻力。<br> ![PREVIEW](capture.gif)
0
torodb/stampede
The ToroDB solution to provide better analytics on top of MongoDB and make it easier to migrate from MongoDB to SQL
2014-10-23T17:04:21Z
null
# ToroDB Stampede > Transform your NoSQL data from a MongoDB replica set into a relational database in PostgreSQL. There are other solutions that are able to store the JSON document in a relational table using PostgreSQL JSON support, but it doesn't solve the real problem of 'how to really use that data'. ToroDB Stampede replicates the document structure in different relational tables and stores the document data in different tuples using those tables. ![](documentation/docs/images/tables_distribution.jpeg) ## Installation Due to the use of different external systems like MongoDB and PostgreSQL, the installation requires some previous steps. Take a look at out [quickstart][1] in the documentation. ## Usage example MongoDB is a great idea, but sooner or later some kind of business intelligence, or complex aggregated queries are required. At this point MongoDB is not so powerful and ToroDB Stampede borns to solve that problem (see [our post about that][2]). The kind of replication done by ToroDB Stampede allows the execution of aggregated queries in a relational backend (PostgreSQL) with a noticeable time improvement. A deeper explanation is available in our [how to use][3] section in the documentation. ## Development setup As it was said in the installation section, the requirements of external systems can make more difficult to explain briefly how to setup the development environment here. So if you want to take a look on how to prepare your development environment, take a look to our [documentation][4]. ## Release History * 1.0.0 * Released on October 24th 2018 * 1.0.0-beta3 * Released on June 30th 2017 * 1.0.0-beta2 * Released on April 06th 2017 * 1.0.0-beta1 * Released on December 30th 2016 ## Meta ToroDB – [@nosqlonsql](https://twitter.com/nosqlonsql) – info@8kdata.com Distributed under the GNU AGPL v3 license. See ``LICENSE`` for more information. [1]: https://www.torodb.com/stampede/docs/quickstart [2]: https://www.8kdata.com/blog/the-conundrum-of-bi-aggregate-queries-on-mongodb/ [3]: https://www.torodb.com/stampede/docs/how-to-use [4]: https://www.torodb.com/stampede/docs/installation/previous-requirements/
0
Raysmond/SpringBlog
A simple blogging system implemented with Spring Boot + Hibernate + MySQL + Bootstrap4.
2015-09-26T15:58:47Z
null
SpringBlog ===== 中文开发和部署文档请查看:http://raysmond.com/posts/springblog-guide SpringBlog is a very simple and clean-design blog system implemented with Spring Boot. It's one of my learning projects to explore awesome features in Spring Boot web programming. You can check my blog site for demo [https://raysmond.com](http://raysmond.com). There's no demo online. Here's the screenshot of my previous blog homepage. ![](http://7b1fa0.com1.z0.glb.clouddn.com/screencapture-blog-raysmond-8080-1480663084590.png) SpringBlog is powered by many powerful frameworks and third-party projects: - Spring Boot and many of Spring familiy (e.g. Spring MVC, Spring JPA, Spring Secruity and etc) - Hibernate + MySQL - [HikariCP](https://github.com/brettwooldridge/HikariCP) - A solid high-performance JDBC connection pool - [Bootstrap](https://getbootstrap.com) - A very popular and responsive front-end framework - [Pegdown](https://github.com/sirthias/pegdown) - A pure-java markdown processor - [ACE Editor](http://ace.c9.io/) - A high performance code editor which I use to write posts and code. - [Redis](http://redis.io/) - A very powerful in-memory data cache server. - EhCache - Thymeleaf (Spring MVC) ## Development Before development, please install the following service software: - [MySQL](https://www.mysql.com) Edit the spring config profile `src/main/resources/application.yml` according to your settings. And start MySQL and Redis first before running the application. ``` # If you're using Ubuntu server # Install MySQL apt-get install mysql-server service mysql start mysql -u root -p >> create database spring_blog; ``` This is a Gradle project. Make sure Gradle is installed in your machine. Try `gradle -v` command. Otherwise install in from [http://www.gradle.org/](http://www.gradle.org/). I recommend you import the source code into Intellij IDE to edit the code. ``` # Start the web application ./gradlew bootRun ``` ## Development **How to import the project into Intellij IDEA and run from the IDE?** ``` git clone https://github.com/Raysmond/SpringBlog.git cd SpringBlog bower install ``` 1. Clone the project 2. Download all dependencies 3. Open the project in Intellij IDEA. 4. Run `SpringBlogApplication.java` as Java application. 5. Preview: http://localhost:8080 Admin: http://localhost:8080/admin , the default admin account is: `admin`, password: `admin` > Lombok is required to run the project. You can install the plugin in Intellij IDEA. > Reference: https://github.com/mplushnikov/lombok-intellij-plugin - Build application jar `./gradlew build`, then upload the distribution jar (e.g. `build/libs/SpringBlog-0.1.jar`) to your remote server. - Upload `application-production.yml` to your server and change it according to your server settings. - Run it (Java8 is a must) ``` java -jar SpringBlog-0.1.jar --spring.profiles.active=prod # OR with external spring profile file java -jar SpringBlog-0.1.jar --spring.config.location=application-production.yml ``` ## TODO - [x] Upgrade frontend framework to Bootstrap4 - [ ] Replace Jade with Thymeleaf(HTML) - [ ] Frontend building tools, e.g. webpack - [x] Use hibernate 2nd level cache (EHCache?) - [ ] Markdown preview while editing - [ ] Html editor ## License Modified BSD license. Copyright (c) 2015 - 2018, Jiankun LEI (Raysmond).
0
Dreampie/Resty
The minimalist framework of RESTful(server and client) - Resty
2014-12-29T10:45:13Z
null
Resty 一款极简的restful轻量级的web框架 =========== 更新说明 ---- - [x] feature/20170203 强化Stringer工具和让日志支持彩色输出方便开发者调试 [@t-baby](https://github.com/t-baby) ---- [![Join the chat at https://gitter.im/Dreampie/Resty](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Dreampie/Resty?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Issue Stats](http://issuestats.com/github/Dreampie/Resty/badge/pr?style=flat)](http://issuestats.com/github/Dreampie/Resty) [![Issue Stats](http://issuestats.com/github/Dreampie/Resty/badge/issue?style=flat)](http://issuestats.com/github/Dreampie/Resty) <a href="http://dreampie.gitbooks.io/resty-chs/content/index.html" target="_blank">开发文档</a> 如果你还不是很了解restful,或者认为restful只是一种规范不具有实际意义,推荐一篇osc两年前的文章:[RESTful API 设计最佳实践](http://www.oschina.net/translate/best-practices-for-a-pragmatic-restful-api) 和 Infoq的一篇极其理论的文章 [理解本真的REST架构风格](http://www.infoq.com/cn/articles/understanding-restful-style) 虽然有点老,介绍的也很简单,大家权当了解,restful的更多好处,还请google 拥有jfinal/activejdbc一样的activerecord的简洁设计,使用更简单的restful框架 restful的api设计,是作为restful的服务端最佳选择(使用场景:客户端和服务端解藕,用于对静态的html客户端(mvvm等),ios,andriod等提供服务端的api接口) Java开发指南:[Java style guide](https://github.com/Dreampie/java-style-guide) Api设计指南:[Http api design](https://github.com/Dreampie/http-api-design-ZH_CN) Resty例子: [resty-samples](https://github.com/Dreampie/resty-samples)(纯接口) [resty-demo](https://github.com/Dreampie/resty-demo)(带界面) 如果你在考虑前后端分离方案,推荐resty+vuejs,https://github.com/Dreampie/vuejs2-demo 开发群: <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=8fc9498714ebbc3675cc5a5035858004154ef4645ebc9c128dfd76688d32179b"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="极简Restful框架 - Resty" title="极简Restful框架 - Resty"></a> 其他开发者贡献的插件:[Beetl扩展(大鹏)](https://github.com/zhaopengme/Resty-ext) [Shiro扩展(zhoulieqing)](http://git.oschina.net/zhoulieqing/resty-shiro) [MongoPlugin(T-baby)](https://github.com/T-baby/MongoDB-Plugin) > 有兴趣一起维护该框架的,可以联系我,进入合作开发 > 规范:提前说明功能,新建分支 `feature/日期` 功能 `fix/日期` 修复 在readme里添加一个TODO list描述 > - [x] feature/20161228 a task list item done [@Dreampie](https://github.com/Dreampie) > - [ ] feature/20161229 a task list item todo [@Dreampie](https://github.com/Dreampie) > 注意代码2格缩进,最后所有合作者一起代码review,合格之后合并到master maven使用方式: 1. 添加依赖包 ```xml <dependency> <groupId>cn.dreampie</groupId> <artifactId>resty-route</artifactId> <version>1.3.1.SNAPSHOT</version> </dependency> ``` 2.如果使用带有SNAPSHOT后缀的包,请添加该仓库 ```xml <repositories> <repository> <id>oss-snapshots</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> ``` 一、独有优点: ----------- 重大更新: 1.3.0更新内容: 使用jetty作为嵌入式热加载默认实现(只要java文件进行编译就会重新加载),resty-captcha验证码功能... 1.2.0更新内容:使用header来控制api版本,基于数据源的读写分离,更简单的tableSetting.[详情查看](http://www.oschina.net/news/68791/resty-1-2-0-snapshot) 1.1.0版本重大更新:快速接入spring,缓存,加密,header,XForwardedSupports等,[详情查看](http://www.oschina.net/news/67001/resty-1-1-0-snapshot) Record的时代已经到来,你完全不用使用任何的model来执行你的数据 ```java //创建record的执行器 针对sec_user表 并开启缓存 Record recordDAO = new Record("sec_user"); //使用当前数据源和表数据 new一个对象来保存数据 recordDAO.reNew().set("属性", "值").save(); Record r1 = recordDAO.reNew().set("属性", "值"); Record r2 = recordDAO.reNew().set("属性", "值"); //批量保存 recordDAO.save(r1, r2); //更新 r2.set("属性", "值").update() //查询全部 List<Record> records = recordDAO.findAll(); //条件查询 recordDAO.findBy(where,paras) //分页查询 Page<Record> records = recordDAO.paginateAll(); //根据id删除 recordDAO.deleteById("1"); //本次查询放弃使用cache recordDAO.unCache().findBy(where,paras); //把record的数据源切换到dsmName数据源上 recordDAO.useDS(dsmName).findBy(where,paras); //等等,完全摆脱model,实现快速操作数据 ``` Model支持动态切换数据源和本次查询放弃使用cache ```java User dao=new User(); //本次查询放弃使用cache dao.unCache().findBy(where,paras); //把model的数据源切换到dsmName数据源上 dao.useDS(dsmName).findBy(where,paras); ``` //数据库和全局参数配置移植到application.properties 详情参看resty-example ```java #not must auto load app.encoding=UTF-8 app.devEnable=true app.showRoute=false app.cacheEnabled=true #默认使用ehcacheProvider #app.cacheProvider=cn.dreampie.cache.redis.RedisProvider ##druid plugin auto load db.default.url=jdbc:mysql://127.0.0.1/example?useUnicode=true&characterEncoding=UTF-8 db.default.user=dev db.default.password=dev1010 db.default.dialect=mysql #c3p0配置 c3p0.default.minPoolSize=3 c3p0.default.maxPoolSize=20 #druid配置 #druid.default.initialSize=10 #druid.default.maxPoolPreparedStatementPerConnectionSize=20 #druid.default.timeBetweenConnectErrorMillis=1000 #druid.default.filters=slf4j,stat,wall #flyway database migration auto load flyway.default.valid.clean=true flyway.default.migration.auto=true flyway.default.migration.initOnMigrate=true db.demo.url=jdbc:mysql://127.0.0.1/demo?useUnicode=true&characterEncoding=UTF-8 db.demo.user=dev db.demo.password=dev1010 db.demo.dialect=mysql #druid druid.demo.initialSize=10 druid.demo.maxPoolPreparedStatementPerConnectionSize=20 druid.demo.timeBetweenConnectErrorMillis=1000 druid.demo.filters=slf4j,stat,wall #flyway flyway.demo.valid.clean=true flyway.demo.migration.auto=true flyway.demo.migration.initOnMigrate=true //数据库的配置精简 自动从文件读取参数 只需配置model扫描目录 和dsmName public void configPlugin(PluginLoader pluginLoader) { //第一个数据库 ActiveRecordPlugin activeRecordPlugin = new ActiveRecordPlugin(new DruidDataSourceProvider("default"), true); activeRecordPlugin.addIncludePaths("cn.dreampie.resource"); pluginLoader.add(activeRecordPlugin); } ``` 1.极简的route设计,完全融入普通方法的方式,方法参数就是请求参数,方法返回值就是数据返回值 ```java @GET("/users/:name") //在路径中自定义解析的参数 如果有其他符合 也可以用 /users/{name} // 参数名就是方法变量名 除路径参数之外的参数也可以放在方法参数里 传递方式 user={json字符串} public Map find(String name,User user) { // return Lister.of(name); return Maper.of("k1", "v1,name:" + name, "k2", "v2"); //返回什么数据直接return } ``` 2.极简的activerecord设计,数据操作只需短短的一行,支持批量保存对象 ```java //批量保存 User u1 = new User().set("username", "test").set("providername", "test").set("password", "123456"); User u2 = new User().set("username", "test").set("providername", "test").set("password", "123456"); User.dao.save(u1,u2); //普通保存 User u = new User().set("username", "test").set("providername", "test").set("password", "123456"); u.save(); //更新 u.update(); //条件更新 User.dao.updateBy(columns,where,paras); User.dao.updateAll(columns,paras); //删除 u.deleted(); //条件删除 User.dao.deleteBy(where,paras); User.dao.deleteAll(); //查询 User.dao.findById(id); User.dao.findBy(where,paras); User.dao.findAll(); //分页 User.dao.paginateBy(pageNumber,pageSize,where,paras); User.dao.paginateAll(pageNumber,pageSize); ``` 3.极简的客户端设计,支持各种请求,文件上传和文件下载(支持断点续传) ```java Client httpClient=null;//创建客户端对象 //启动resty-example项目,即可测试客户端 String apiUrl = "http://localhost:8081/api/v1.0"; //如果不需要 使用账号登陆 //httpClient = new Client(apiUrl); //如果有账号权限限制 需要登陆 httpClient = new Client(apiUrl, "/tests/login", "u", "123"); //该请求必须 登陆之后才能访问 未登录时返回 401 未认证 ClientRequest authRequest = new ClientRequest("/users"); ClientResult authResult = httpClient.build(authRequest).get(); System.out.println(authResult.getResult()); //get ClientRequest getRequest = new ClientRequest("/tests"); ClientResult getResult = httpClient.build(getRequest).get(); System.out.println(getResult.getResult()); //post ClientRequest postRequest = new ClientRequest("/tests"); postRequest.addParam("test", Jsoner.toJSONString(Maper.of("a", "谔谔"))); ClientResult postResult = httpClient.build(postRequest).post(); System.out.println(postResult.getResult()); //put ClientRequest putRequest = new ClientRequest("/tests/x"); ClientResult putResult = httpClient.build(putRequest).put(); System.out.println(putResult.getResult()); //delete ClientRequest deleteRequest = new ClientRequest("/tests/a"); ClientResult deleteResult = httpClient.build(deleteRequest).delete(); System.out.println(deleteResult.getResult()); //upload ClientRequest uploadRequest = new ClientRequest("/tests/resty"); uploadRequest.addUploadFiles("resty", ClientTest.class.getResource("/resty.jar").getFile()); uploadRequest.addParam("des", "test file paras 测试笔"); ClientResult uploadResult = httpClient.build(uploadRequest).post(); System.out.println(uploadResult.getResult()); //download 支持断点续传 ClientRequest downloadRequest = new ClientRequest("/tests/file"); downloadRequest.setDownloadFile(ClientTest.class.getResource("/resty.jar").getFile().replace(".jar", "x.jar")); ClientResult downloadResult = httpClient.build(downloadRequest).get(); System.out.println(downloadResult.getResult()); ``` 4.支持多数据源和嵌套事务(使用场景:需要访问多个数据库的应用,或者作为公司内部的数据中间件向客户端提供数据访问api等) ```java // 在resource里使用事务,也就是controller里,rest的世界认为所以的请求都表示资源,所以这儿叫resource @GET("/users") @Transaction(name = {"default", "demo"}) //多数据源的事务,如果你只有一个数据库 直接@Transaction 不需要参数 public User transaction() { //TODO 用model执行数据库的操作 只要有操作抛出异常 两个数据源 都会回滚 虽然不是分布式事务 也能保证代码块的数据执行安全 } // 如果你需要在service里实现事务,通过java动态代理(必须使用接口,jdk设计就是这样) public interface UserService { @Transaction(name = {"demo"})//service里添加多数据源的事务,如果你只有一个数据库 直接@Transaction 不需要参数 public User save(User u); } // 在resource里使用service层的 事务 // @Transaction(name = {"demo"})的注解需要写在service的接口上 // 注意java的自动代理必须存在接口 // TransactionAspect 是事务切面 ,你也可以实现自己的切面比如日志的Aspect,实现Aspect接口 // 再private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect(),new LogAspect()); private UserService userService = AspectFactory.newInstance(new UserServiceImpl(), new TransactionAspect()); ``` 5.极简的权限设计,可以通过cache支持分布式session,你只需要实现一个简单接口和添加一个拦截器,即可实现基于url的权限设计 ```java public void configInterceptor(InterceptorLoader interceptorLoader) { //权限拦截器 放在第一位 第一时间判断 避免执行不必要的代码 interceptorLoader.add(new SecurityInterceptor(new MyAuthenticateService())); } //实现接口 public class MyAuthenticateService implements AuthenticateService { //登陆时 通过name获取用户的密码和权限信息 public Principal findByName(String name) { DefaultPasswordService defaultPasswordService = new DefaultPasswordService(); Principal principal = new Principal(name, defaultPasswordService.hash("123"), new HashSet<String>() {{ add("api"); }}); return principal; } //基础的权限总表 所以的url权限都放在这儿 你可以通过 文件或者数据库或者直接代码 来设置所有权限 public Set<Credential> loadAllCredentials() { Set<Credential> credentials = new HashSet<Credential>(); credentials.add(new Credential("GET", "/api/v1.0/users**", "users")); return credentials; } } ``` 6.极简的缓存设计,可扩展,非常简单即可启用model的自动缓存功能 ```java //启用缓存并在要自动使用缓存的model上 //config application.properties app.cacheEnabled=true //开启缓存@Table(name = "sec_user", cached = true) @Table(name = "sec_user", cached = true) public class User extends Model<User> { public static User dao = new User(); } ``` 7.下载文件,只需要直接return file ```java @GET("/files") public File file() { return new File(path); } ``` 8.上传文件,注解配置把文件写到服务器 ```java @POST("/files") @FILE(dir = "/upload/") //配置上传文件的相关信息 public UploadedFile file(UploadedFile file) { return file; } ``` 9.当然也是支持传统的web开发,你可以自己实现数据解析,在config里添加自定义的解析模板 ```java public void configConstant(ConstantLoader constantLoader) { // 通过后缀来返回不同的数据类型 你可以自定义自己的 render 如:FreemarkerRender //默认已添加json和text的支持,只需要把自定义的Render add即可 // constantLoader.addRender("json", new JsonRender()); } ``` 二、运行example示例: ----------------- 1.在本地mysql数据库里创建demo,example数据库,对应application.properties的数据库配置 2.运行resty-example下的pom.xml->flyway-maven-plugin:migrate,自动根具resources下db目录下的数据库文件生成数据库表结构 3.运行resty-example下的pom.xml->tomcat6-maven-plugin:run,启动example程序 提醒:推荐idea作为开发ide,使用分模块的多module开发 License <a href="https://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License V2</a> 捐赠: [支付宝](https://raw.githubusercontent.com/Dreampie/Resty/master/alipay.png)
0
jmxtrans/jmxtrans
jmxtrans
2011-12-07T17:24:36Z
null
![jmxtranslogo](http://www.jmxtrans.org/assets/img/jmxtrans-logo.gif) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjmxtrans%2Fjmxtrans.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjmxtrans%2Fjmxtrans?ref=badge_shield) [![Build Status](https://secure.travis-ci.org/jmxtrans/jmxtrans.png?branch=master)](http://travis-ci.org/jmxtrans/jmxtrans) [![Build status](https://ci.appveyor.com/api/projects/status/7g88sgeglsm7st17?svg=true)](https://ci.appveyor.com/project/gquintana/jmxtrans) [![Dependency Status](https://www.versioneye.com/user/projects/5421de9e3a8c2f2b8b000056/badge.svg?style=flat)](https://www.versioneye.com/user/projects/5421de9e3a8c2f2b8b000056) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jmxtrans/jmxtrans?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Maven site](https://img.shields.io/badge/Maven-site-blue.svg)](http://www.jmxtrans.org/jmxtrans/) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.jmxtrans/jmxtrans/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.jmxtrans/jmxtrans) [![sonarcloud.io](https://img.shields.io/badge/sonarcloud-quality-lightgrey.svg)](https://sonarcloud.io/dashboard?id=org.jmxtrans%3Ajmxtrans-parent) This is the source code repository for the jmxtrans project. This is effectively the missing connector between speaking to a JVM via JMX on one end and whatever logging / monitoring / graphing package that you can dream up on the other end. jmxtrans is very powerful tool which uses easily generated JSON (or [YAML](https://github.com/jmxtrans/jmxtrans/blob/master/jmxtrans/tools/yaml2jmxtrans.py)) based configuration files and then outputs the data in whatever format you desire. It does this with a very efficient engine design that will scale to communicating with thousands of machines from a single jmxtrans instance. The core engine is very solid and there are writers for [Graphite](http://graphite.wikidot.com/), [StatsD](https://github.com/etsy/statsd), [Ganglia](http://ganglia.sourceforge.net/), [cacti/rrdtool](http://www.cacti.net/), [OpenTSDB](http://opentsdb.net/), text files, and stdout. Feel free to suggest more on the discussion group or issue tracker. * [Download a recent stable build](https://repo1.maven.org/maven2/org/jmxtrans/jmxtrans/) (or a [SNAPSHOT one](https://oss.sonatype.org/content/repositories/snapshots/org/jmxtrans/jmxtrans/)) * See the [Wiki](https://github.com/jmxtrans/jmxtrans/wiki) for full documentation. * Join the [Google Group](http://groups.google.com/group/jmxtrans) if you have anything to discuss or [follow the commits](http://groups.google.com/group/jmxtrans-commits). Please don't email Jon directly because he just doesn't have enough time to answer every question individually. * People are [talking - this is me! (skip to 21:45)](http://www.justin.tv/kctv88/b/290736874) and [talking](http://www.slideshare.net/cyrille.leclerc/paris-devops-monitoring-and-feature-toggle-pattern-with-jmx) and [talking (skip to 34:40)](http://www.justin.tv/kctv88/b/288229232) and [(french talking)](http://www.slideshare.net/henri.gomez/devops-retour-dexprience-marsjug-du-29-juin-2011) about it. * If you are seeing duplication of output data, look for 'typeNames' in the documentation. * If you like this project, please tell your friends, blog & tweet. I'd really love your help getting more publicity. Coda Hale did [an excellent talk](http://pivotallabs.com/talks/139-metrics-metrics-everywhere) for [Pivotal Labs](http://pivotallabs.com/) on *why* metrics matter. Great justification for using a tool like jmxtrans. ![render](http://jmxtrans.googlecode.com/svn/wiki/render.png) ## Special thanks: * [JetBrains](https://www.jetbrains.com/buy/opensource/) for providing us with IntelliJ licenses, * [EJ Technologies](https://www.ej-technologies.com/) for providing us with licenses of their [Java profiler](https://www.ej-technologies.com/products/jprofiler/overview.html). ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjmxtrans%2Fjmxtrans.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjmxtrans%2Fjmxtrans?ref=badge_large)
0
zzz40500/GsonFormat
根据Gson库使用的要求,将JSONObject格式的String 解析成实体
2014-10-31T14:16:39Z
null
GsonFormat ------ [jetbrains](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-GsonFormat-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1896) [swift](https://github.com/EnjoySR/ESJsonFormat-Xcode) [Json Annotation](https://github.com/tianzhijiexian/JsonAnnotation) [中文Readme](README_CN.md) This is a plugin you can generate Json model from Json String. Please do aware **This Plugin is only for Android Studio and IntelliJ IDEA**. ## Install - Using IDE built-in plugin system on Windows: - <kbd>File</kbd> > <kbd>Settings</kbd> > <kbd>Plugins</kbd> > <kbd>Browse repositories...</kbd> > <kbd>Search for "GsonFormat"</kbd> > <kbd>Install Plugin</kbd> - Using IDE built-in plugin system on MacOs: - <kbd>Preferences</kbd> > <kbd>Settings</kbd> > <kbd>Plugins</kbd> > <kbd>Browse repositories...</kbd> > <kbd>Search for "GsonFormat"</kbd> > <kbd>Install Plugin</kbd> - Manually: - Download the [latest release](https://github.com/zzz40500/GsonFormat/releases/latest) and install it manually using <kbd>Preferences</kbd> > <kbd>Plugins</kbd> > <kbd>Install plugin from disk...</kbd> - From official jetbrains store from [download](https://plugins.jetbrains.com/plugin/7654?pr=androidstudio) Restart IDE. ## Usage ### Use IDE menu ![Generate.png](http://upload-images.jianshu.io/upload_images/166866-2c5168c72b7155ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ### Use hotkey Default **Option + s**(Mac), **Alt + s** (win) You can change the hotkey via: ![修改快捷键.png](http://upload-images.jianshu.io/upload_images/166866-f9e20ca0ad7b9ae4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) ## Demo picture ![gsonFormat.gif](http://upload-images.jianshu.io/upload_images/166866-ff9dc336af72d7d7.gif?imageMogr2/auto-orient/strip) ## Version Info v1.2.2 > * Supports field type changes. * Supports shortcut to open GsonFormat, default option + s (mac), alt + s (win) * Support for field name changes. * Support to add the prefix field. * Support for multiple conversion libraries (Gson, Jackjson, FastJson, LoganSquare). * Support for private and public modes. * Supports filtering of superclass into existing fields. ## License Copyright 2014 The GsonFormat Authors 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.
0
mcxtzhang/AnimShopButton
A shopping cart button with a telescopic displacement rotation animation ...一个带伸缩位移旋转动画的购物车按钮
2016-12-28T10:05:53Z
null
# AnimShopButton [![](https://jitpack.io/v/mcxtzhang/AnimShopButton.svg)](https://jitpack.io/#mcxtzhang/AnimShopButton) A shopping cart button with a telescopic displacement rotation animation ... 一个仿饿了么 带伸缩位移旋转动画的购物车按钮 注意,本控件非继承自`ViewGroup`,而是**纯自定义View**,实现的仿饿了么加入购物车控件,自带**闪转腾挪动画**的按钮。 图1 项目中使用的效果,考虑到了`View`的**回收复用**, 并且可以看到在`RecyclerView`中使用,切换`LayoutManager`也是没有问题的, ![项目中使用的效果](https://github.com/mcxtzhang/AnimShopButton/blob/master/gif/new.gif) 图2 Demo效果,测试各种属性值 ![图2 Demo效果,测试各种属性值](https://github.com/mcxtzhang/AnimShopButton/blob/master/gif/testAttr.gif) 图3 最新静态图 ![图3 最新静态图,测试各种属性值](https://github.com/mcxtzhang/AnimShopButton/blob/master/gif/attrs.png) # Article 相关博文: http://blog.csdn.net/zxt0601/article/details/54235736 想经济上支持我 or 想通过视频看我是怎么实现的: http://edu.csdn.net/course/detail/3898 # Import **Step 1. Add the JitPack repository to your build file** **Step 1. 在项目根build.gradle文件中增加JitPack仓库依赖。** ``` allprojects { repositories { ... maven { url "https://jitpack.io" } } } ``` Step 2. Add the dependency ``` dependencies { compile 'com.github.mcxtzhang:AnimShopButton:V1.2.0' } ``` # Usage xml: ``` <!--使用默认UI属性--> <com.mcxtzhang.lib.AnimShopButton android:id="@+id/btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" app:maxCount="3"/> <!--设置了两圆间距--> <com.mcxtzhang.lib.AnimShopButton android:id="@+id/btn2" android:layout_width="wrap_content" android:layout_height="wrap_content" app:count="3" app:gapBetweenCircle="90dp" app:maxCount="99"/> <!--仿饿了么--> <com.mcxtzhang.lib.AnimShopButton android:id="@+id/btnEle" android:layout_width="wrap_content" android:layout_height="wrap_content" app:addEnableBgColor="#3190E8" app:addEnableFgColor="#ffffff" app:hintBgColor="#3190E8" app:hintBgRoundValue="15dp" app:hintFgColor="#ffffff" app:maxCount="99"/> ``` 注意: 加减点击后,具体的操作,要根据业务的不同来编写了,设计到实际的购物车可能还有写数据库操作,或者请求接口等,要操作成功后才执行动画、或者修改count,这一块代码每个人写法可能不同。 使用时,可以重写`onDelClick()`和` onAddClick()`方法,并在合适的时机回调`onCountAddSuccess()`和` onCountDelSuccess()`以执行动画。 效果图如图2. # Attributes |name|format|description|中文解释 |:---:|:---:|:---:|:---:| | isAddFillMode| boolean| Plus button is opened Fill mode default is stroke (false)|加按钮是否开启fill模式 默认是stroke(false) | addEnableBgColor| color|The background color of the plus button|加按钮的背景色 | addEnableFgColor| color|The foreground color of the plus button|加按钮的前景色 | addDisableBgColor| color|The background color when the button is not available|加按钮不可用时的背景色 | addDisableFgColor| color |The foreground color when the button is not available|加按钮不可用时的前景色 | isDelFillMode| boolean| Plus button is opened Fill mode default is stroke (false)|减按钮是否开启fill模式 默认是stroke(false) | delEnableBgColor| color|The background color of the minus button|减按钮的背景色 | delEnableFgColor| color|The foreground color of the minus button|减按钮的前景色 | delDisableBgColor| color|The background color when the button is not available|减按钮不可用时的背景色 | delDisableFgColor| color |The foreground color when the button is not available|减按钮不可用时的前景色 | radius| dimension|The radius of the circle|圆的半径 | circleStrokeWidth| dimension|The width of the circle|圆圈的宽度 | lineWidth| dimension|The width of the line (+ - sign)|线(+ - 符号)的宽度 | gapBetweenCircle| dimension| The spacing between two circles|两个圆之间的间距 | numTextSize| dimension| The textSize of draws the number|绘制数量的textSize | maxCount| integer| max count|最大数量 | count| integer| current count|当前数量 | hintText| string| The hint text when number is 0|数量为0时,hint文字 | hintBgColor| color| The hint background when number is 0|数量为0时,hint背景色 | hintFgColor| color| The hint foreground when number is 0|数量为0时,hint前景色 | hingTextSize| dimension| The hint text size when number is 0|数量为0时,hint文字大小 | hintBgRoundValue| dimension| The background fillet value when number is 0|数量为0时,hint背景圆角值 | ignoreHintArea| boolean| The UI/animation whether ignores the hint area|UI显示、动画是否忽略hint收缩区域 | perAnimDuration| integer| The duration of each animation, in ms|每一段动画的执行时间,单位ms | hintText| string| The hint text when number is 0|数量为0时,hint文字 | replenishTextColor| color| TextColor in replenish status|补货中状态的文字颜色 | replenishTextSize| dimension| TextSize in replenish status|补货中状态的文字大小 | replenishText| string | Text hint in replenish status|补货中状态的文字 这么多属性够你用了吧。 ## Where to find me: [Github](https://github.com/mcxtzhang) [CSDN](http://blog.csdn.net/zxt0601) [稀土掘金](http://gold.xitu.io/user/56de210b816dfa0052e66495) [简书](http://www.jianshu.com/users/8e91ff99b072/timeline) QQ群 :**557266366** *** ## History Version : 1.1.0,Time: 2017/01/12 * 1 Feature : Add a boolean variable `ignoreHintArea` :The UI/animation whether ignores the hint area * 2 Feature : Add a int variable `perAnimDuration` : The duration of each animation, in ms Version : 1.2.0 Time: 2017/02/08 * 1 Feature : Add a status: replenishment.Click is not allowed at this time. * Judgment by setReplenish (boolean) and isReplenish ()
0
puniverse/capsule
Dead-Simple Packaging and Deployment for JVM Apps
2014-04-18T12:15:41Z
null
# *Capsule*<br/>Dead-Simple Packaging and Deployment for JVM Applications [![Build Status](http://img.shields.io/travis/puniverse/capsule.svg?style=flat)](https://travis-ci.org/puniverse/capsule) [![Coverage](https://coveralls.io/repos/puniverse/capsule/badge.svg?branch=master)](https://coveralls.io/r/puniverse/capsule?branch=master) [![Dependency Status](https://www.versioneye.com/user/projects/539704a483add7f80a000030/badge.svg?style=flat)](https://www.versioneye.com/user/projects/539704a483add7f80a000030) [![Version](http://img.shields.io/badge/version-1.0.3-blue.svg?style=flat)](https://github.com/puniverse/capsule/releases) [![License](http://img.shields.io/badge/license-EPL-blue.svg?style=flat)](https://www.eclipse.org/legal/epl-v10.html) Capsule is a packaging and deployment tool for JVM applications. A capsule is a single executable JAR that contains everything your application needs to run either in the form of embedded files or as declarative metadata. It can contain your JAR artifacts, your dependencies and resources, native libraries, the require JRE version, the JVM flags required to run the application well, Java or native agents and more. In short, a capsule is a self-contained JAR that knows everything there is to know about how to run your application the way it's meant to run. One way of thinking about a capsule is as a fat JAR on steroids (that also allows native libraries and never interferes with your dependencies) and a declarative startup script rolled into one; another, is to see it is as the deploy-time counterpart to your build tool. Just as a build tool manages your build, Capsule manages the launching of your application. But while plain capsules are cool and let you ship any JVM application -- no matter how complex -- as a single executable JAR, caplets make capsules even more powerful. ## Documentation [Capsule website](http://www.capsule.io) ## Support Discuss Capsule on the capsule-user [Google Group/Mailing List](https://groups.google.com/forum/#!forum/capsule-user) ## Getting Started [Download](https://github.com/puniverse/capsule/releases) or: co.paralleluniverse:capsule:1.0.3 or: Clone the repository and gradle install ## License Copyright (c) 2014-2016, Parallel Universe Software Co. and Contributors. All rights reserved. This program and the accompanying materials are licensed under the terms of the Eclipse Public License v1.0 as published by the Eclipse Foundation. http://www.eclipse.org/legal/epl-v10.html As Capsule does not link in any way with any of the code bundled in the JAR file, and simply treats it as raw data, Capsule is no different from a self-extracting ZIP file (especially as manually unzipping and examining the JAR's contents is extremely easy). Capsule's own license, therefore, does not interfere with the licensing of the bundled software. In particular, even though Capsule's license is incompatible with the GPL/LGPL, it is permitted to distribute GPL programs packaged as capsules, as Capsule is simply a packaging medium and an activation script, and does not restrict access to the packaged GPL code. Capsule does not add any capability to, nor removes any from the bundled application. It therefore falls under the definition of an "aggregate" in the GPL's terminology.
0
marcosbarbero/spring-cloud-zuul-ratelimit
Rate limit auto-configure for Spring Cloud Netflix Zuul
2016-04-14T17:49:19Z
null
null
0
jarlen/PhotoEditDemo
1,图片编辑(图片添加,文字添加),实现图片编辑中的图片添加,旋转,缩放,删除;文字的添加,大小缩放,字体更换,颜色更换,删除; 2,基本滤镜实现与接口封装; 涂鸦(画笔的样式,粗细,颜色,橡皮擦,贴图); 相框(简单相框,酷炫相框); 马赛就克(基本马赛克,酷炫马赛克,橡皮擦)及其接口封装 3,接下来, 图像剪切,旋转等功能实现测试接口封装; GIF与MP4,图片互转实现测试与接口封装;
2015-08-18T01:21:55Z
null
# 图片处理sdk(just for eclipse) Note: 新的项目(for studio)转移到https://github.com/jarlen/PhotoEdit (包括jni本地源码) - cn.ffmpeg - gif mp4 互转 - com.js.photosdk.bodywarp - 图片变形 - com.js.photosdk.crop - 图片剪切 - 借用 library [cropper](https://github.com/edmodo/cropper) - com.js.photosdk.enhance - 图片增强,对比度,饱和度,亮度 - com.js.photosdk.filter - 滤镜 - 借用 library [android-gpuimage](https://github.com/CyberAgent/android-gpuimage) - com.js.photosdk.mosaic - 马赛克 - com.js.photosdk.operate - 图片添加水印,添加文字 - com.js.photosdk.photoframe - 添加相框 - com.js.photosdk.scrawl - 涂鸦 - com.js.photosdk.utils - 工具类 - jp.co.cyberagent.android.gpuimage - 滤镜 library - jp.co.cyberagent.android.gpuimage.util - 滤镜 library
0
tough1985/RxjavaRetrofitDemo
A demo show how to use Retrofit with Rxjava
2016-03-09T08:57:41Z
null
# Retrofit与Rxjava结合的实例 1. RxJava如何与Retrofit结合 2. 相同格式的Http请求数据该如何封装 3. 相同格式的Http请求数据统一进行预处理 4. 如何取消一个Http请求 5. 一个需要ProgressDialog的Subscriber该有的样子
0
razerdp/AnimatedPieView
// 一个好吃的甜甜圈?
2017-11-07T09:11:48Z
null
AnimatedPieView --- **一个好吃的甜甜圈?请问客官要啥口味捏-V-** [**English Doc**](https://github.com/razerdp/AnimatedPieView/blob/master/README_EN.md) [![jcenter](https://api.bintray.com/packages/razerdp/maven/AnimatedPieView/images/download.svg)](https://bintray.com/razerdp/maven/AnimatedPieView/_latestVersion) [![license](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/razerdp/AnimatedPieView/blob/master/LICENSE) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-AnimatedPieView-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/6507) [![Api](https://img.shields.io/badge/Api-14%2B-green.svg)](https://img.shields.io/badge/Api-14%2B-green.svg) [![Author](https://img.shields.io/badge/Author-razerdp-blue.svg)](https://github.com/razerdp) 开发进度 (更新日志->[日志](https://github.com/razerdp/AnimatedPieView/blob/master/UPDATE_LOG.md)) --- > 如果您有别的需求,可以提交您的issue哦,当然,也可以直接修改源码-V- * ~~支持TypeFace~~ * ~~点选文字或图表选中甜甜圈~~ * ~~增加默认选中支持~~ * ~~增加图例支持~~ * ~~增加删除数据的方法~~ * ~~增加描述标签支持~~ * ~~项目优化/重构,1.2.0发布~~ * ~~允许alpha突出选中的甜甜圈~~ * ~~允许甜甜圈之间含有间隔~~ * ~~文字自适应点击动画位置~~ * ~~文字描述动画~~ * ~~有文字描述的甜甜圈~~ * ~~点击事件回调的甜甜圈~~ * ~~点击动画的甜甜圈~~ * ~~可以点击的甜甜圈~~ * ~~可以变成大饼的甜甜圈~~ * ~~动画长大的甜甜圈~~ 主要功能 --- | 描述 | 方法 | 预览 | | -------- | :----- | ---- | | 动画生长 | -- | ![pie_animation](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_animation.gif) | | 饼图/甜甜圈转换 | strokeMode(boolean) | ![pie_switch](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_switch.gif) | | 角度间隙 | splitAngle(float) | ![pie_split_angle](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_split_angle.gif) | | 绘制文字 | drawText(true) | ![pie_with_text](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_with_text.gif) | | 点击效果 | canTouch(true) / selectListener() | ![pie_click_effect](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_click_effect.gif) | | 焦点甜甜圈效果 (反向) | focusAlphaType(<br>AnimatedPieViewConfig.FOCUS_WITH_ALPHA_REV,150<br>) | ![pie_click_with_focus_alpha_type_rev](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_click_with_focus_alpha_type_rev.gif) | | 焦点甜甜圈效果 | focusAlphaType(<br>AnimatedPieViewConfig.FOCUS_WITH_ALPHA,150<br>) | ![pie_click_with_focus_alpha_type](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_click_with_focus_alpha_type.gif) | | 甜甜圈标签 | IPieInfo.PieOption | ![pie_option](https://github.com/razerdp/AnimatedPieView/blob/master/art/pie_option.png) | 依赖 --- 添加依赖(请把{latestVersion}替换成上面的jcenter标签所示版本) ```xml dependencies { implementation 'com.github.razerdp:AnimatedPieView:{latestVersion}' } ``` 基本使用方式(简单的超乎想像) --- **step 1:定义任意类实现IPieInfo接口(如果懒,可以使用SimplePieInfo)** ```java public class Test implements IPieInfo { @Override public float getValue() { //这个数值将会决定其所占有的饼图百分比 return 0.5f; } @Override public int getColor() { //该段甜甜圈的颜色,请返回@colorInt,不要返回@colorRes return Color.WHITE; } @Override public String getDesc() { //描述文字,可不返回 return "这是一个测试"; } @Nullable @Override public PieOption getPieOpeion() { //一些别的设置,比如标签 return mPieOption; } } ``` **step 2:定义config并配置就可以了** ```java AnimatedPieView mAnimatedPieView = findViewById(R.id.animatedPieView); AnimatedPieViewConfig config = new AnimatedPieViewConfig(); config.startAngle(-90)// 起始角度偏移 .addData(new SimplePieInfo(30, getColor("FFC5FF8C"), "这是第一段"))//数据(实现IPieInfo接口的bean) .addData(new SimplePieInfo(18.0f, getColor("FFFFD28C"), "这是第二段")) ...(尽管addData吧) .duration(2000);// 持续时间 // 以下两句可以直接用 mAnimatedPieView.start(config); 解决,功能一致 mAnimatedPieView.applyConfig(config); mAnimatedPieView.start(); ``` 进阶用法(所有配置都在config,and...相信我,我提供大多数配置,但日常用到的,其实不多哈哈) --- ```java AnimatedPieViewConfig mConfig=mAnimatedPieView.getConfig(); mConfig.animOnTouch(true)// 点击事件是否播放浮现动画/回退动画(默认true) .addData(IPieInfo info, boolean autoDesc)// 添加数据,autoDesc:是否自动补充描述?(百分比) .floatExpandAngle(15f)// 点击后圆弧/扇形扩展的角度 .floatShadowRadius(18f)// 点击后的阴影扩散范围 .floatUpDuration(500)// 点击浮现动画时间 .floatDownDuration(500)// 上一个浮现的圆弧回退的动画时间 .floatExpandSize(15)// 点击后扇形放大数值,,只对饼图有效 .strokeMode(true)// 是否只画圆弧【甜甜圈哈哈】,否则画扇形(默认true) .strokeWidth(15)// 圆弧(甜甜圈)宽度 .duration(2500)// 动画时间 .startAngle(-90f)// 开始的角度 .selectListener(new OnPieSelectListener<IPieInfo>())//点击事件 .drawText(true)// 是否绘制文字描述 .textSize(12)// 绘制的文字大小 .textMargin(8)// 绘制文字与导航线的距离 .autoSize(true)// 自动测量甜甜圈半径 .pieRadius(100)// 甜甜圈半径 .pieRadiusRatio(0.8f)// 甜甜圈半径占比 .guidePointRadius(2)// 设置描述文字的开始小点的大小 .guideLineWidth(4)// 设置描述文字的指示线宽度 .guideLineMarginStart(8)// 设置描述文字的指示线开始距离外圆半径的大小 .textGravity(AnimatedPieViewConfig.ABOVE)// 设置描述文字方向 【 -AnimatedPieViewConfig.ABOVE:文字将会在导航线上方绘制 -AnimatedPieViewConfig.BELOW:文字在导航线下方绘制 -AnimatedPieViewConfig.ALIGN:文字与导航线对齐 -AnimatedPieViewConfig.ECTOPIC:文字在1、2象限部分绘制在线的上方,在3、4象限绘制在线的下方 】 .canTouch(true)// 是否允许甜甜圈点击放大 .typeFae(TypeFace)// 字体样式 .splitAngle(1)// 甜甜圈间隙角度 .focusAlphaType(AnimatedPieViewConfig.FOCUS_WITH_ALPHA_REV,150)// 焦点甜甜圈的alpha表现形态及alpha削减值 .interpolator(new DecelerateInterpolator())// 动画插值器 .focusAlpha(150) // 选中的/或者非选中的甜甜圈的alpha值(跟focusAlphaType挂钩) .legendsWith((ViewGroup) findViewById(R.id.ll_legends), new OnPieLegendBindListener<BasePieLegendsView>() { @Override public BasePieLegendsView onCreateLegendView(int position, IPieInfo info) { return position % 2 == 0 ? DefaultPieLegendsView.newInstance(MainActivity.this) : DefaultCirclePieLegendsView.newInstance(MainActivity.this); } @Override public boolean onAddView(ViewGroup parent, BasePieLegendsView view) { return false; } }); //图例支持 ``` --- 更多配置: ----- 在IPieInfo中,你可以配置`PieOption`以扩展每个甜甜圈的行为 ```java @Nullable @Override public PieOption getPieOption() { return new PieOption() .setDefaultSelected(true) // 默认选中 .setIconHeight(50) // 图标的高度 .setIconWidth(50) //图标宽度 .setIconScaledHeight(0.5f) // 图标高度缩放 .setIconScaledWidth(0.5f) // 图标宽度缩放 .setLabelIcon(bitmap) // 图标资源 .setLabelPadding(5) // 图标与文字的距离 .setLabelPosition(PieOption.NEAR_PIE); // 图标在甜甜圈内侧 } ``` 打赏(看在我那么努力维护的份上。。。给个零食呗~) --- | 微信 |支付宝 | | ---- | ---- | | ![](https://github.com/razerdp/FriendCircle/blob/master/wechat.png) | ![](https://github.com/razerdp/FriendCircle/blob/master/alipay.png) | 控件思路【按思路顺序更新】 --- [一起弄个甜甜圈吧](https://github.com/razerdp/Article/blob/master/%E4%B8%80%E8%B5%B7%E6%92%B8%E4%B8%AA%E7%94%9C%E7%94%9C%E5%9C%88.md) LICENSE --- [Apache-2.0](https://github.com/razerdp/AnimatedPieView/blob/master/LICENSE)
0
zaaach/CityPicker
:fire::fire::fire:城市选择、定位、搜索及右侧字母导航,类似美团 百度糯米 饿了么等APP选择城市功能
2016-02-27T09:11:27Z
null
<p align="center"> <img src="art/header.png"> </p> # CityPicker [![Platform](https://img.shields.io/badge/platform-android-green.svg)](http://developer.android.com/index.html) [![API](https://img.shields.io/badge/API-14%2B-yellow.svg?style=flat)](https://android-arsenal.com/api?level=14) 现在使用较多的类似美团、外卖等APP的城市选择界面,**一行代码搞定**,就是这么简单粗暴!!! **Tips:**(旧版本1.x)会报高德定位jar包冲突,推荐使用2.x版本。 #### 主要功能: - 字母悬浮栏 - 指定热门城市 - 自定义动画效果 - 自定义主题 - 名称或拼音搜索 - 返回城市名、code等数据 - 提供定位接口,解耦定位SDK # Preview ![image](https://github.com/zaaach/CityPicker/raw/master/art/screen.gif) ![image](https://github.com/zaaach/CityPicker/raw/master/art/screen1.gif) ![image](https://github.com/zaaach/CityPicker/raw/master/art/screen2.gif) # APK 下载[demo.apk](https://github.com/zaaach/CityPicker/raw/master/art/demo.apk)体验. # Download **1:** 项目根目录的build.gradle添加如下配置: ```groovy allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` **2:** app添加依赖: ```groovy dependencies { implementation 'com.github.zaaach:CityPicker:x.y.z' } ``` 记得把`x.y.z`替换为[![jitpack](https://jitpack.io/v/zaaach/CityPicker.svg)](https://jitpack.io/#zaaach/CityPicker)中的数字 # Usage `CityPicker` 基于`DialogFragment` 实现,已提供定位接口,需要APP自身实现定位。 ### 基本使用: #### Step1: 在`manifest.xml`中给使用`CityPicker` 的`activity`添加主题`android:theme="@style/DefaultCityPickerTheme"` ```xml <activity android:name=".MainActivity" android:theme="@style/DefaultCityPickerTheme"> ...... </activity> ``` #### Step2: 注意:热门城市使用`HotCity` ,定位城市使用`LocatedCity` ```java List<HotCity> hotCities = new ArrayList<>(); hotCities.add(new HotCity("北京", "北京", "101010100")); //code为城市代码 hotCities.add(new HotCity("上海", "上海", "101020100")); hotCities.add(new HotCity("广州", "广东", "101280101")); hotCities.add(new HotCity("深圳", "广东", "101280601")); hotCities.add(new HotCity("杭州", "浙江", "101210101")); ...... CityPicker.from(activity) //activity或者fragment .enableAnimation(true) //启用动画效果,默认无 .setAnimationStyle(anim) //自定义动画 .setLocatedCity(new LocatedCity("杭州", "浙江", "101210101"))) //APP自身已定位的城市,传null会自动定位(默认) .setHotCities(hotCities) //指定热门城市 .setOnPickListener(new OnPickListener() { @Override public void onPick(int position, City data) { Toast.makeText(getApplicationContext(), data.getName(), Toast.LENGTH_SHORT).show(); } @Override public void onCancel(){ Toast.makeText(getApplicationContext(), "取消选择", Toast.LENGTH_SHORT).show(); } @Override public void onLocate() { //定位接口,需要APP自身实现,这里模拟一下定位 new Handler().postDelayed(new Runnable() { @Override public void run() { //定位完成之后更新数据 CityPicker.getInstance() .locateComplete(new LocatedCity("深圳", "广东", "101280601"), LocateState.SUCCESS); } }, 3000); } }) .show(); ``` ### 关于自定义主题: 在`style.xml` 中自定义主题并且继承`DefaultCityPickerTheme` ,别忘了在`manifest.xml` 设置给`activity`。 ```xml <style name="CustomTheme" parent="DefaultCityPickerTheme"> <item name="cpCancelTextColor">@color/color_green</item> <item name="cpSearchCursorDrawable">@color/color_green</item> <item name="cpIndexBarNormalTextColor">@color/color_green</item> <item name="cpIndexBarSelectedTextColor">@color/color_green</item> <item name="cpSectionHeight">@dimen/custom_section_height</item> <item name="cpOverlayBackground">@color/color_green</item> ...... </style> ``` `CityPicker` 中自定义的所有属性如下,有些属性值必须是引用类型`refrence`,使用时注意。 ```xml <resources> <attr name="cpCancelTextSize" format="dimension|reference" /> <attr name="cpCancelTextColor" format="color|reference" /> <attr name="cpClearTextIcon" format="reference" /> <attr name="cpSearchTextSize" format="dimension|reference" /> <attr name="cpSearchTextColor" format="color|reference" /> <attr name="cpSearchHintText" format="string|reference" /> <attr name="cpSearchHintTextColor" format="color|reference" /> <attr name="cpSearchCursorDrawable" format="reference" /> <attr name="cpListItemTextSize" format="dimension|reference" /> <attr name="cpListItemTextColor" format="color|reference" /> <attr name="cpListItemHeight" format="dimension|reference"/> <attr name="cpEmptyIcon" format="reference"/> <attr name="cpEmptyIconWidth" format="dimension|reference"/> <attr name="cpEmptyIconHeight" format="dimension|reference"/> <attr name="cpEmptyText" format="string|reference"/> <attr name="cpEmptyTextSize" format="dimension|reference"/> <attr name="cpEmptyTextColor" format="color|reference"/> <attr name="cpGridItemBackground" format="color|reference"/> <attr name="cpGridItemSpace" format="reference"/> <!--悬浮栏--> <attr name="cpSectionHeight" format="reference"/> <attr name="cpSectionTextSize" format="reference" /> <attr name="cpSectionTextColor" format="reference" /> <attr name="cpSectionBackground" format="reference" /> <attr name="cpIndexBarTextSize" format="reference" /> <attr name="cpIndexBarNormalTextColor" format="reference" /> <attr name="cpIndexBarSelectedTextColor" format="reference" /> <!--特写布局--> <attr name="cpOverlayWidth" format="dimension|reference"/> <attr name="cpOverlayHeight" format="dimension|reference"/> <attr name="cpOverlayTextSize" format="dimension|reference"/> <attr name="cpOverlayTextColor" format="color|reference"/> <attr name="cpOverlayBackground" format="color|reference"/> </resources> ``` OK,enjoy it~ # Changelog #### v2.1.0 - 迁移至AndroidX #### v2.0.3 - 修复状态栏变黑问题 - 修复字母索引栏被软遮挡的问题 - 新增取消选择监听 - 方法调用方式稍微改变 #### v2.0.2 - 修复定位城市偶尔不刷新的bug #### v2.0.1 - 新增定位接口 - 修改返回类型为`City` ,可获取城市名、code等数据 #### v2.0.0 - 项目重构优化,结构更清晰 - 使用RecyclerView # 感谢 [ImmersionBar](https://github.com/gyf-dev/ImmersionBar) # About me 掘金:[ https://juejin.im/user/56f3dfe8efa6310055ac719f ](https://juejin.im/user/56f3dfe8efa6310055ac719f) 简书:[ https://www.jianshu.com/u/913a8bb93d12 ](https://www.jianshu.com/u/913a8bb93d12) 淘宝店:[ LEON家居生活馆 (动漫摆件)]( https://shop238932691.taobao.com) ![LEON](https://raw.githubusercontent.com/zaaach/imgbed/master/arts/leon_shop_qrcode.png) :wink:淘宝店求个关注:wink: # QQ群 有兴趣可以加入QQ群一起交流: ![扫码入群601783167](https://raw.githubusercontent.com/zaaach/imgbed/master/arts/qqgroup.jpg)
0
gjiazhe/PanoramaImageView
An imageView can auto scroll with device rotating.
2016-12-21T03:06:25Z
null
# PanoramaImageView An imageView can auto scroll with device rotating. ## ScreenShots <img src="screenshots/recyclerview_sample.gif" width="270"> <img src="screenshots/horizontal_sample.gif" width="270"> <img src="screenshots/vertical_sample.gif" width="270"> ## Include PanoramaImageView to Your Project With gradle: ```groovy dependencies { compile 'com.gjiazhe:PanoramaImageView:1.0' } ``` ## Use PanoramaImageView in Layout File Just Like ImageView ```xml <com.gjiazhe.panoramaimageview.PanoramaImageView android:id="@+id/panorama_image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:src="@drawable/img" app:piv_enablePanoramaMode="true" app:piv_show_scrollbar="true" app:piv_invertScrollDirection="false" /> ``` ## Description of Attributes | Attributes | Format | Default | Description | | :-----------------------: | :-----: | :-----: | :---------------------------------: | | piv_enablePanoramaMode | boolean | true | Enable panorama effect or not. | | piv_show_scrollbar | boolean | true | Show scrollbar or not. | | piv_invertScrollDirection | boolean | false | Invert the scroll direction or not. | All the attributes can also be set in java code: ```java panoramaImageView.setEnablePanoramaMode(true); panoramaImageView.setEnableScrollbar(true); panoramaImageView.setInvertScrollDirection(false); ``` ## Register the GyroscopeObserver In Activity or Fragment using PanoramaImageView, you should __register the GyroscopeObserver in onResume()__ and __remember to unregister it in onPause()__. ```java public class MyActivity extends AppCompatActivity { private GyroscopeObserver gyroscopeObserver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialize GyroscopeObserver. gyroscopeObserver = new GyroscopeObserver(); // Set the maximum radian the device should rotate to show image's bounds. // It should be set between 0 and π/2. // The default value is π/9. gyroscopeObserver.setMaxRotateRadian(Math.PI/9); PanoramaImageView panoramaImageView = (PanoramaImageView) findViewById(R.id.panorama_image_view); // Set GyroscopeObserver for PanoramaImageView. panoramaImageView.setGyroscopeObserver(gyroscopeObserver); } @Override protected void onResume() { super.onResume(); // Register GyroscopeObserver. gyroscopeObserver.register(this); } @Override protected void onPause() { super.onPause(); // Unregister GyroscopeObserver. gyroscopeObserver.unregister(); } } ``` ## Set OnPanoramaScrollListener to observe scroll state If you want to get callback when the image scrolls, set an OnPanoramaScrollListener for PanoramaImageView. ```java panoramaImageView.setOnPanoramaScrollListener(new PanoramaImageView.OnPanoramaScrollListener() { @Override public void onScrolled(PanoramaImageView view, float offsetProgress) { // Do something here. // The offsetProgress range from -1 to 1, indicating the image scrolls // from left(top) to right(bottom). } }); ``` ## License MIT License Copyright (c) 2016 郭佳哲 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.
0
oubowu/OuNews
新闻阅读
2016-02-29T16:24:11Z
null
# OuNews 简单的新闻客户端 # ## 一、为什么写这个? ## 一直想练习MVP模式开发应用,把学习的RxJava、Retrofit等热门的开源库结合起来,于是写了这么一款新闻阅读软件, 有新闻、图片、视频三大模块,使用Retrofit和Okhttp实现无网读缓存,有网根据过期时间重新请求, 还有边缘或整页侧滑、夜间模式切换等小功能,还写了几个自定义小控件,虽然无啥卵用,但是学到了很多东西,很有收获。 ## 二、运行截图 ## ![](/pic/1.png) ![](/pic/2.png) ![](/pic/3.png) ![](/pic/4.png) ![](/pic/5.png) ![](/pic/6.png) ![](/pic/7.png) ![](/pic/8.png) ![](/pic/9.png) ![](/pic/10.png) ![](/pic/11.png) ![](/pic/12.png) ## 三、用到的开源库 ## * [Quick-News API来自此项目,特此感谢](https://github.com/tigerguixh/QuickNews) * [RxJava 响应式编程框架](https://github.com/ReactiveX/RxJava) * [Retrofit2.0 REST安卓客户端请求库](https://github.com/square/retrofit) * [OkHttp3 网络请求](https://github.com/square/okhttp) * [Glide 图片加载](https://github.com/bumptech/glide) * [GreenDao 数据库操作](https://github.com/greenrobot/greenDAO) * [PhotoView 图片缩放](https://github.com/chrisbanes/PhotoView) * [Ijkplayer 视频播放](https://github.com/Bilibili/ijkplayer) * [AndroidChangeSkin 无需重启换肤](https://github.com/hongyangAndroid/AndroidChangeSkin) * ...... 感谢各位大神无私的开源精神。 ## 四、一些零散的知识点 ## MVP模式代码学习<br>https://github.com/antoniolg/androidmvp</br> 使用Retrofit和Okhttp实现网络缓存。无网读缓存,有网根据过期时间重新请求<br>http://www.jianshu.com/p/9c3b4ea108a7</br> Retrofit+RxJava实战日志(5)-如何获取缓存<br>http://blog.csdn.net/efan006/article/details/50549107</br> Drawable 着色的后向兼容方案<br>http://www.cnblogs.com/helloandroid/p/4779061.html</br> Java基础加强总结(一)——注解(Annotation)<br>http://www.cnblogs.com/xdp-gacl/p/3622275.html</br> Android实现RecyclerView侧滑删除和长按拖拽-ItemTouchHelper<br>http://blog.csdn.net/u010687392/article/details/47950199</br> 基于RxJava、RxAndroid的EventBus实现<br>http://www.cnblogs.com/tiantianbyconan/p/4578699.html</br> 深入浅出RxJava<br>http://blog.csdn.net/lzyzsd/article/details/41833541</br> ## 五、声明 ## 应用中展示的所有内容均搜集自互联网,若内容有侵权请联系作者进行删除处理。本应用仅用作分享与学习。 ## 六、关于作者 ## 微博:http://weibo.com/palfansinheart CSDN博客:http://blog.csdn.net/oushangfeng123?viewmode=contents
0
kymjs/RxVolley
RxVolley = Volley + RxJava(RxJava3.0) + OkHttp(OkHttp3)
2016-01-04T03:38:41Z
null
[![OSL](https://kymjs.com/qiniu/image/logo3.png)](https://kymjs.com/works/) ================= > RxVolley = Volley + RxAndroid3 + OkHttp3 [中文帮助](https://github.com/kymjs/RxVolley/blob/master/Readme_zh.md) ## Retrofit? No, I Love Volley. RxVolley is modified Volley. Removed the HttpClient, and support RxJava. If you are building with Gradle, simply add the following line to the ```dependencies``` section of your ```build.gradle``` file: latest version numbers: [![](https://jitpack.io/v/kymjs/RxVolley.svg)](https://jitpack.io/#kymjs/RxVolley) >implementation 'com.github.kymjs.rxvolley:rxvolley:3.0.0' > >// If use okhttp function >implementation 'com.github.kymjs.rxvolley:okhttp3:3.0.0' >//or okhttp2 >implementation 'com.github.kymjs.rxvolley:okhttp:3.0.0' > >// If use image-loader function >implementation 'com.github.kymjs.rxvolley:image:3.0.0' ## Getting Started Builder pattern to create objects. #### Callback method do Get request and contenttype is form ``` HttpParams params = new HttpParams(); //http header, optional parameters params.putHeaders("cookie", "your cookie"); params.putHeaders("User-Agent", "rxvolley"); //request parameters params.put("name", "kymjs"); params.put("age", "18"); HttpCallback callBack = new HttpCallback(){ @Override public void onSuccess(String t) { } @Override public void onFailure(int errorNo, String strMsg) { } } new RxVolley.Builder() .url("https://www.kymjs.com/rss.xml") .httpMethod(RxVolley.Method.GET) //default GET or POST/PUT/DELETE/HEAD/OPTIONS/TRACE/PATCH .cacheTime(6) //default: get 5min, post 0min .contentType(RxVolley.ContentType.FORM)//default FORM or JSON .params(params) .shouldCache(true) //default: get true, post false .callback(callBack) .encoding("UTF-8") //default .doTask(); ``` #### Callback method do Post request and contenttype is json ``` String paramJson = "{\n" + " \"name\": \"kymjs\", " + " \"age\": \"18\" " + "}"; //request parameters, json format HttpParams params = new HttpParams(); params.putJsonParams(paramJson); // upload progress ProgressListener listener = new ProgressListener(){ @Override public void onProgress(long transferredBytes, long totalSize){ } } new RxVolley.Builder() .url("https://www.kymjs.com/rss.xml") .httpMethod(RxVolley.Method.POST) //default GET or POST/PUT/DELETE/HEAD/OPTIONS/TRACE/PATCH .cacheTime(6) //default: get 5min, post 0min .params(params) .contentType(RxVolley.ContentType.JSON) .shouldCache(true) //default: get true, post false .progressListener(listener) //upload progress .callback(callback) .encoding("UTF-8") //default .doTask(); ``` #### return Observable\<Result\> type ``` Observable<Result> observable = new RxVolley.Builder() .url("https://www.kymjs.com/rss.xml") .httpMethod(RxVolley.Method.POST) //default GET or POST/PUT/DELETE/HEAD/OPTIONS/TRACE/PATCH .cacheTime(6) //default: get 5min, post 0min .params(params) .contentType(RxVolley.ContentType.JSON) .getResult(); //do something observable.subscribe(subscriber); ``` ## Requirements RxVolley can be included in any Android application. RxVolley supports Android 3.1, API12 (HONEYCOMB_MR1) and later. ## License Licensed under the Apache License Version 2.0. [The "License"](http://www.apache.org/licenses/LICENSE-2.0)
0
MZCretin/ExpandableTextView
实现类似微博内容,@用户,链接高亮,@用户和链接可点击跳转,可展开和收回的TextView
2018-08-17T13:34:46Z
null
# ExpandableTextView **实现类似微博内容,@用户,链接高亮,@用户和链接可点击跳转,可展开和收回的TextView。觉得好用别忘了star哦,你的star是对我最大的激励** ### 全平台国际化话翻译解决方案 项目国际化翻译解决方案,支持Android、iOS、Flutter、前端Vue、后端PHP等等,点几下按钮就能实现翻译内容的自动抓取和翻译后文件的自动生成,适合各类场景下的国际化需求。详情请查看:https://github.com/MZCretin/Eva-Translate 欢迎star ------- ### [需求解决系列之-【系列工具概览】](https://juejin.im/post/5ed6174f51882542fb06d850) 此系列是大道至简的起始,将一系列简单恶心的操作封装起来,框架么,可以败絮其中,但一定要金絮其外! ### 快速使用 Gradle: ``` implementation 'com.github.MZCretin:ExpandableTextView:v1.6.1' ``` // if u use AndroidX, use the following ``` implementation 'com.github.MZCretin:ExpandableTextView:v1.6.1-x' ``` ### 更新日志 + 2019-07-04 12:06:06更新,如果你需要监听展开和回收的时间监听,但是不需要控件真正的执行展开和回收操作,你可以在添加展开和收回操作的时候置顶是否需要真正执行展开和回收操作,具体效果可以参考效果图第2条的第二个,依赖版本请使用tag版本v1.6.1,[查看说明](#v1612019-07-04-120205-更新了如下特性-版本v161可以正常使用) ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.6.1' ``` + 2019-05-20 15:14:04更新,如果你需要展示链接但是不想让链接自动转换成"网页链接"的形式,你可以禁用自动转换功能;如果你希望知道是否满足展开/收起的条件,添加一个监听就好了,依赖版本请使用tag版本1.6.0,[查看说明](#v162019-05-20-151910-更新了如下特性-版本v16可以正常使用) ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.6.0' ``` + 2019-03-14 10:25:57更新,修复在有些手机上偶尔会出现白屏,加载不出内容的情况,依赖版本请使用tag版本1.5.3 ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.5.3' ``` + 2018-10-09 17:20:45 更新,新增对展开和回收的点击事件监听,依赖版本请使用tag版本v1.5.2 ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.5.2' ``` + 2018-09-28 09:37:28 更新,优化了将"展开"和"收回"固定最右显示时中间空格数量的计算方式,依赖版本请使用tag版本v1.5.1,[查看说明](#新特性额外说明) ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.5.1' ``` + 2018-09-27 09:18:14 更新 + 修复了不添加事件监听,点击链接会直接打开百度页面; + 在demo中添加自定义设置显示文本的功能,您可以自己设置需要显示的文本,然后查看对应的显示效果; + 新增了"展开"和"收回"按钮始终居右的功能,具体效果请查看效果图的第9条,依赖版本请使用tag版本v1.5,[查看说明](#新特性额外说明) ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.5' ``` + 2018-09-22 23:32:16 更新,新增自定义规则解析,具体效果请查看效果图的第10条,依赖版本请使用tag版本v1.4,[查看说明](#新特性额外说明) ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.4' ``` + 2018-09-21 11:51:24 更新,优化了demo的代码逻辑和注释 + 2018-09-21 08:45:13 更新,修复了自定义设置展开和收回内容无效的问题,依赖请使用tag版本v1.3.1 ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.3.1' ``` + 2018-09-20 16:31:13 更新 + 一、提供了在RecyclerView中使用的时候,对之前状态的保存的功能支持,[查看说明](#新特性额外说明); + 二、新增对@用户和链接的处理,用户可以设置不对这些内容进行识别,仅仅使用展开和收回功能; + 三、优化的demo的效果,请大家重新下载apk进行体验。 + 四、如果你没有设置对链接的监听,会默认调用系统浏览器打开链接 + 五、支持语言国际化 + 六、最新版请使用v1.3 + 2018-09-03 17:39:56 修复一些bug,链接sheSpan位置错误,未生成release,等待下次修复其他bug一起打tag依赖包,使用请本地依赖使用 + 2018-08-31 17:31:56 优化设置padding对宽度造成的影响,依赖请使用tag版本v1.2 ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.2' ``` + 2018-08-31 11:21:22 在V1.0的基础上进行了优化,依赖请使用tag版本v1.1 ```java implementation 'com.github.MZCretin:ExpandableTextView:v1.1' ``` ### 实现效果: <img src="./extra/demo.jpg"/> #### 下面是RecyclerView中的样式,可以保留之前展开和收回的状态 <img src="./extra/demo_gif.gif"/> ### 使用方式: #### Step 1. Add the JitPack repository to your build file Add it in your root build.gradle at the end of repositories: ``` allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` #### Step 2. Add the dependency ``` dependencies { implementation 'com.github.MZCretin:ExpandableTextView:请使用最新版本' } ``` ### demo下载 [Demo下载](https://raw.githubusercontent.com/MZCretin/ExpandableTextView/master/extra/demo.apk) 扫描二维码下载: <img src="./extra/erweima.png"/> ### 代码说明 + 以下属性都可以在xml中设置 ```xml <!--保留的行数--> <attr name="ep_max_line" format="integer" /> <!--是否需要展开--> <attr name="ep_need_expand" format="boolean" /> <!--是否需要收起 这个是建立在开启展开的基础上的--> <attr name="ep_need_contract" format="boolean" /> <!--是否需要@用户 --> <attr name="ep_need_mention" format="boolean" /> <!--是否需要对链接进行处理 --> <attr name="ep_need_link" format="boolean" /> <!--是否需要动画--> <attr name="ep_need_animation" format="boolean" /> <!--是否需要将连接转换成网页链接显示 默认为true--> <attr name="ep_need_convert_url" format="boolean" /> <!--是否需要自定义规则--> <attr name="ep_need_self" format="boolean" /> <!--收起的文案--> <attr name="ep_contract_text" format="string" /> <!--展开的文案--> <attr name="ep_expand_text" format="string" /> <!--展开的文字的颜色--> <attr name="ep_expand_color" format="color" /> <!--收起的文字的颜色--> <attr name="ep_contract_color" format="color" /> <!--在收回和展开前面添加的内容的字体颜色--> <attr name="ep_end_color" format="color" /> <!--链接的文字的颜色--> <attr name="ep_link_color" format="color" /> <!--@用户的文字的颜色--> <attr name="ep_mention_color" format="color" /> <!--自定义规则的文字的颜色--> <attr name="ep_self_color" format="color" /> <!--链接的图标--> <attr name="ep_link_res" format="reference"/> <!--是否需要永远将展开或者收回放置在最后边--> <attr name="ep_need_always_showright" format="boolean" /> //布局文件中使用 可选 也可以在代码中设置 <com.ctetin.expandabletextviewlibrary.ExpandableTextView android:id="@+id/ep_01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="15dp" android:lineSpacingExtra="4dp" android:textSize="14sp" <!--开始展开的行数 --> app:ep_max_line="4" <!--是否需要对链接进行识别--> app:ep_need_link="true" <!--是否需要对@用户进行识别--> app:ep_need_mention="true" <!--是否需要收回功能--> app:ep_need_contract="true" <!--是否需要展开和收回的动画--> app:ep_need_animation="true" <!--展开文字的颜色--> app:ep_expand_color="@color/colorAccent" <!--收回的文字描述--> app:ep_contract_text="收回" <!--在展开前可添加tips tips的文字颜色--> app:ep_end_color="@color/colorAccent" <!--展开的文字描述--> app:ep_expand_text="展开" <!--被识别出来的链接的颜色--> app:ep_link_color="@color/colorAccent" <!--被识别出来的链接的前面的图标资源--> app:ep_link_res="@color/colorAccent" <!--展开的文字的颜色--> app:ep_contract_color="@color/colorAccent" <!--@用户的文字的颜色--> app:ep_mention_color="@color/colorAccent" <!--是否需要将连接转换成网页链接显示--> app:ep_need_convert_url="false" <!--是否需要自定义规则--> app:ep_need_self="true" <!--自定义规则的文字的颜色--> app:ep_self_color="@color/colorAccent" <!--是否需要永远将展开或者收回放置在最后边--> app:ep_need_always_showright="true" <!--是否需要展开功能--> app:ep_need_expand="false" /> ``` + java代码 ```java /** * 正常的使用 */ ExpandableTextView expandableTextView = findViewById(R.id.ep_01); //需要显示的内容 String yourText = " 我所认识的中国,强大、友好。@奥特曼 “一带一路”经济带带动了沿线国家的经济发展,促进我国与他国的友好往来和贸易发展,可谓“双赢”。http://www.baidu.com 自古以来,中国以和平、友好的面孔示人。汉武帝派张骞出使西域,开辟丝绸之路,增进与西域各国的友好往来。http://www.baidu.com 胡麻、胡豆、香料等食材也随之传入中国,汇集于中华美食。@RNG 漠漠古道,驼铃阵阵,这条路奠定了“一带一路”的基础,让世界认识了中国。"; //将内容设置给控件 expandableTextView.setContent(yourText); //xml中的属性也可以通过代码设置 比如 expandableTextView.setmNeedExpend(true); //还有很多。。。。 //添加点击监听 expandableTextView.setLinkClickListener(new ExpandableTextView.OnLinkClickListener() { @Override public void onLinkClickListener(LinkType linkType, String content,String selfContent) { //根据类型去判断 if (type.equals(LinkType.LINK_TYPE)) { Toast.makeText(MainActivity.this, "你点击了链接 内容是:" + content, Toast.LENGTH_SHORT).show(); } else if (type.equals(LinkType.MENTION_TYPE)) { Toast.makeText(MainActivity.this, "你点击了@用户 内容是:" + content, Toast.LENGTH_SHORT).show(); } else if (type.equals(LinkType.SELF)) { Toast.makeText(MainActivity.this, "你点击了自定义规则 内容是:" + content + " " + selfContent, Toast.LENGTH_SHORT).show(); } } }); //添加展开和收回操作 expandableTextView.setExpandOrContractClickListener(type -> { if (type.equals(StatusType.STATUS_CONTRACT)) { Toast.makeText(MainActivity.this, "收回操作", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "展开操作", Toast.LENGTH_SHORT).show(); } }); //监听是否初始化完成 在这里可以获取是否支持展开/收回 expandableTextView.setOnGetLineCountListener(new ExpandableTextView.OnGetLineCountListener() { @Override public void onGetLineCount(int lineCount, boolean canExpand) { Toast.makeText(MainActivity.this, "行数:" + lineCount + " 是否满足展开条件:" + canExpand, Toast.LENGTH_SHORT).show(); } }); //添加展开和收回操作 只触发点击 不真正触发展开和收回操作 expandableTextView.setExpandOrContractClickListener(type -> { if (type.equals(StatusType.STATUS_CONTRACT)) { Toast.makeText(MainActivity.this, "收回操作,不真正触发收回操作", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "展开操作,不真正触发展开操作", Toast.LENGTH_SHORT).show(); } },false); ``` ### 新特性额外说明 ### V1.6.1:2019-07-04 12:02:05 更新了如下特性 版本v1.6.1+可以正常使用 如果你需要监听展开和回收的时间监听,但是不需要控件真正的执行展开和回收操作,你可以在添加展开和收回操作的时候置顶是否需要真正执行展开和回收操作,具体效果可以参考效果图第2条的第二个控件效果: ```java //添加展开和收回操作 只触发点击 不真正触发展开和收回操作 expandableTextView.setExpandOrContractClickListener(type -> { if (type.equals(StatusType.STATUS_CONTRACT)) { Toast.makeText(MainActivity.this, "收回操作,不真正触发收回操作", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "展开操作,不真正触发展开操作", Toast.LENGTH_SHORT).show(); } },false); ``` ### V1.6:2019-05-20 15:19:10 更新了如下特性 版本v1.6+可以正常使用 如果你需要展示链接但是不想让链接自动转换成"网页链接"的形式,你可以禁用自动转换功能,具体效果可以参考效果图第11条;如果你希望知道是否满足展开/收起的条件,添加一个监听就好了: ```java //监听是否初始化完成 在这里可以获取是否支持展开/收回 views[10].setOnGetLineCountListener(new ExpandableTextView.OnGetLineCountListener() { @Override public void onGetLineCount(int lineCount, boolean canExpand) { Toast.makeText(MainActivity.this, "行数:" + lineCount + " 是否满足展开条件:" + canExpand, Toast.LENGTH_SHORT).show(); } }); ``` ### V1.5: 2018-09-27 09:20:28 更新了如下特性 版本v1.5+可以正常使用 如果你需要将"展开"和"收回"始终居右显示,你需要开启它,具体效果可以参考效果图第9条 ``` //需要先开启始终靠右显示的功能 views[8].setNeedAlwaysShowRight(true); //或者在xml中开启 app:ep_need_always_showright="true" ``` ### V1.4:2018-09-22 23:32:16 更新了如下特性 版本v1.4+可以正常使用 如果你觉得目前@用户和网页链接两种形式并不能完全满足你的业务,那么我提供了一个新的自定义规则给你,让你可以更加灵活的去适应自己的业务。 比如上面实现效果的第9条中,我们通过自定义规则对文字中的"--习大大"和"Github地址"进行了自定义规则,让其高亮显示并且可以添加触发相应的事件。 具体做法是: * 在一段文字中将你需要处理的文字做上特殊标记,,标记的规则就是\[显示的内容\](动作),这个标记的规则可以交给后台给你处理,或者你自己处理也可以。 * 比如上文中的"Github地址",那么标记后就是这样的 \[Github地址\]\( https://github.com/MZCretin/ExpandableTextView ),这样在控件中显示的就只是Github地址,可以点击,当点击之后,会将"显示的内容"和"动作"都通过接口回调的方式回传给调用者自己处理; * 再比如上文中的"--习大大",那么标记后就是这样的 \[--习大大\](schema_jump_userinfo),这样控件中只会显示"--习大大",然后根据后面的动作去做处理,比如这是一个用户,可以跳转到这个用户的个人详情页面。 * 默认不会对自定义规则进行解析,如需开启,请开启此功能: ``` <!--是否需要自定义规则--> app:ep_need_self="true" ``` ### V1.3:2018-09-20 16:31:13 更新了如下特性 版本v1.3+可以正常使用 如果你希望在RecyclerView(或者ListView)中使用,请认真阅读demo中在RecyclerView中的使用,细节都在注释中。 如果你需要在列表中保留之前的展开或收回状态,特殊说明的有以下几点: * 一、实现 ExpandableStatusFix * 二、在你的model中定义一个 private StatusType status; * 三、实现对应的方法,将你刚刚定义的status返回, * 四、并在给ExpandableTextView设置内容之前,调用bind方法 ### 实现思路讲解 **简书:** [【需求解决系列之三】Android 自定义可展开收回的ExpandableTextView](https://www.jianshu.com/p/5519fbab6907) **掘金:** [【需求解决系列之三】Android 自定义可展开收回的ExpandableTextView](https://juejin.im/post/5b876a4de51d4571c5137660)
0
tang-jie/NettyRPC
NettyRPC is high performance java rpc server base on Netty,using kryo,hessian,protostuff support message serialization.
2016-07-28T14:56:15Z
null
# NettyRPC Project high performance java rpc server base on netty framework,using kryo,hessian,protostuff support rpc message serialization. ---------- ## NettyRPC开发指南 有兴趣的同学可以参考:[NettyRPC入门手册](https://github.com/tang-jie/NettyRPC/wiki/NettyRPC%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97)。 ---------- ## NettyRPC 1.0 Build 2016/6/25 ### NettyRPC 1.0 中文简介: **NettyRPC是基于Netty构建的RPC系统,消息网络传输支持目前主流的编码解码器** * NettyRPC基于Java语言进行编写,网络通讯依赖Netty。 * RPC服务端采用线程池对RPC调用进行异步回调处理。 * 服务定义、实现,通过Spring容器进行加载、卸载。 * 消息网络传输除了JDK原生的对象序列化方式,还支持目前主流的编码解码器:kryo、hessian。 * Netty网络模型采用主从Reactor线程模型,提升RPC服务器并行吞吐性能。 * 多线程模型采用guava线程库进行封装。 ### NettyRPC 1.0 English Introduction: **NettyRPC is based on Netty to build the RPC system, the message network transmission support the current mainstream codec.** * NettyRPC based on Java language, network communications rely on Netty. * RPC server using the thread pool on the RPC call asynchronous callback processing. * service definition, implementation, through the Spring container(IOC) loading, unloading. * message network transmission in addition to JDK native object serialization mode, but also to support the current mainstream of the codec: kryo, hessian. * Netty network model uses the master-slave Reactor thread model, to improve the performance of RPC server parallel throughput. * multi thread model using guava thread framework. ---------- ## NettyRPC 2.0 Build 2016/10/7 ### NettyRPC 2.0 中文简介: **NettyRPC 2.0是基于NettyRPC 1.0 在Maven下构建的RPC系统,在原有1.0版本的基础上对代码进行重构升级,主要改进点如下:** * RPC服务启动、注册、卸载支持通过Spring中的nettyrpc标签进行统一管理。 * 在原来编码解码器:JDK原生的对象序列化方式、kryo、hessian,新增了:protostuff。 * 优化了NettyRPC服务端的线程池模型,支持LinkedBlockingQueue、ArrayBlockingQueue、SynchronousQueue,并扩展了多个线程池任务处理策略。 * NettyRPC服务端加入JMX监控支持。 ### NettyRPC 2.0 English Introduction: **NettyRPC 2.0 is based on NettyRPC 1.0 under the Maven to build the RPC system, based on the original 1.0 version of the code to refactoring, the main improvements are as follows:** * RPC service startup, registration, uninstall support through the nettyrpc Spring tags for unified management. * in the original codec: JDK native object serialization mode, kryo, hessian, added: protostuff. * optimize the NettyRPC server's thread pool model, support LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, and expand the various thread pool task processing strategy. * NettyRPC JMX monitoring support. ---------- ## NettyRPC 2.1 Build 2017/3/23 **在NettyRPC 2.0的基础上新增NettyRPC异步回调功能模块:** * 基于cglib生成异步代理Mock对象,针对一些极端耗时的RPC调用场景进行异步回调,从而提高客户端的并行吞吐量。 ---------- ## NettyRPC 2.2 Build 2017/5/2 **在2.1版本的基础上,提供NettyRPC服务端接口能力展现功能:** * 接口能力展现功能模块部署在服务端的18886端口,可以在浏览器中输入:http://ip地址:18886/NettyRPC.html 进行查看。 * 比如在浏览器的地址栏中输入:http://10.1.1.76:18886/NettyRPC.html, 可以查看NettyRPC服务器对外暴露的服务能力接口信息。 * NettyRPC客户端支持重连功能:这点主要是针对RPC服务器宕机的情形下,RPC客户端可以检测链路情况,如果链路不通,则自动重连(重连重试的时间默认为10s)。 ---------- ## NettyRPC 2.3 Build 2017/7/28 **在NettyRPC 2.2的基础上新增NettyRPC过滤器功能:** * 进一步合理地分配和利用服务端的系统资源,NettyRPC可以针对某些特定的RPC请求,进行过滤拦截。 * 具体过滤器要实现:com.newlandframework.rpc.filter.Filter接口定义的方法。 * 被拦截到的RPC请求,NettyRPC框架会抛出com.newlandframework.rpc.exception.RejectResponeException异常,可以根据需要进行捕获。 * spring配置文件中的nettyrpc:service标签,新增filter属性,用来定义这个服务对应的过滤器的实现。当然,filter属性是可选的。 ---------- ## NettyRPC 2.4 Build 2017/8/31 **在NettyRPC 2.3的基础上,增强了RPC服务端动态加载字节码时,对于热点方法的拦截判断能力:** * 在之前的NettyRPC版本中,RPC服务端集成了一个功能:针对Java HotSpot虚拟机的热加载特性,可以动态加载、生成并执行客户端的热点代码。然而却有一定的风险。因为这些代码中的某些方法,可能存在一些危及服务端安全的操作,所以有必要对这些方法进行拦截控制。 * 技术难点在于:如何对服务端生成的字节码文件进行渲染加工?以往传统的方式,都是基于类进行代理渲染,而这次是针对字节码文件进行织入渲染,最终把拦截方法织入原有的字节码文件中。 * 对字节码操作可选的方案有Byte Code Engineering Library (BCEL)、ASM等。最终从执行性能上考虑,决定采用偏向底层的ASM,对字节码进行渲染织入增强,以节省性能开销。最终通过类加载器,重新把渲染后的字节码,载入运行时上下文环境。 * 具体方法拦截器要实现:com.newlandframework.rpc.compiler.intercept.Interceptor接口定义的方法。NettyRPC框架提供了一个简易的拦截器实现:SimpleMethodInterceptor,可以在这里加入你的拦截判断逻辑。 ---------- ## NettyRPC 2.5 Build 2017/10/13 **在NettyRPC 2.4的基础上,基于JMX(Java Management Extensions)技术,对NettyRPC的服务端进行调用监控,加强服务端对调用请求的分析统计能力:** * 是否开启JMX监控,可以通过环境变量:nettyrpc.jmx.invoke.metrics来控制(为0表示关闭JMX监控;非0表示打开JMX监控)。对应NettyRPC系统变量为:RpcSystemConfig.SYSTEM_PROPERTY_JMX_INVOKE_METRICS。如果开启JMX监控,启动的时候,控制台上会打印JMX URL信息。 * JMX监控的URL地址格式为:service:jmx:rmi:///jndi/rmi://服务器ip地址:1098/NettyRPCServer。比如:service:jmx:rmi:///jndi/rmi://10.1.8.5:1098/NettyRPCServer,然后可以在jconsole中,通过JMX对NettyRPC服务端的调用情况进行监控。 * 目前服务端监控的维度主要有:调用次数、调用成功次数、调用失败次数、过滤拦截次数、调用时长、调用最大时长、调用最小时长、错误明细、最后一次错误发生的时间、调用时长统计数组区间。 * 目前暂时只支持jconsole方式,后续会考虑在NettyRPC内部架设HTTP服务器,以网页的形式直观地展示监控数据信息。 * 为了提高JMX数据统计监控的精度,服务端采用了临界区对RPC请求进行隔离。但是如果客户端是通过AsyncInvoker异步调用的方式进行RPC请求的话,则会把异步并行加载强制转成异步串行加载。这并不是我们希望看到的。 * 后续会针对异步并行加载串行化的问题,在服务端采用哈希队列的方式隔离管理临界区对象,减少JMX监控对异步调用的侵蚀影响。 ---------- ## NettyRPC 2.6 Build 2017/10/30 **在NettyRPC 2.5的基础上,针对JMX监控统计RPC调用指标的场景,采用临界区哈希分片加锁算法,降低锁的颗粒度,减少JMX监控对RPC调用的影响。** * 哈希分片加锁算法,采用空间换时间策略。其主要思路参考借鉴了JDK中ConcurrentHashMap的实现,经过优化之后,NettyRPC的JMX监控统计性能会有很大的提升。 * 哈希分片加锁算法中,哈希分片的个数,通过环境变量nettyrpc.jmx.metrics.hash.nums进行设定,默认为8个哈希桶。当然,你可以改成其它大于1的整数,数值越大,哈希冲突越小,JMX监控的性能越好,但是代价是,JVM堆内存空间有所损耗。 * 经过哈希分片加锁算法优化之后,特别是对异步并行调用(AsyncInvoker)的侵蚀大幅度降低,对整个NettyRPC系统而言,统计性能也有质的提升。一方面不影响原有系统的调用吞吐量,另外一方面也不会降低JMX的统计精度。 * 默认加锁采用非公平锁,你可以通过设置环境变量nettyrpc.jmx.metrics.lock.fair为1,改成公平锁。在高并发调用的场景,建议采用非公平锁。 ---------- ## NettyRPC 2.7 Build 2017/11/2 **在NettyRPC 2.6的基础上,新增内嵌HTTP服务器,用于展示NettyRPC模块调用监控指标。** * 利用JMX接口,从NettyRPC服务端获取模块调用的监控数据。 * 在环境变量nettyrpc.jmx.invoke.metrics为1的前提下,在浏览器输入URL:http://ip地址:18886/NettyRPC.html/metrics。 即可查看NettyRPC系统模块间的调用统计情况。 * 可以按F5刷新统计界面,查看最新的统计指标。 ---------- ## NettyRPC 2.8 Build 2018/2/2 **在NettyRPC 2.7的基础上,加入RPC请求过滤器链和监听器链功能** * 通过监听器链和过滤器链,可以对RPC客户端请求进行过滤和监听。具体参考[NettyRPC入门手册](https://github.com/tang-jie/NettyRPC/wiki/NettyRPC%E5%BC%80%E5%8F%91%E6%8C%87%E5%8D%97)中的“RPC请求链式处理”章节。 * 过滤器链封装类(com.newlandframework.rpc.filter.ModuleFilterChainWrapper)、监听器链封装类(com.newlandframework.rpc.listener.ModuleListenerChainWrapper)通过spring依赖注入。 * NettyRPC内置了一些链式过滤器:com.newlandframework.rpc.filter.support.ClassLoaderChainFilter、com.newlandframework.rpc.filter.support.EchoChainFilter,以及链式监听器:com.newlandframework.rpc.listener.support.ModuleListenerAdapter。具体可以根据需求进行扩展添加。 ---------- ## NettyRPC相关博客文章 if you want to know more details,okey!you can see my blog: **Talk about how to use Netty nio frameworks development high performance RPC server** **谈谈如何使用Netty开发实现高性能的RPC服务器** http://www.cnblogs.com/jietang/p/5615681.html **By Netty to realize high performance RPC server optimization of the message serialization** **Netty实现高性能RPC服务器优化篇之消息序列化** http://www.cnblogs.com/jietang/p/5675171.html **Based on Netty to develop RPC server design experience** **基于Netty打造RPC服务器设计经验谈** http://www.cnblogs.com/jietang/p/5983038.html ---------- ## Author 唐洁(tangjie) http://www.cnblogs.com/jietang/ ---------- ## License [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
0
xaecbd/KCenter
KCenter(KafkaCenter) is a unified platform for kafka cluster management and maintenance, producer / consumer monitoring, and use of ecological components(ksql/kafka connect).it's kafkacenter(kafka center).
2020-03-21T02:15:06Z
null
Language: :us: - :[cn](./README_zh.md): # KCenter ![](https://img.shields.io/badge/java-1.8+-green.svg) ![](https://img.shields.io/badge/maven-3.5+-green.svg) KCenter (previously known as KafkaCenter) is a unified one-stop platform for Apache Kafka cluster management and maintenance, producer/consumer monitoring, and use of ecological components. :loudspeaker::loudspeaker::loudspeaker: Now we have deployed this product on [**Azure**](https://azuremarketplace.microsoft.com/zh-cn/marketplace/apps/newegginc1646343565758.kafka_center?tab=Overview)/[**AWS**](https://aws.amazon.com/marketplace/pp/prodview-g6kmcxajfu3bw?sr=0-9&ref_=beagle&applicationId=AWSMPContessa) :loudspeaker::loudspeaker::loudspeaker: :fire::fire::fire: **Commercial products have better functions and technical support.** if you have any needs, including aws support, personalized development:technologist:. You can create an [issue](https://github.com/xaecbd/KCenter/issues/new) and we will reply as soon as possible. **Table of Contents** - [Why Should I Use KCenter?](#why-should-i-use-KCenter) - [Main Features](#main-features) - [Application Config](#application-config) - [Getting Started](#getting-started) - [1. Init](#1-init) - [2. Run](#2-run) - [3. Access UI](#3-access-ui) - [Building KCenter and/or Contributing Code](#building-KCenter-andor-contributing-code) - [Documentation](#documentation) - [Changelog](#changelog) - [Questions? Problems? Suggestions?](#questions-problems-suggestions) ## Why Should I Use KCenter? You have a **Kafka cluster** and want to - monitor producers and consumers with graphs and the ability to easily configure email alerts for thresholds - let your users request topics and monitor them themselves in a simple web UI - access the Kafka ecosystem (Kafka, KSQL, Kafka Connect, Kafka Manager) in one combined UI All you need is a MySQL DB in the background where KCenter can store its configuration. If you want to use the monitoring functionalities, you additionally need an Elasticsearch installation. Then, just download our Docker image (see HowTo below) and off you go! *\* Note: KCenter does not yet support authenticating to a secured Kafka cluster (SASL or OAuth), we're working on it though.* ## Main Features ![avatar](docs/images/kafka-center.png) ![avatar](docs/images/screenshot.png) - **Home** -> Overview of all configured Kafka clusters as well as high-level monitoring information. - **Favorites** -> Direct access to the monitoring statistics of your favorite topics. - **Topic** -> View your own topics or *apply for new topics. You can also both consume messages and mock new records via web UI into your topics here!* - **Monitor** -> Statistics about production and consumption of your topics. *There is an additional possibility to configure alerts (which optionally trigger emails) for arbitrary consumption delay thresholds here!* - **Kafka Connect** -> Create and maintain your own Kafka Connect jobs (needs an external Kafka Connect service to connect to). - **KSQL** -> Create and maintain your own KSQL jobs (needs an external KQL service to connect to). - **Approve** -> Users can view their topic creation requests here, administrators can manage and approve the requests. - **Settings** -> Maintain users and teams (accessible by administrators only). *You can also use an external OAuth solution for the user management.* - **Kafka Manager** -> Maintain Kafka cluster information (embedded UI from the popular open-source tool [Kafka Manager](https://github.com/yahoo/CMAK)). ## Application Config The main application configuration is done in a central `application.properties` file. Have look at our [detailed example here](KCenter-Core/src/main/resources/application.properties). ## Getting Started **Important**: The application **needs a MySQL database** to store all configurations. Before you begin, make sure that you have it either installed on the same host or that there's an instance available somewhere else. The exact location can then be configured via the `spring.datasource.url` inside the `application.properties`. (There is *no* MySQL service included in the Docker image.) Resource|Dependencies|Use ---|---|--- MySQL|must|Stores all configuration information (users, teams, clusters, etc.) Elasticsearch (7.0+)|optional|Stores monitoring information (cluster metrics, consumption lag visualization, etc.) Email server|optional|Email notifications (topic requests & approvals, configured consumer alerts) ### 1. Init #### Create database and table Execute the provided [table_script.sql](KCenter-Core/sql/table_script.sql) on your MySQL instance to create the database and all necessary tables. #### Edit config Download the provided [application.properties](KCenter-Core/src/main/resources/application.properties) example and adapt the config to your needs. ### 2. Run #### Option A (**recommended**): Docker The following command assumes that you have your adapted `application.properties` inside the same folder: ``` docker run -d \ -p 8080:8080 \ --name KCenter \ -v ${PWD}/application.properties:/opt/app/kafka-center/config/application.properties \ xaecbd/kafka-center:2.3.0 ``` #### Option B: Local **Important**: Make sure you have installed a **JRE 8** or higher and download the most recent [release package](https://github.com/xaecbd/KCenter/releases). ``` $ git clone https://github.com/xaecbd/KCenter.git $ cd KCenter $ mvn clean package -Dmaven.test.skip=true $ cd KCenter\KCenter-Core\target $ java -jar KCenter-Core-2.3.0-SNAPSHOT.jar ``` ### 3. Access UI The application UI is published on port *8080*. Visit `http://localhost:8080` (or insert the IP/URL of the host you deployed on) and log in with the default administrator:**user/pw = admin/admin** ## Building KCenter and/or Contributing Code We're happy if you want to play around and build KCenter locally, or even get involved in shaping and developing KCenter further. The [Contributing Guidelines](./CONTRIBUTING.md) will help to get you started. ## Documentation For more information, see the README in [KCenter/docs](./docs).<br/> For information about user guide the documentation, see the UserGuide in [KCenter/docs/UserGuide](./docs/UserGuide.md) For information about module the documentation, see the Module in [KCenter/docs/Module](./docs/Module.md).<br/> For information about kafka connect ui, see docs in [KafkaConnectUi](./docs/KafkaConnectUi.md). *Note that we open-sourced our tool very recently and did not translate all the documents to English yet. (We are happy about contributions in this area as well if you're motivated!)* ## Changelog See the separate [Changelog](./CHANGELOG.md). ## Questions? Problems? Suggestions? If you found a bug, want to request a feature or have a question, please create an [issue](https://github.com/xaecbd/KCenter/issues/new). Try to make sure someone else hasn't already created an issue for the same topic beforehand.
0
electronicarts/ea-async
EA Async implements async-await methods in the JVM.
2015-12-22T21:16:08Z
null
EA Async ============ [![Release](https://img.shields.io/github/release/electronicarts/ea-async.svg)](https://github.com/electronicarts/ea-async/releases) [![Maven Central](https://img.shields.io/maven-central/v/com.ea.async/ea-async-parent.svg)](http://repo1.maven.org/maven2/com/ea/async/) [![Javadocs](https://img.shields.io/maven-central/v/com.ea.async/ea-async.svg?label=Javadocs)](http://www.javadoc.io/doc/com.ea.async/ea-async) [![Build Status](https://img.shields.io/travis/electronicarts/ea-async.svg)](https://travis-ci.org/electronicarts/ea-async) EA Async implements Async-Await methods in the JVM. It allows programmers to write asynchronous code in a sequential fashion. It is heavily inspired by Async-Await on the .NET CLR, see [Asynchronous Programming with Async and Await](https://msdn.microsoft.com/en-us/library/hh191443.aspx) for more information. Who should use it? ------ EA Async should be used to write non-blocking asynchronous code that makes heavy use of CompletableFutures or CompletionStage. It improves scalability by freeing worker threads while your code awaits other processes; And improves productivity by making asynchronous code simpler and more readable. Developer & License ====== This project was developed by [Electronic Arts](http://www.ea.com) and is licensed under the [BSD 3-Clause License](LICENSE). Examples ======= #### With EA Async ```java import static com.ea.async.Async.await; import static java.util.concurrent.CompletableFuture.completedFuture; public class Store { public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost) { if(!await(bank.decrement(cost))) { return completedFuture(false); } await(inventory.giveItem(itemTypeId)); return completedFuture(true); } } ``` In this example `Bank.decrement` returns `CompletableFuture<Boolean>` and `Inventory.giveItem` returns `CompletableFuture<String>` EA Async rewrites the calls to `Async.await` making your methods non-blocking. The methods look blocking but are actually transformed into asynchronous methods that use CompletableFutures to continue the execution as intermediary results arrive. #### Without EA Async This is how the first example looks without EA Async. It is a bit less readable. ```java import static java.util.concurrent.CompletableFuture.completedFuture; public class Store { public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost) { return bank.decrement(cost) .thenCompose(result -> { if(!result) { return completedFuture(false); } return inventory.giveItem(itemTypeId).thenApply(res -> true); }); } } ``` This is a small example... A method with a few more CompletableFutures can look very convoluted. EA Async abstracts away the complexity of the CompletableFutures. #### With EA Async (2) So you like CompletableFutures? Try converting this method to use only CompletableFutures without ever blocking (so no joining): ```java import static com.ea.async.Async.await; import static java.util.concurrent.CompletableFuture.completedFuture; public class Store { public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost) { if(!await(bank.decrement(cost))) { return completedFuture(false); } try { await(inventory.giveItem(itemTypeId)); return completedFuture(true); } catch (Exception ex) { await(bank.refund(cost)); throw new AppException(ex); } } } ``` Got it? Send it [to us](https://github.com/electronicarts/ea-async/issues/new). It probably looks ugly... Getting started --------------- EA Async currently supports JDK 8-10. It works with Java and Scala and should work with most JVM languages. The only requirement to use EA Async is that must be used only inside methods that return `CompletableFuture`, `CompletionStage`, or subclasses of `CompletableFuture`. ### Using with maven ```xml <dependency> <groupId>com.ea.async</groupId> <artifactId>ea-async</artifactId> <version>1.2.3</version> </dependency> ``` ### Gradle ``` 'com.ea.async:ea-async:1.2.3' ``` ### Instrumenting your code #### Option 1 - JVM parameter Start your application with an extra JVM parameter: `-javaagent:ea-async-1.2.3.jar` ``` java -javaagent:ea-async-1.2.3.jar -cp your_claspath YourMainClass args... ``` It's recommended to add this as a default option to launchers in IntelliJ projects that use ea-async. #### Option 2 - Runtime On your main class or as early as possible, call at least once: ``` Async.init(); ``` Provided that your JVM has the capability enabled, this will start a runtime instrumentation agent. If you forget to invoke this function, the first call to `await` will initialize the system (and print a warning). This is a solution for testing and development, it has the least amount of configuration. It might interfere with JVM debugging. This alternative is present as a fallback. #### Option 3 - Run instrumentation tool The ea-async-1.2.3.jar is a runnable jar that can pre-instrument your files. Usage: ```bash java -cp YOUR_PROJECT_CLASSPATH -jar ea-async-1.2.3.jar classDirectory ``` Example: ```bash java -cp guava.jar;commons-lang.jar -jar ea-async-1.2.3.jar target/classes ``` After that all the files in target/classes will have been instrumented. There will be no references to `Async.await` and `Async.init` left in those classes. #### Option 4 - Build time instrumentation, with Maven - Preferred Use the [ea-async-maven-plugin](maven-plugin). It will instrument your classes in compile time and remove all references to `Async.await` and `Async.init()`. With build time instrumentation your project users won't need to have EA Async in their classpath unless they also choose to use it. This means that EA Async <i>does not need to be a transitive dependency</i>. This is the best option for libraries and maven projects. ```xml <build> <plugins> <plugin> <groupId>com.ea.async</groupId> <artifactId>ea-async-maven-plugin</artifactId> <version>1.2.3</version> <executions> <execution> <goals> <goal>instrument</goal> <goal>instrument-test</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ```
0
knightliao/disconf
Distributed Configuration Management Platform(分布式配置管理平台)
2014-05-30T09:39:27Z
null
Disconf ======= [![Apache License 2](https://img.shields.io/badge/license-ASF2-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0.txt) [![Build Status](https://travis-ci.org/knightliao/disconf.svg?branch=master)](https://travis-ci.org/knightliao/disconf) [![Coverage Status](https://coveralls.io/repos/knightliao/disconf/badge.png?branch=master)](https://coveralls.io/r/knightliao/disconf?branch=master) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.baidu.disconf/disconf-client/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/com.baidu.disconf/disconf-client) Distributed Configuration Management Platform(分布式配置管理平台) 专注于各种「分布式系统配置管理」的「通用组件」和「通用平台」, 提供统一的「配置管理服务」 ![](http://ww3.sinaimg.cn/mw1024/60c9620fjw1esvjzny1rmj20aj061t9a.jpg) 包括 **百度**、**滴滴出行**、**银联**、**网易**、**拉勾网**、**苏宁易购**、**顺丰科技** 等知名互联网公司正在使用! [「disconf」在「2015 年度新增开源软件排名 TOP 100(OSC开源中国提供)」中排名第16强。](http://www.oschina.net/news/69808/2015-annual-ranking-top-100-new-open-source-software) ## 主要目标: - 部署极其简单:同一个上线包,无须改动配置,即可在 多个环境中(RD/QA/PRODUCTION) 上线 - 部署动态化:更改配置,无需重新打包或重启,即可 实时生效 - 统一管理:提供web平台,统一管理 多个环境(RD/QA/PRODUCTION)、多个产品 的所有配置 - 核心目标:一个jar包,到处运行 ## demos && 文档 && 协作 - demos: https://github.com/knightliao/disconf-demos-java - wiki: https://github.com/knightliao/disconf/wiki - 文档: http://disconf.readthedocs.io - 协作开发: 在 master 分支上提pull request - 提问题: https://github.com/knightliao/disconf/issues 提issue ## 版本 - dev(dev branch): 2.6.36 - master(latest && cooperate && contribute branch):2.6.36 - stable(release && stable branch): 2.6.36 ## 功能特点 ## - 支持配置(配置项+配置文件)的分布式化管理 - 配置发布统一化 - 配置发布、更新统一化: - 同一个上线包 无须改动配置 即可在 多个环境中(RD/QA/PRODUCTION) 上线 - 配置存储在云端系统,用户统一管理 多个环境(RD/QA/PRODUCTION)、多个平台 的所有配置 - 配置更新自动化:用户在平台更新配置,使用该配置的系统会自动发现该情况,并应用新配置。特殊地,如果用户为此配置定义了回调函数类,则此函数类会被自动调用。 - 极简的使用方式(注解式编程 或 XML无代码侵入模式):我们追求的是极简的、用户编程体验良好的编程方式。目前支持两种开发模式:基于XML配置或者基于注解,即可完成复杂的配置分布式化。 注:配置项是指某个类里的某个Field字段。 Disconf的功能特点描述图: ![](http://ww4.sinaimg.cn/bmiddle/006oy5Ulgw1f25z80js0fj30fl08uq3z.jpg) [查看大图](http://ww3.sinaimg.cn/mw1024/006oy5Ulgw1f25z80js0fj30fl08uq3z.jpg) ### 其它功能特点 ### - 低侵入性或无侵入性、强兼容性: - 低侵入性:通过极少的注解式代码撰写,即可实现分布式配置。 - 无侵入性:通过XML简单配置,即可实现分布式配置。 - 强兼容性:为程序添加了分布式配置注解后,开启Disconf则使用分布式配置;若关闭Disconf则使用本地配置;若开启Disconf后disconf-web不能正常Work,则Disconf使用本地配置。 - 支持配置项多个项目共享,支持批量处理项目配置。 - 配置监控:平台提供自校验功能(进一步提高稳定性),可以定时校验应用系统的配置是否正确。 ## 大家都在使用disconf ## - [百度](20+条产品线使用) - [滴滴出行(上海/北京)](http://www.xiaojukeji.com/) - [银联] - [网易](http://www.163.com/) - [苏宁易购](http://www.suning.com) (搜索中心数据处理平台) - [顺丰科技] - [更多](http://disconf.readthedocs.io/zh_CN/latest/others/src/contribute.html) ## 他人评价 快速递技术总监: ![http://ww1.sinaimg.cn/bmiddle/60c9620fjw1ergy58j978j20i302u0t2.jpg](http://ww1.sinaimg.cn/mw1024/60c9620fjw1ergy58j978j20i302u0t2.jpg) 润生活总监: ![http://ww4.sinaimg.cn/bmiddle/60c9620fjw1est6ptf2dlj20ab01udfy.jpg](http://ww4.sinaimg.cn/bmiddle/60c9620fjw1est6ptf2dlj20ab01udfy.jpg) 人脉通后端RD: ![http://ww4.sinaimg.cn/bmiddle/60c9620fjw1est6pzqo68j208k05tjrm.jpg](http://ww4.sinaimg.cn/bmiddle/60c9620fjw1est6pzqo68j208k05tjrm.jpg)
0
java8/Java8InAction
null
2013-10-28T23:59:40Z
null
Java8InAction =============== This repository contains all the source code for the examples and quizzes in the book Java 8 in Action: Lambdas, Streams and functional-style programming. You can purchase the book here: [http://manning.com/urma/](http://manning.com/urma/) or on Amazon The source code for all examples can be found in the directory [src/main/java/lambdasinaction](https://github.com/java8/Java8InAction/tree/master/src/main/java/lambdasinaction) * Chapter 1: Java 8: why should you care? * Chapter 2: Passing code with behavior parameterization * Chapter 3: Lambda expressions * Chapter 4: Working with Streams * Chapter 5: Processing data with streams * Chapter 6: Collecting data with streams * Chapter 7: Parallel data processing and performance * Chapter 8: Refactoring, testing, debugging * Chapter 9: Default methods * Chapter 10: Using Optional as a better alternative to null * Chapter 11: CompletableFuture: composable asynchronous programming * Chapter 12: New Date and Time API * Chapter 13: Thinking functionally * Chapter 14: Functional programming techniques * Chapter 15: Blending OOP and FP: comparing Java 8 and Scala * Chapter 16: Conclusions and "where next" for Java * Appendix A: Miscellaneous language updates * Appendix B: Miscellaneous library updates * Appendix C: Performing multiple operations in parallel on a Stream * Appendix D: Lambdas and JVM bytecode We will update the repository as we update the book. Stay tuned! ### Make sure to have JDK8 installed The latest binary can be found here: http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html $ java -version java version "1.8.0_05" Java(TM) SE Runtime Environment (build 1.8.0_05-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode) You can download a preview version here: https://jdk8.java.net/ ### Compile/Run the examples Using maven: $ mvn compile $ cd target/classes $ java lambdasinaction/chap1/FilteringApples Alternatively you can compile the files manually inside the directory src/main/java You can also import the project in your favorite IDE: * In IntelliJ use "File->Open" menu and navigate to the folder where the project resides * In Eclipse use "File->Import->Existing Maven Projects" (also modify "Reduntant super interfaces" to report as Warnings instead of Errors * In Netbeans use "File->Open Project" menu
0
smartyuge/TVSample
1、仿泰捷视频最新TV版 Metro UI效果. 2、仿腾讯视频TV版(云视听·极光) 列表页
2016-10-13T13:39:47Z
null
# Some Android TV related Sample ## [中文README](/README_CN.md) 更多TV相关,欢迎关注公众号: ![这里写图片描述](https://github.com/hejunlin2013/RedPackage/blob/master/image/qrcode.jpg) Android TV开发交流群:135622564 --- ## 1.Imitation of tai jie latest TV video version of the Metro UI Android TV development cannot leave the Metro UI, first to see the latest Thai TV of the members area renderings, belongs to the typical style of Metro, as follows: ![这里写图片描述](/images/device-2016-10-13-170829.png) ### What is the Metro UI: Metro design idea comes from transport airport the sign at the bus stop and subway sign inspired Microsoft design team, design team said Metro is derived from the King County, Washington, us will transport (the King County Metro) logo design, the style of use large fonts, can attract the attention of the audience. Microsoft thinks Metro design [2] topic should be: \"smooth, fast, modern\". Metro also differs from that of Android and iOS icon design. ### Metro UI software Metro is for the convenience of Microsoft developers write Metro style applications and provide a development platform, you can call Microsoft WinRT exposed interface write Metro style applications. And Metro style controls [3] to expand doing standard control methods and properties, some new functions, such as Component One Studio for WinRT XAML, Component One Studio for WinJS. In Windows open Windows application market also use and Metro style interface is recommended for the application. Metro interface, boot after first greeted the first interface, personal feeling is mainly designed to touchscreen devices, but also to use the same in the TV is convenient. We installed in the Desktop program and download in the app store will be displayed in the Metro, so we should regularly or irregularly on the grouping, sequencing, sorting, to facilitate our operation and beautiful interface. Metro interface provides a convenient options at the same time, make the operation more convenient. Today to follow and implement the Metro interface, the following is my implementation effect: ![这里写图片描述](/images/device-2016-10-13-192016.png) ![这里写图片描述](/images/device-2016-10-13-191954.png) GIF: (for has not a good record on TV screen tools, box system generally less than 5.0, some manufacturers have rose to 5.0, I'm using the i71, very old box, based on the API 17, 4.2.2) ![这里写图片描述](/images/metro.gif) ##2.Imitation tencent video TV version (cloud audio-visual aurora) list page( use RecycleView plus GridLayoutManager) To see the latest tencent video TV version of the TV playlist page, as follows: ![这里写图片描述](/images/device-2016-10-17-141123.png) Today to follow and implement the tencent video TV version of the TV playlist page, the following is my implementation effect: ![这里写图片描述](/images/device-2016-10-17-151218.png) ![这里写图片描述](/images/device-2016-10-17-145135.png) gif: ![这里写图片描述](/images/recycleview_1.gif) ![这里写图片描述](/images/recycleview_2.gif) #### Welcome to follow my personal WeChat Official Accounts, useful android technology, conclusion for bug, the FrameWork source code analysis, plugin research, the latest open source projects recommended ![这里写图片描述](https://github.com/hejunlin2013/RedPackage/blob/master/image/qrcode.jpg) License -------- ``` Copyright (C) 2016 hejunlin 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. ```
0
databricks/learning-spark
Example code from Learning Spark book
2014-06-16T04:47:54Z
null
[![buildstatus](https://travis-ci.org/holdenk/learning-spark-examples.svg?branch=master)](https://travis-ci.org/holdenk/learning-spark-examples) Examples for Learning Spark =============== Examples for the Learning Spark book. These examples require a number of libraries and as such have long build files. We have also added a stand alone example with minimal dependencies and a small build file in the mini-complete-example directory. These examples have been updated to run against Spark 1.3 so they may be slightly different than the versions in your copy of "Learning Spark". Requirements == * JDK 1.7 or higher * Scala 2.10.3 - scala-lang.org * Spark 1.3 * Protobuf compiler - On debian you can install with sudo apt-get install protobuf-compiler * R & the CRAN package Imap are required for the ChapterSixExample * The Python examples require urllib3 Python examples === From spark just run ./bin/pyspark ./src/python/[example] Spark Submit === You can also create an assembly jar with all of the dependencies for running either the java or scala versions of the code and run the job with the spark-submit script ./sbt/sbt assembly OR mvn package cd $SPARK_HOME; ./bin/spark-submit --class com.oreilly.learningsparkexamples.[lang].[example] ../learning-spark-examples/target/scala-2.10/learning-spark-examples-assembly-0.0.1.jar [![Learning Spark](http://akamaicovers.oreilly.com/images/0636920028512/cat.gif)](http://www.jdoqocy.com/click-7645222-11260198?url=http%3A%2F%2Fshop.oreilly.com%2Fproduct%2F0636920028512.do%3Fcmp%3Daf-strata-books-videos-product_cj_9781449358600_%2525zp&cjsku=0636920028512)
1
4refr0nt/ESPlorer
Integrated Development Environment (IDE) for ESP8266 developers
2014-12-29T17:14:49Z
null
# ESPlorer [![Build Actions Status](https://github.com/4refr0nt/ESPlorer/workflows/build/badge.svg)](https://github.com/4refr0nt/ESPlorer/actions) [![Join the chat at https://gitter.im/4refr0nt/ESPlorer](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/4refr0nt/ESPlorer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) #### Integrated Development Environment (IDE) for ESP8266 developers ### Package Description The essential multiplatforms tools for any ESP8266 developer from luatool author’s, including a LUA for NodeMCU and MicroPython. Also, all AT commands are supported. Requires Java 8 or above. Download the latest and greatest one from [Oracle website](https://www.oracle.com/java/technologies/javase-downloads.html). ### Supported platforms - Windows(x86, x86-64) - Linux(x86, x86-64, ARM soft & hard float) - Solaris(x86, x86-64) - Mac OS X(x86, x86-64, PPC, PPC64) ### Detailed features list - Syntax highlighting LUA and Python code - Code editor color themes: default, dark, Eclipse, IDEA, Visual Studio - Undo/Redo editors features - Code Autocomplete (Ctrl+Space) - Smart send data to ESP8266 (without dumb send with fixed line delay), check correct answer from ESP8266 after every line. - Code snippets - Detailed logging - and more, more more… ### Discuss * [English esp8266.com](http://www.esp8266.com/viewtopic.php?f=22&t=882) * [Russian esp8266.ru](http://esp8266.ru/forum/threads/esplorer.34/) ### Home Page [http://esp8266.ru/ESPlorer/](http://esp8266.ru/esplorer/) ### Latest binaries download Check out [Releases](https://github.com/4refr0nt/ESPlorer/releases) ### Build from sources #### Windows ``` mvnw.cmd clean package ``` #### Linux / Mac OS ``` ./mvnw clean package ``` The build creates all-in-one executable `ESPlorer.jar` in the `target` folder. Then run the app: ``` java -jar target/ESPlorer.jar ```
0
ysc/QuestionAnsweringSystem
QuestionAnsweringSystem是一个Java实现的人机问答系统,能够自动分析问题并给出候选答案。
2014-07-28T20:27:58Z
null
## QuestionAnsweringSystem是一个Java实现的人机问答系统,能够自动分析问题并给出候选答案。IBM人工智能计算机系统"沃森"(Watson)在2011年2月美国热门的电视智力问答节目"危险边缘"(Jeopardy!)中战胜了两位人类冠军选手,QuestionAnsweringSystem就是IBM Watson的Java开源实现。 [QuestionAnsweringSystem技术实现简要分析](http://blog.sina.com.cn/s/blog_9be6dec10102vq55.html) [QuestionAnsweringSystem在100offer举办的「寻找实干和坚持的技术力量」Side Project赞助活动中荣获最具人气奖](http://i.100offer.com/projects/result) ![100offer最具人气奖.png](100offer最具人气奖.png) [捐赠致谢](https://github.com/ysc/QuestionAnsweringSystem/wiki/donation) ## 使用方法 1、安装JDK8和Maven3.3.3 将JDK的bin目录和Maven的bin目录加入PATH环境变量,确保在命令行能调用java和mvn命令: java -version java version "1.8.0_60" mvn -v Apache Maven 3.3.3 2、获取人机问答系统源码 git clone https://github.com/ysc/QuestionAnsweringSystem.git cd QuestionAnsweringSystem 建议自己注册一个GitHub账号,将项目Fork到自己的账号下,然后再从自己的账号下签出项目源码, 这样便于使用GitHub的Pull requests功能进行协作开发。 3、运行项目 unix类操作系统执行: chmod +x startup.sh & ./startup.sh windows类操作系统执行: ./startup.bat 4、使用系统 打开浏览器访问:http://localhost:8080/deep-qa-web/index.jsp ## 工作原理 1、判断问题类型(答案类型),当前使用模式匹配的方法,将来支持更多的方法,如朴素贝叶斯分类器。 2、提取问题关键词。 3、利用问题关键词搜索多种数据源,当前的数据源主要是人工标注的语料库、谷歌、百度。 4、从搜索结果中根据问题类型(答案类型)提取候选答案。 5、结合问题以及搜索结果对候选答案进行打分。 6、返回得分最高的TopN项候选答案。 ## 目前支持5种问题类型(答案类型) 1、人名 如: APDPlat的作者是谁? APDPlat的发起人是谁? 谁死后布了七十二疑冢? 习近平最爱的女人是谁? 2、地名 如: “海的女儿”是哪个城市的城徽? 世界上流经国家最多的河流是哪一条? 世界上最长的河流是什么? 汉城是哪个国家的首都? 3、机构团体名 如: BMW是哪个汽车公司制造的? 长城信用卡是哪家银行发行的? 美国历史上第一所高等学府是哪个学校? 前身是红色中华通讯社的是什么? 4、数字 如: 全球表面积有多少平方公里? 撒哈拉有多少平方公里? 北京大学占地多少平方米? 撒哈拉有多少平方公里? 5、时间 如: 哪一年第一次提出“大跃进”的口号? 大庆油田是哪一年发现的? 澳门是在哪一年回归祖国怀抱的? 邓小平在什么时候进行南巡讲话? ## 增加新的问题类型(答案类型) 1、在枚举类 org.apdplat.qa.model.QuestionType 中 增加新的问题类型,并在词性和问题类型之间做映射。 2、在资源目录 src/main/resources/questionTypePatterns 中增加新的模式匹配规则来支持新的问题类型的判定 目录中的 3 个文件代表不同抽象层级的模式,只需要在其中一个文件中增加新的模式即可。 3、在类 org.apdplat.qa.questiontypeanalysis.QuestionTypeTransformer 中 将模式匹配规则映射为枚举类 org.apdplat.qa.model.QuestionType 的实例。 ## API接口 调用地址: http://127.0.0.1/deep-qa-web/api/ask?n=1&q=APDPlat的作者是谁? 参数: n表示需要返回的答案的个数 q表示问题 编码: 服务端和客户端均使用UTF-8编码 服务端需要修改tomcat配置文件conf/server.xml,在相应的Connector中加入配置URIEncoding="UTF-8" 返回json: [ { "answer": "杨尚川", "score": 1 } ] ## 使用说明 1、初始化MySQL数据库(MySQL作为数据缓存区使用,此步骤可选): 在MySQL命令行中执行QuestionAnsweringSystem/deep-qa/src/main/resources/mysql/questionanswer.sql文件中的脚本 MySQL编码:UTF-8, 主机:127.0.0.1 端口:3306 数据库:questionanswer 用户名:root 密码:root 2、构建war文件并部署到tomcat: cd QuestionAnsweringSystem mvn install cp deep-qa-web/target/deep-qa-web-1.2.war apache-tomcat-8.0.27/webapps/ 启动tomcat 3、打开浏览器访问: http://localhost:8080/deep-qa-web-1.2/index.jsp [可部署war包下载](http://pan.baidu.com/s/1hq9pekc) ## 在你的应用中集成人机问答系统QuestionAnsweringSystem QuestionAnsweringSystem提供了两种集成方式,以库的方式嵌入到应用中,以平台的方式独立部署。 下面说说这两种方式如何做。 1、以库的方式嵌入到应用中。 这种方式只支持Java平台,可通过Maven依赖将库加入构建路径,如下所示: <dependency> <groupId>org.apdplat</groupId> <artifactId>deep-qa</artifactId> <version>1.2</version> </dependency> 在应用如何使用呢?示例代码如下: String questionStr = "APDPlat的作者是谁?"; Question question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr); if (question != null) { List<CandidateAnswer> candidateAnswers = question.getAllCandidateAnswer(); int i=1; for(CandidateAnswer candidateAnswer : candidateAnswers){ System.out.println((i++)+"、"+candidateAnswer.getAnswer()+":"+candidateAnswer.getScore()); } } 运行程序后会在当前目录下生成目录deep-qa,目录里面又有两个目录dic和questionTypePatterns。 dic是中文分词组件依赖的词库,questionTypePatterns是问题类别分析依赖的模式定义,可根据自己的需要修改。 2、以平台的方式独立部署。 首先在自己的服务器上如192.168.0.1部署好了,然后就可以通过Json Over HTTP的方式提供服务,使用方法如下所示: 调用地址: http://192.168.0.1/deep-qa-web/api/ask?n=1&q=APDPlat的作者是谁? 参数: n表示需要返回的答案的个数 q表示问题 编码: UTF-8编码 返回json: [ { "answer": "杨尚川", "score": 1 } ] ## 深入了解 QuestionAnsweringSystem由2个子项目构成,deep-qa和deep-qa-web。 deep-qa是核心部分,deep-qa-web提供web界面来和用户交互,同时也提供了Json Over HTTP的访问接口,便于异构系统的集成。 deep-qa是一个jar包,可通过maven引用: <dependency> <groupId>org.apdplat</groupId> <artifactId>deep-qa</artifactId> <version>1.2</version> </dependency> 示例代码如下: String questionStr = "APDPlat的作者是谁?"; Question question = SharedQuestionAnsweringSystem.getInstance().answerQuestion(questionStr); if (question != null) { List<CandidateAnswer> candidateAnswers = question.getAllCandidateAnswer(); int i=1; for(CandidateAnswer candidateAnswer : candidateAnswers){ System.out.println((i++)+"、"+candidateAnswer.getAnswer()+":"+candidateAnswer.getScore()); } } 运行程序后会在当前目录下生成目录deep-qa,目录里面又有两个目录dic和questionTypePatterns。 dic是中文分词组件依赖的词库,questionTypePatterns是问题类别分析依赖的模式定义,可根据自己的需要修改。 ## Watson介绍 Watson is a computer system like no other ever built. It analyzes natural language questions and content well enough and fast enough to compete and win against champion players at Jeopardy! [IBM Watson: How it Works](https://www.youtube.com/watch?v=_Xcmh1LQB9I) [Building Watson - A Brief Overview of the DeepQA Project](https://www.youtube.com/watch?v=3G2H3DZ8rNc) [This is Watson:A detailed explanation of how Watson works](http://ieeexplore.ieee.org/xpl/tocresult.jsp?isnumber=6177717) [The DeepQA Research Team](http://researcher.watson.ibm.com/researcher/view_group.php?id=2099) ## 相关文章 [测试人机问答系统智能性的3760个问题](http://my.oschina.net/apdplat/blog/401622) [人机问答系统的前世今生](http://my.oschina.net/apdplat/blog/420370) [人机问答系统的类别](http://my.oschina.net/apdplat/blog/420720) [What is Question Answering?](https://class.coursera.org/nlp/lecture/155) ## 其他人机问答系统介绍 1、OpenEphyra(Java开源) Ephyra is a modular and extensible framework for open domain question answering (QA). The system retrieves accurate answers to natural language questions from the Web and other sources. [OpenEphyra主页](http://www.ephyra.info/) 2、Watsonsim(Java开源) Open-domain question answering system from UNCC. Watsonsim works using a pipeline of operations on questions, candidate answers, and their supporting passages. In many ways it is similar to IBM's Watson, and Petr's YodaQA. It's not all that similar to more logic based systems like OpenCog or Wolfram Alpha. [Watsonsim主页](https://github.com/SeanTater/uncc2014watsonsim/) 3、YodaQA(Java开源) YodaQA is an open source Question Answering system. using on-the-fly Information Extraction from various data sources (mainly enwiki). YodaQA stands for "Yet anOther Deep Answering pipeline" and the system is inspired by the DeepQA (IBM Watson) papers. It is built on top of the Apache UIMA. [YodaQA主页](https://github.com/brmson/yodaqa/) 4、OpenQA(Java开源) OpenQA is an open source question answering framework that unifies approaches from several domain experts. The aim of OpenQA is to provide a common platform that can be used to promote advances by easy integration and measurement of different approaches. [OpenQA主页](http://openqa.aksw.org/) 5、START(商业) START, the world's first Web-based question answering system, has been on-line and continuously operating since December, 1993. It has been developed by Boris Katz and his associates of the InfoLab Group at the MIT Computer Science and Artificial Intelligence Laboratory. Unlike information retrieval systems (e.g., search engines), START aims to supply users with "just the right information" instead of merely providing a list of hits. Currently, the system can answer millions of English questions about places (e.g., cities, countries, lakes, coordinates, weather, maps, demographics, political and economic systems), movies (e.g., titles, actors, directors), people (e.g., birth dates, biographies), dictionary definitions, and much, much more. [START主页](http://start.csail.mit.edu/index.php) 6、IBM Watson(商业) Watson is built to mirror the same learning process that we have. Watson has been learning the language of professions and is trained by experts to work across many different industries. [IBM Watson主页](http://www.ibm.com/smarterplanet/us/en/ibmwatson/what-is-watson.html) 7、Siri(商业) Siri /ˈsɪri/ is a part of Apple Inc.'s iOS which works as an intelligent personal assistant and knowledge navigator. The feature uses a natural language user interface to answer questions, make recommendations, and perform actions by delegating requests to a set of Web services. [Siri主页](http://www.apple.com/ios/siri/) 8、Wolfram|Alpha(商业) Wolfram|Alpha introduces a fundamentally new way to get knowledge and answers not by searching the web, but by doing dynamic computations based on a vast collection of built-in data, algorithms, and methods. [Wolfram|Alpha主页](http://www.wolframalpha.com/) 9、Evi(商业) Evi was founded in August 2005, originally under the name of True Knowledge, with the mission of powering a new kind of search experience where users can access the world's knowledge simply by asking for the information they need in a way that is completely natural. [Evi主页](https://www.evi.com/) 10、微软小冰(商业) 微软小冰是智能聊天机器人,基于微软搜索引擎和大数据积累,所有数据全部来自于公开的互联网网页信息。 [微软小冰主页](http://www.msxiaoice.com/) 11、Magi Semantic Search(商业) Magi is a search engine that gives you answers instead of references. It's designed to be General, Feasible and Useful. [Magi Semantic Search主页](http://www.peak-labs.com/) [https://travis-ci.org/ysc/QuestionAnsweringSystem](https://travis-ci.org/ysc/QuestionAnsweringSystem)
0
brianway/java-learning
旨在打造在线最佳的 Java 学习笔记,含博客讲解和源码实例,包括 Java SE 和 Java Web
2016-02-09T05:20:58Z
null
# 我的 Java 学习笔记 旨在打造在线最佳的 Java 学习笔记,笔记内容主要是对一些基础特性和编程细节进行总结整理,适合了解 Java 基础语法,想进一步深入学习的人 含**博客讲解**和**源码实例**,采用 maven 构建,分模块学习,涉及反射,代理,多线程,IO,集合类等核心知识。 **如果觉得不错,请先在这个仓库上点个 star 吧**,这也是对我的肯定和鼓励,谢谢了。 不定时进行调整和补充,需要关注更新的请 watch、star、fork ----- # 仓库目录 **点击相应的模块能看到每个目录的说明文档** - [blogs](/blogs):博客文档 - [java-base](/java-base):Java 基础巩固模块的 Java 源码 - [java-multithread](/java-multithread):多线程模块的 Java 源码 - [java-container](/java-container):容器类模块的 Java 源码 - [java-io](/java-io):IO 模块的 Java 源码 - [java-jvm](/java-jvm): JVM 模块的 Java 源码 - [java8](/java8): Java 8 模块的源码 # 博客文档 如果你只是单纯要阅读的话,建议移步 CSDN 或者 oschina 上观看,访问速度快很多: >* CSDN:[我的java&javaweb学习笔记(汇总)](http://blog.csdn.net/h3243212/article/details/50659471) >* oschina:[我的java&javaweb学习笔记(汇总)](http://my.oschina.net/brianway/blog/614355) **博客目录** - [Java SE](/blogs/javase) - [java基础巩固笔记(1)-反射.md](/blogs/javase/java基础巩固笔记(1)-反射.md) - [java基础巩固笔记(2)-泛型.md](/blogs/javase/java基础巩固笔记(2)-泛型.md) - [java基础巩固笔记(3)-类加载器.md](/blogs/javase/java基础巩固笔记(3)-类加载器.md) - [java基础巩固笔记(4)-代理.md](/blogs/javase/java基础巩固笔记(4)-代理.md) - [java基础巩固笔记(4)-实现AOP功能的封装与配置的小框架.md](/blogs/javase/java基础巩固笔记(4)-实现AOP功能的封装与配置的小框架.md) - [java基础巩固笔记(5)-多线程之传统多线程.md](/blogs/javase/java基础巩固笔记(5)-多线程之传统多线程.md) - [java基础巩固笔记(5)-多线程之共享数据.md](/blogs/javase/java基础巩固笔记(5)-多线程之共享数据.md) - [java基础巩固笔记(5)-多线程之线程并发库.md](/blogs/javase/java基础巩固笔记(5)-多线程之线程并发库.md) - [java基础巩固笔记(6)-注解.md](/blogs/javase/java基础巩固笔记(6)-注解.md) - [Java Web](/blogs/javaweb) - [javaweb入门笔记(1)-Tomcat.md](/blogs/javaweb/javaweb入门笔记(1)-Tomcat.md) - [javaweb入门笔记(2)-http入门.md](/blogs/javaweb/javaweb入门笔记(2)-http入门.md) - [javaweb入门笔记(3)-Servlet.md](/blogs/javaweb/javaweb入门笔记(3)-Servlet.md) - [javaweb入门笔记(4)-request和response.md](/blogs/javaweb/javaweb入门笔记(4)-request和response.md) - [javaweb入门笔记(5)-cookie和session.md](/blogs/javaweb/javaweb入门笔记(5)-cookie和session.md) - [javaweb入门笔记(6)-JSP技术.md](/blogs/javaweb/javaweb入门笔记(6)-JSP技术.md) ----- ## 赞助 如果您觉得该项目对您有帮助,请扫描下方二维码对我进行鼓励,以便我更好的维护和更新,谢谢支持! ![支付宝](https://brianway.github.io/img/alipay_small.png) ![微信](https://brianway.github.io/img/wechatpay_small.png) # TODO 计划将这个仓库进行重构,逐步扩充并实现下面的功能。 * [x] 整理成 maven 的结构,使用聚合和继承特性(2016.4.12 完成) * [ ] 原有的 Java SE 部分代码重构为 java-base 模块,并逐步上传代码 * [x] 多线程部分使用 java-multithread 模块(2016.4.17 完成雏形) * [ ] 容器类部分使用模块 java-container * [ ] IO 部分使用模块 java-io * [x] Java 虚拟机相关部分使用模块 java-jvm(2017.3.20 完成雏形) * [x] Java 8 新特性使用模块 java8(2017.3.29 完成) ----- # 联系作者 - [Brian's Personal Website](http://brianway.github.io/) - [CSDN](http://blog.csdn.net/h3243212/) - [oschina](http://my.oschina.net/brianway) Email: weichuyang@163.com ----- # Lisence Lisenced under [Apache 2.0 lisence](http://opensource.org/licenses/Apache-2.0)
0
android-cjj/JJSearchViewAnim
A cool search view animation library
2016-04-03T15:08:38Z
null
JJSearchViewAnim ============================ [中文版文档及相关文章](https://github.com/android-cjj/JJSearchViewAnim/blob/master/README-CN.md) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-JJSearchViewAnim-green.svg?style=true)](https://android-arsenal.com/details/1/3390) ![](http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2kefqi8ekj205s05s749.jpg) ####A cool search view animation library ,I hope you like it. ###look <table> <thead> <tr> <th>Design</th> <th>Demo</th> <th>Designer</th> <th>Class</th> </tr> </thead> <tbody> <tr> <td><img src="http://ww3.sinaimg.cn/mw690/7ef01fcagw1f2gzz0570bg20an05hmxv.gif" width="240"></td> <td><img src="http://ww2.sinaimg.cn/mw690/7ef01fcagw1f2kfx45rqyg20b505lq3b.gif" width="240"></td> <td>Nick</td> <td>JJDotGoPathController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzyysygrg20an05h3zb.gif" width="240"></td> <td><img src="http://ww3.sinaimg.cn/mw690/7ef01fcagw1f2kfx4n06bg20b505l0te.gif" width="240"></td> <td>Oleg Frolov</td> <td>JJAroundCircleBornTailController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzyx8egbg20an05h3zl.gif" width="240"></td> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2kfx516l3g20b505laa3.gif" width="240"></td> <td>sandeep virk</td> <td>JJBarWithErrorIconController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzz1dsvsg20an06ltbr.gif" width="240"></td> <td><img src="http://ww3.sinaimg.cn/mw690/7ef01fcagw1f2kfx5ckjsg20b505lt97.gif" width="240"></td> <td>Jurre Houtkamp</td> <td>JJScaleCircleAndTailController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzyzdp5vg20an05hgng.gif" width="240"></td> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2kg8o2htzg20b505ljrj.gif" width="240"></td> <td> Rahul Bhosale</td> <td>JJChangeArrowController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzyzljmyg20an05h0t0.gif" width="240"></td> <td><img src="http://ww3.sinaimg.cn/mw690/7ef01fcagw1f2kfx644s8g20b505lglq.gif" width="240"></td> <td>Nicolás J. Engler</td> <td>JJCircleToLineAlphaController</td> </tr> <tr> <td><img src="http://ww1.sinaimg.cn/mw690/7ef01fcagw1f2gzywvmklg20an05hk2w.gif" width="240"></td> <td><img src="http://ww2.sinaimg.cn/mw690/7ef01fcagw1f2kfx6egogg20b505lq3r.gif" width="240"></td> <td> Boris Kirov </td> <td>JJCircleToBarController</td> </tr> <tr> <td><img src="http://ww4.sinaimg.cn/mw690/7ef01fcagw1f2gzyxopnfg20an05haaa.gif" width="240"></td> <td><img src="http://ww4.sinaimg.cn/mw690/7ef01fcagw1f2kfx6owemg20b505laav.gif" width="240"></td> <td>Anish Chandran</td> <td>JJCircleToSimpleLineController</td> </tr> <tr> <td><img src="http://ww2.sinaimg.cn/mw690/7ef01fcagw1f2gzz0xbkfg20an05hq47.gif" width="240"></td> <td><img src="https://camo.githubusercontent.com/8220bd55683ee57442aef6c833e1a971d07b6429/687474703a2f2f7777772e61706b6275732e636f6d2f646174612f6174746163686d656e742f666f72756d2f3230313530382f30372f313632343332673033696c7a7a69373335696d686d382e676966" width="240"></td> <td>Antonio Di Nardo</td> <td> MaterialSearchView</td> </tr> </tbody> </table> * The last effect you can find here:[MaterialSearchView](https://github.com/android-cjj/MaterialSearchView) ###Usage #### (1) In xml ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.cjj.jjsearchviewanim.MainActivity"> <com.cjj.sva.JJSearchView android:id="@+id/jjsv" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> ``` #### (2) In java ```java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); JJSearchView mJJSearchView = (JJSearchView) findViewById(R.id.jjsv); mJJSearchView.setController(new JJChangeArrowController()); } ``` #### (3) Setting ```java mJJSearchView.startAnim(); mJJSearchView.resetAnim(); ``` ####Thanks: [http://www.materialup.com/posts/search-0c73a055-dcc9-486f-8540-f9517204edf8](http://www.materialup.com/posts/search-0c73a055-dcc9-486f-8540-f9517204edf8) [http://www.materialup.com/posts/search-bar-concept](http://www.materialup.com/posts/search-bar-concept) [http://www.materialup.com/posts/search-inspiration](http://www.materialup.com/posts/search-inspiration) [http://www.materialup.com/posts/search](http://www.materialup.com/posts/search) [http://www.materialup.com/posts/search-input-focus-animation](http://www.materialup.com/posts/search-input-focus-animation) [http://www.materialup.com/posts/material-search](http://www.materialup.com/posts/material-search) [http://www.materialup.com/search?q=search](http://www.materialup.com/search?q=search) [http://www.materialup.com/posts/css3-jquery-material-design-close-animation](http://www.materialup.com/posts/css3-jquery-material-design-close-animation) ####About me A low-level android software development engineer, like watching cartoons, like playing football, love life ! If you want to make friends with me, You can email tell me.Email address: cjjcjj2014@gmail.com. License ======= The MIT License (MIT) Copyright (c) 2016 android-cjj 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.
0
Teevity/ice
AWS Usage Tool
2013-06-14T20:56:13Z
null
# Ice [![Build Status](https://travis-ci.org/Teevity/ice.svg?branch=master)](https://travis-ci.org/Teevity/ice) ## Intro Ice provides a birds-eye view of our large and complex cloud landscape from a usage and cost perspective. Cloud resources are dynamically provisioned by dozens of service teams within the organization and any static snapshot of resource allocation has limited value. The ability to trend usage patterns on a global scale, yet decompose them down to a region, availability zone, or service team provides incredible flexibility. Ice allows us to quantify our AWS footprint and to make educated decisions regarding reservation purchases and reallocation of resources. Ice is a Grails project. It consists of three parts: processor, reader and UI. Processor processes the Amazon detailed billing file into data readable by reader. Reader reads data generated by processor and renders them to UI. UI queries reader and renders interactive graphs and tables in the browser. ## What it does Ice communicates with AWS Programmatic Billing Access and maintains knowledge of the following key AWS entity categories: - Accounts - Regions - Services (e.g. EC2, S3, EBS) - Usage types (e.g. EC2 - m1.xlarge) - Cost and Usage Categories (On-Demand, Reserved, etc.) The UI allows you to filter directly on the above categories to custom tailor your view. In addition, Ice supports the definition of Application Groups. These groups are explicitly defined collections of resources in your organization. Such groups allow usage and cost information to be aggregated by individual service teams within your organization, each consisting of multiple services and resources. Ice also provides the ability to email weekly cost reports for each Application Group showing current usage and past trends. When representing the cost profile for individual resources, Ice will factor the depreciation schedule into your cost contour, if so desired. The ability to amortize one-time purchases, such as reservations, over time allows teams to better evaluate their month-to-month cost footprint. ## Screenshots 1. Summary page grouped by accounts ![Summary page grouped by accounts](https://github.com/Netflix/ice/blob/master/screenshots/ss_summary.png?raw=true) 2. Detail page with throughput metrics and grouped by products ![Detail page with throughput metrics and grouped by products](https://github.com/Netflix/ice/blob/master/screenshots/ss_detail.png?raw=true) 3. Reservation page grouped by on-demand, un-used, reserved, upfront costs ![Reservation page](https://github.com/Netflix/ice/blob/master/screenshots/ss_reservation_byreservation.png?raw=true) 4. Reservation page with on-demand cost and grouped by instance types ![Reservation page with on-demand cost and grouped by instance types](https://github.com/Netflix/ice/blob/master/screenshots/ss_reservation_bytype.png?raw=true) 5. Breakdown page of Application Groups ![Breakdown page of Application Groups](https://github.com/Netflix/ice/blob/master/screenshots/ss_breakdown_appgroup.png?raw=true) ## Prerequisite: 1. First sign up for Amazon's programmatic billing access [here](http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/detailed-billing-reports.html) to receive detailed billing(hourly) reports. Verify you receive monthly billing file in the following format: `<accountid>-aws-billing-detailed-line-items-<year>-<month>.csv.zip`. 2. Install Grails 2.4.4 and set GRAILS_HOME and JAVA_HOME 3. Ice uses [highstock](http://www.highcharts.com/) to generate interactive graphs. Please make sure you acquire the proper license before using it. ## Basic setup: Using basic setup, you don't need any extra code change and you will use the provided bootstrap.groovy. You will need to construct your own ice.properties file and have it in your classpath (I put it at src/java). You can use sample.properties (located at src/java) file as the template. 1. Processor configuration 1.1 Enable processor in ice.properties: ice.processor=true 1.2 In ice.properties, set up the local directory where the processor can copy the billing file to and store the output files. The directory must pre-exist. For example: ice.processor.localDir=/mnt/ice_processor 1.3 In ice.properties, set up the working s3 bucket and working s3 bucket file prefix to upload the processed output files which will be read by reader. Ice must have read and write access to the s3 bucket. For example: ice.work_s3bucketname=work_s3bucketname ice.work_s3bucketprefix=work_s3bucketprefix/ 1.4 If running locally, set the following system properties at runtime. ice.s3AccessToken is optional. ice.s3AccessKeyId=<accessKeyId> ice.s3SecretKey=<secretKey> ice.s3AccessToken=<accessToken> If running on a ec2 instance and you want to use the credentials in the instance metadata, you can leave the above properties unset. 1.5 In ice.properties, specify the start time in millis for the processor to start processing billing files. For example, if you want to start processing billing files from April 1, 2013. If this property is not set, Ice will set startmillis to be the beginning of current month. ice.startmillis=1364774400000 1.6 Set up s3 billing bucket in ice.properties. If you have multiple payer accounts, you will need to specify multiple values for each property. # s3 bucket name where the billing files are. multiple bucket names are delimited by ",". Ice must have read access to billing s3 bucket. ice.billing_s3bucketname=billing_s3bucketname1,billing_s3bucketname2 # prefix of the billing files. multiple prefixes are delimited by "," ice.billing_s3bucketprefix=, # location for the billing bucket. It should be specified for buckets using v4 validation ice.billing_s3bucketregion=eu-west-1,eu-central-1 # specify your payer account id here if across-accounts IAM role access is used. multiple account ids are delimited by ",". "ice.billing_payerAccountId=,222222222222" means assumed role access is only used for the second bucket. ice.billing_payerAccountId=,123456789012 # specify the assumed role name here if you use IAM role access to read from billing s3 bucket. multiple role names are delimited by ",". "ice.billing_accessRoleName=,ice" means assumed role access is only used for the second bucket. ice.billing_accessRoleName=,ice # specify external id here if it is used. multiple external ids are delimited by ",". if you don't use external id, you can leave this property unset. ice.billing_accessExternalId= Tip: If you have multiple payer accounts, or Ice is running from a different account of the s3 billing bucket, for example Ice is running in account "test", while the billing files are written to bucket in account "prod", account "test" does not have read access to those billing files because Amazon created them. In this case, the recommended way is to use cross-accounts IAM roles. E.g. you can create an assumed role "ice". In "prod" account, grant assumed role "ice" with read access to billing bucket, then specify ice.billing_accessRoleName=ice. You can also create a secondary s3 bucket in account "prod" and grant read access to account "test", and then create a billing file poller running in account "prod" to copy billing files to the secondary bucket. 1.7 Specify account id and account name mappings in ice.properties. This is for readability purposes. For example: ice.account.account1=123456789011 ice.account.account2=123456789012 ice.account.account3=123456789013 1.8 If you have reserved ec2 instances, please also make sure Ice has the permission to make ec2 call describeReservedInstancesOfferings, which is used to get ri prices. 2. Reader configuration 2.1 Enable reader in ice.properties: ice.reader=true 2.2 In ice.properties, set up the local directory where the reader will copy files to. The local directory must pre-exist. For example: ice.reader.localDir=/mnt/ice_reader Make sure the local directory is different if you run processor and reader on the same instance. 2.3 Same as 1.3 2.4 Same as 1.4 2.5 Same as 1.5 2.6 Specify your organization name in ice.properties. This will show up in the UI header. ice.companyName=Your Company Name 2.7 You can choose to show cost in currency other than "$". To enable other currency, specify the following properties in ice.properties: # Specify your currency sign here. The default value is $. For other currency symbols, you can use UTF-8 code, e.g. for ¥, you can use ice.currencySign=\u00A5 ice.currencySign=£ # Specify your currency conversion rate here. The default value is 1. If 1 pound = 1.5 dollar, then the rate is 0.6666667. ice.currencyRate=0.6666667 2.8 By default, Ice pulls in [Highstock](https://www.highcharts.com/) from its CDN. ice.highstockUrl=https://example.com/js/highstock.js 3. Running Ice After the processor and reader setup, you can choose to run the processor and reader on the same or different instances. Running on different instances is recommended. For the first time, you should FIRST RUN PROCESSOR. Make sure you see non-empty output files in your working s3 bucket. Then run reader and browse to http://localhost:8080/ice/dashboard/summary. Here are the steps of getting ice running locally: 3.1 Pull the project 3.2 Run `grails wrapper` from the project root directory. This step will pull all necessary jar from maven central. 3.3 Construct ice.properties for processor and make sure ice.properties is added to directory src/java 3.4 Run Ice processor. From project root directory, run `./grailsw run-app`. Note you may need to add system properties like `./grailsw -Dice.s3AccessKeyId=<s3AccessKeyId> -Dice.s3SecretKey=<s3SecretKey> run-app`. To verify Ice processor runs successfully, make sure you see un-empty output files in your working S3 bucket, e.g. tagdb_all, cost_weekly_all, cost_daily_all_2013, etc. 3.5 Repeat steps 3.3 and 3.4 to run Ice reader. Tip: Sometimes you want to re-start from a clean slate. To do that: a) Get the latest code b) Delete all files from your working s3 bucket under the working prefix c) Delete all files from your local ice directory (for processor and reader) d) Start Ice in processor mode. Make sure it runs correctly. e) Then start Ice in reader mode. ## Ice Cookbook: 1. A community cookbook is available for deploying Ice via Chef here https://github.com/mdsol/ice_cookbook. ## Ice Docker Image: 1. A community image is available for deploying Ice via Docker here https://github.com/jonbrouse/docker-ice ## Advanced options: Options with * require writing your own code. 1. Basic reservation service If you have reserved instances in your accounts, you may want to make use of the reservation view in the UI, where you can browse/analyze your on-demand, unused reserved instance usage & cost of different instance types in different regions, zones and accounts. in Bootstrap.groovy, BasicReservationService is used. You can specify reservation period and reservation utilization type in ice.properties: # reservation period, possible values are oneyear, threeyear ice.reservationPeriod=threeyear # reservation utilization, possible values are LIGHT, HEAVY ice.reservationUtilization=HEAVY 2. Reservation capacity poller To use BasicReservationService, you should also run reservation capacity poller, which will call ec2 API (describeReservedInstances) to poll reservation capacities for each reservation owner account defined in ice.properties. The reservation capacities history is stored in a file in s3 bucket. To run reservation capacity poller, following steps below: 2.1 Set ice.reservationCapacityPoller=true in ice.properties 2.2 Make sure you set up reservation owner accounts in ice.properties. For example: ice.owneraccount.account1= ice.owneraccount.account2=account3,account4 ice.owneraccount.account5=account6 2.3 If you need to poll reservation capacity of different accounts, set up IAM roles. Then specify the assumed roles and external ids in ice.properties. For example, if assumed role "ice" is used: ice.owneraccount.account1.role=ice ice.owneraccount.account2.role=ice ice.owneraccount.account5.role=ice If you use external id too, specify it like following: ice.owneraccount.account1.externalId= 3. On-demand instance cost alert You can set set an on-demand instance cost threshold so that alert emails will be sent through Amazon SES if the threshold is reached within last 24 hours. The alert emails will be sent no more than once a day. The following properties are needed in ice.properties: # url prefix, e.g. http://ice.netflix.com/. This is used to create the link in alert email ice.urlPrefix= # from email address, this email must be registered in ses. ice.fromEmail= # ec2 ondemand hourly cost threshold to send alert email. The alert email will be sent at most once per day. ice.ondemandCostAlertThreshold=250 # ec2 ondemand hourly cost alert emails, separated by "," ice.ondemandCostAlertEmails= 4. Sharing reserved instances among accounts (*) All linked accounts under the same payer account can share each other's reservations (see http://docs.aws.amazon.com/awsaccountbilling/latest/about/AboutConsolidatedBilling.html). If reserved instances are shared among accounts, please specify them in ice.properties. For example: # set reservation owner accounts. In the example below, account1, account2, account3 and account4 are linked under the same payer account. account5, account6 are linked under the same payer account. # if reservation capacity poller is enabled, the poller will try to poll reservation capacity through ec2 API (describeReservedInstances) for each reservation owner account. ice.owneraccount.account1_name=account2_name,account3_name,account4_name ice.owneraccount.account2_name=account1_name,account3_name,account4_name ice.owneraccount.account5_name=account6_name If different accounts have different AZ mappings, you will also need to subclass BasicAccountService and override method getAccountMappedZone to provide correct AZ mapping. 5. Customized reservation service (*) Reserved instance prices in BasicReservationService are copied from Amazon's ec2 price page as of Jun 1, 2013. Your accounts may have different reservation prices (e.g. Amazon may change prices in the future). In this case, you need to write a subclass of BasicReservationService to provide the correct pricing. 6. Resource service (*) To use the breakdown feature and application group feature, first make sure you signed up the beta version of detailed billing file with resources and tag. Verify you receive monthly billing file in the this format: `<accountid>-aws-billing-detailed-line-items-with-resources-and-tags-<year>-<month>.csv.zip`. Then you will need to subclass abstract class ResourceService and have your own bootstrap.groovy create ProcessorConfig and ReaderConfig. See SampleMapDbResourceService for a sample of subclass. If your custom tags have limited number of value combinations (e.g. < 100), you can choose to set the following parameter in ice.properties, and Ice will generate resource group values for each line item in the billing file. Please be VERY careful about using this feature. Resource group values are generated by concatenating values of of all custom tags. If it results in a long list of resource group values, Ice performance will be greatly affected. Please make sure the custom tags exist in the header of the billing file. # specify your custom tags here. Multiple tags are delimited by ",". If specified, BasicResourceService will be used to generate resource groups for you. # PLEASE MAKE SURE you have limited number (e.g. < 100) of unique value combinations from your custom tags, otherwise Ice performance will be greatly affected. ice.customTags=tag1,tag2 You will need to ensure that any tag you wish to use in ICE is ticked in the "Manage Cost allocation report" page here: https://portal.aws.amazon.com/gp/aws/developer/account?ie=UTF8&action=cost-allocation-report Any tag that you have created yourself (as opposed to being automatically generated by AWS) will require you to use the ice.customTags= parameter in the following way. See this example: ice.customTags=user:CostCenter,User:Environment 7. Weekly cost email per application group (*) If you have resource service enabled, you can use BasicWeeklyCostEmailService to send weekly cost emails. You can use the default BasicS3ApplicationGroupService, or you can have your own ApplicationGroupService implementation. 8. Throughput metric service (*) You may also want to show your organization's throughput metric alongside usage and cost. You can choose to implement interface ThroughputMetricService, or you can simply use the existing BasicThroughputMetricService. Using BasicThroughputMetricService requires the throughput metric data to be stores monthly in files with names like <filePrefix>_2013_04, <filePrefix>_2013_05. Data in files should be delimited by new lines. <filePrefix> is specified when you create BasicThroughputMetricService instance. 9. Blended Costs By default, unblended costs are shown. You can show Blended costs with the following configuration: ice.use_blended=true 10. Extra Grails configuration file If you need to setup custom Grails settings, you can specify an additional configuration file to be loaded by Grails by setting the ``ice.config.location`` system property to the location of that file. See http://docs.grails.org/2.4.4/guide/single.html#configExternalized for more information. ## Example IAM Permissions Grant the following permissions to either an instance role, or the user running the reports: ``` { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1421551747000", "Effect": "Allow", "Action": [ "ec2:DescribeReservedInstances", "ec2:DescribeReservedInstancesOfferings" ], "Resource": [ "*" ] }, { "Sid": "Stmt1418665415000", "Effect": "Allow", "Action": [ "s3:DeleteObject", "s3:GetBucketLocation", "s3:GetObject", "s3:ListAllMyBuckets", "s3:ListBucket", "s3:PutObject" ], "Resource": [ "arn:aws:s3:::work-bucket-name/*" ] }, { "Sid": "Stmt1418665415001", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::work-bucket-name" ] }, { "Sid": "Stmt1418665415000a", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:GetObject", "s3:ListAllMyBuckets", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::billing-reports-bucket/*" ] }, { "Sid": "Stmt1418665415001a", "Effect": "Allow", "Action": [ "s3:GetBucketLocation", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::billing-reports-bucket" ] } ] } ``` ## Support Please use the [Ice Google Group](https://groups.google.com/d/forum/iceusers) for general questions and discussion. ## Download Snapshot Builds Download snapshot builds here: [https://netflixoss.ci.cloudbees.com/job/ice-master/](https://netflixoss.ci.cloudbees.com/job/ice-master/) ## License Copyright 2014 Netflix, Inc. 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.
0
bmuschko/gradle-docker-plugin
Gradle plugin for managing Docker images and containers.
2014-05-08T21:35:02Z
null
null
0
ren93/RecyclerBanner
用RecyclerView实现无限轮播图,有普通版和3d版
2017-11-17T09:26:08Z
null
# RecyclerBanner ## 介绍 RecyclerBanner是一个利用RecycleView实现轮播图的自定义控件。 这里有[相关博客介绍!](https://juejin.im/post/5a13a28c51882512a860ee6a)。 ## 属性 | **属性名称**  | **方法** | **意义** | **类型** | **默认值** | | --- | ---| --- | --- | --- | | app:showIndicator |setShowIndicator(boolean showIndicator)| 是否显示指示器 | boolean | true | | app:interval |setAutoPlayDuration(int autoPlayDuration)| 轮播时间间隔 | int | 4000 | | app:isAutoPlaying |setAutoPlaying(boolean isAutoPlaying)| 是否开启自动轮播 | boolean | true | | app:orientation | setOrientation(int orientation)|轮播图方向 | enum | horizontal | | app:itemSpace |setItemSpace(int itemSpace) |图片间距 | int | 20 | | app:centerScale | setCenterScale(float centerScale)|当前图片缩放比列 | float | 1.2 | | app:moveSpeed | setMoveSpeed(float moveSpeed)|滚动速度,越大越快 | float | 1.0 | 效果如下图: ![](./pictures/banner.gif) ## 使用方法 设置一个带数据的`RecyclerView.Adapter`即可。 ``` <com.example.library.banner.BannerLayout android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="200dp" app:autoPlaying="true" app:centerScale="1.3" app:itemSpace="20" app:moveSpeed="1.8"/> ``` ``` BannerLayout recyclerBanner = findViewById(R.id.recycler); bannerVertical = findViewById(R.id.recycler_ver); List<String> list = new ArrayList<>(); list.add("http://img0.imgtn.bdimg.com/it/u=1352823040,1166166164&fm=27&gp=0.jpg"); list.add("http://img3.imgtn.bdimg.com/it/u=2293177440,3125900197&fm=27&gp=0.jpg"); list.add("http://img3.imgtn.bdimg.com/it/u=3967183915,4078698000&fm=27&gp=0.jpg"); list.add("http://img0.imgtn.bdimg.com/it/u=3184221534,2238244948&fm=27&gp=0.jpg"); list.add("http://img4.imgtn.bdimg.com/it/u=1794621527,1964098559&fm=27&gp=0.jpg"); list.add("http://img4.imgtn.bdimg.com/it/u=1243617734,335916716&fm=27&gp=0.jpg"); WebBannerAdapter webBannerAdapter=new WebBannerAdapter(this,list); webBannerAdapter.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() { @Override public void onItemClick(int position) { Toast.makeText(MainActivity.this, "点击了第 " + position+" 项", Toast.LENGTH_SHORT).show(); } }); recyclerBanner.setAdapter(webBannerAdapter); ``` ## License 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. ## 致谢 [ViewPagerLayoutManager](https://github.com/leochuan/ViewPagerLayoutManager) 使用了部分代码
0
learning-zone/java-basics
Java Basics ( Java-8 )
2019-03-06T05:03:23Z
null
# Java Basics > *Click &#9733; if you like the project. Your contributions are heartily ♡ welcome.* <br/> ## Related Topics * *[Multithreading](multithreading-questions.md)* * *[Collections](collections-questions.md)* * *[Java Database Connectivity (JDBC)](JDBC-questions.md)* * *[Java Programs](java-programs.md)* * *[Java String Methods](java-string-methods.md)* * *[Jakarta Server Pages (JSP)](jsp-questions.md)* * *[Servlets](servlets-questions.md)* * *[Java Multiple Choice Questions](java-multiple-choice-questions-answers.md)* * *[Java Design Pattern](https://github.com/learning-zone/java-design-patterns)* * *[Hibernate](https://github.com/learning-zone/hibernate-basics)* * *[Spring Framework Basics](https://github.com/learning-zone/spring-basics)* <br/> ## Table of Contents * [Introduction](#-1-introduction) * [Java Architecture](#-2-java-architecture) * [Java Data Types](#-3-java-data-types) * [Java Methods](#-4-java-methods) * [Java Functional programming](#-5-java-functional-programming) * [Java Lambda expressions](#-6-java-lambda-expressions) * [Java Classes](#-7-java-classes) * [Java Constructors](#-8-java-constructors) * [Java Array](#-9-java-array) * [Java Strings](#-10-java-strings) * [Java Reflection](#-11-java-reflection) * [Java Streams](#-12-java-streams) * [Java Regular Expressions](#-13-java-regular-expressions) * [Java File Handling](#-14-java-file-handling) * [Java Exceptions](#-15-java-exceptions) * [Java Inheritance](#-16-java-inheritance) * [Java Method Overriding](#-17-java-method-overriding) * [Java Polymorphism](#-18-java-polymorphism) * [Java Abstraction](#-19-java-abstraction) * [Java Interfaces](#-20-java-interfaces) * [Java Encapsulation](#-21-java-encapsulation) * [Java Generics](#-22-java-generics) * [Miscellaneous](#-23-miscellaneous) <br/> ## # 1. INTRODUCTION <br/> ## Q. What are the important features of Java 8 release? * Interface methods by default; * Lambda expressions; * Functional interfaces; * References to methods and constructors; * Repeatable annotations * Annotations on data types; * Reflection for method parameters; * Stream API for working with collections; * Parallel sorting of arrays; * New API for working with dates and times; * New JavaScript Nashorn Engine ; * Added several new classes for thread safe operation; * Added a new API for `Calendar`and `Locale`; * Added support for Unicode 6.2.0 ; * Added a standard class for working with Base64 ; * Added support for unsigned arithmetic; * Improved constructor `java.lang.String(byte[], *)` and method performance `java.lang.String.getBytes()`; * A new implementation `AccessController.doPrivileged` that allows you to set a subset of privileges without having to check all * other access levels; * Password-based algorithms have become more robust; * Added support for SSL / TLS Server Name Indication (NSI) in JSSE Server ; * Improved keystore (KeyStore); * Added SHA-224 algorithm; * Removed JDBC Bridge - ODBC; * PermGen is removed , the method for storing meta-data of classes is changed; * Ability to create profiles for the Java SE platform, which include not the entire platform, but some part of it; * Tools * Added utility `jjs` for using JavaScript Nashorn; * The command `java` can run JavaFX applications; * Added utility `jdeps` for analyzing .class files. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is Nashorn? **Nashorn** is a JavaScript engine developed in Java by Oracle. Designed to provide the ability to embed JavaScript code in Java applications. Compared to Rhino , which is supported by the Mozilla Foundation, Nashorn provides 2 to 10 times better performance, as it compiles code and transfers bytecode to the Java virtual machine directly in memory. Nashorn can compile JavaScript code and generate Java classes that are loaded with a special loader. It is also possible to call Java code directly from JavaScript. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is jjs? `jjs` - This is a command line utility that allows you to execute JavaScript programs directly in the console. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. In Java, How many ways you can take input from the console? In Java, there are three different ways for reading input from the user in the command line environment ( console ). **1. Using Buffered Reader Class:** This method is used by wrapping the System.in ( standard input stream ) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. ```java /** * Buffered Reader Class */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); } } ``` **2. Using Scanner Class:** The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however it is also can be used to read input from the user in the command line. ```java /** * Scanner Class */ import java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string " + s); int a = in.nextInt(); System.out.println("You entered integer " + a); float b = in.nextFloat(); System.out.println("You entered float " + b); } } ``` **3. Using Console Class:** It has been becoming a preferred way for reading user\'s input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used ( like System.out.printf() ). ```java /** * Console Class */ public class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println(name); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the purpose of using javap? The **javap** command displays information about the fields, constructors and methods present in a class file. The javap command ( also known as the Java Disassembler ) disassembles one or more class files. ```java /** * Java Disassembler */ class Simple { public static void main(String args[]) { System.out.println("Hello World"); } } ``` ```cmd cmd> javap Simple.class ``` Output ```java Compiled from ".java" class Simple { Simple(); public static void main(java.lang.String[]); } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Explain the expression `System.out::println`? The specified expression illustrates passing a reference to a static method of a `println()`class `System.out`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Tell us about parallel processing in Java 8? Streams can be sequential and parallel. Operations on sequential streams are performed in one processor thread, on parallel streams - using several processor threads. Parallel streams use the shared stream `ForkJoinPool`through the static `ForkJoinPool.commonPool()`method. In this case, if the environment is not multi-core, then the stream will be executed as sequential. In fact, the use of parallel streams is reduced to the fact that the data in the streams will be divided into parts, each part is processed on a separate processor core, and in the end these parts are connected, and final operations are performed on them. You can also use the `parallelStream()`interface method to create a parallel stream from the collection `Collection`. To make a regular sequential stream parallel, you must call the `Stream`method on the object `parallel()`. The method `isParallel()`allows you to find out if the stream is parallel. Using, methods `parallel()`and `sequential()`it is possible to determine which operations can be parallel, and which only sequential. You can also make a parallel stream from any sequential stream and vice versa: ```java collection .stream () .peek ( ... ) // operation is sequential .parallel () .map ( ... ) // the operation can be performed in parallel, .sequential () .reduce ( ... ) // operation is sequential again ``` As a rule, elements are transferred to the stream in the same order in which they are defined in the data source. When working with parallel streams, the system preserves the sequence of elements. An exception is a method `forEach()`that can output elements in random order. And in order to maintain the order, it is necessary to apply the method `forEachOrdered()`. * Criteria that may affect performance in parallel streams: * Data size - the more data, the more difficult it is to separate the data first, and then combine them. * The number of processor cores. Theoretically, the more cores in a computer, the faster the program will work. If the machine has one core, it makes no sense to use parallel threads. * The simpler the data structure the stream works with, the faster operations will occur. For example, data from is `ArrayList`easy to use, since the structure of this collection assumes a sequence of unrelated data. But a type collection `LinkedList`is not the best option, since in a sequential list all the elements are connected with previous / next. And such data is difficult to parallelize. * Operations with primitive types will be faster than with class objects. * It is highly recommended that you do not use parallel streams for any long operations (for example, network connections), since all parallel streams work with one `ForkJoinPool`, such long operations can stop all parallel streams in the JVM due to the lack of available threads in the pool, etc. e. parallel streams should be used only for short operations where the count goes for milliseconds, but not for those where the count can go for seconds and minutes; * Saving order in parallel streams increases execution costs, and if order is not important, it is possible to disable its saving and thereby increase productivity by using an intermediate operation `unordered()`: ```java collection.parallelStream () .sorted () .unordered () .collect ( Collectors . toList ()); ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 2. JAVA ARCHITECTURE <br/> ## Q. What is JVM and is it platform independent? Java Virtual Machine (JVM) is a specification that provides runtime environment in which java bytecode(.class files) can be executed. The JVM is the platform. The JVM acts as a "virtual" machine or processor. Java\'s platform independence consists mostly of its Java Virtual Machine (JVM). JVM makes this possible because it is aware of the specific instruction lengths and other particularities of the platform (Operating System). The JVM is not platform independent. Java Virtual Machine (JVM) provides the environment to execute the java file(. Class file). So at the end it's depends on kernel and kernel is differ from OS (Operating System) to OS. The JVM is used to both translate the bytecode into the machine language for a particular computer and actually execute the corresponding machine-language instructions as well. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is JIT compiler in Java? The Just-In-Time (JIT) compiler is a component of the runtime environment that improves the performance of Java applications by compiling bytecodes to native machine code at run time. Java programs consists of classes, which contain platform-neutral bytecodes that can be interpreted by a JVM on many different computer architectures. At run time, the JVM loads the class files, determines the semantics of each individual bytecode, and performs the appropriate computation. The additional processor and memory usage during interpretation means that a Java application performs more slowly than a native application. The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time. The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is Classloader in Java? The **Java ClassLoader** is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source. **Types of ClassLoader:** **1. Bootstrap Class Loader**: It loads standard JDK class files from rt.jar and other core classes. It loads class files from jre/lib/rt.jar. For example, java.lang package class. **2. Extensions Class Loader**: It loads classes from the JDK extensions directly usually `JAVA_HOME/lib/ext` directory or any other directory as java.ext.dirs. **3. System Class Loader**: It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Java Compiler is stored in JDK, JRE or JVM? **1. JDK**: Java Development Kit is the core component of Java Environment and provides all the tools, executables and binaries required to compile, debug and execute a Java Program. **2. JVM**: JVM is responsible for converting Byte code to the machine specific code. JVM is also platform dependent and provides core java functions like memory management, garbage collection, security etc. JVM is customizable and we can use java options to customize it, for example allocating minimum and maximum memory to JVM. JVM is called virtual because it provides an interface that does not depend on the underlying operating system and machine hardware. **2. JRE**: Java Runtime Environment provides a platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. <p align="center"> <img src="assets/jdk.jpg" alt="Java Compiler" width="500px" /> </p> <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between Heap and Stack Memory in java? **1. Java Heap Space:** Java Heap space is used by java runtime to allocate memory to **Objects** and **JRE classes**. Whenever we create any object, it\'s always created in the Heap space. Garbage Collection runs on the heap memory to free the memory used by objects that doesn\'t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application. **2. Java Stack Memory:** Stack in java is a section of memory which contains **methods**, **local variables** and **reference variables**. Local variables are created in the stack. Stack memory is always referenced in LIFO ( Last-In-First-Out ) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method. As soon as method ends, the block becomes unused and become available for next method. Stack memory size is very less compared to Heap memory. **Difference:** |Parameter |Stack Memory |Heap Space | |------------------|-----------------------------|-----------------------------------| |Application |Stack is used in parts, one at a time during execution of a thread| The entire application uses Heap space during runtime| |Size |Stack has size limits depending upon OS and is usually smaller then Heap|There is no size limit on Heap| |Storage |Stores only primitive variables and references to objects that are created in Heap Space|All the newly created objects are stored here| |Order |It is accessed using Last-in First-out (LIFO) memory allocation system| This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.| |Life |Stack memory only exists as long as the current method is running|Heap space exists as long as the application runs| |Efficiency |Comparatively much faster to allocate when compared to heap| Slower to allocate when compared to stack| |Allocation/Deallocation| This Memory is automatically allocated and deallocated when a method is called and returned respectively|Heap space is allocated when new objects are created and deallocated by Gargabe Collector when they are no longer referenced | <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How many types of memory areas are allocated by JVM? JVM is a program which takes Java bytecode and converts the byte code (line by line) into machine understandable code. JVM perform some particular types of operations: * Loading of code * Verification of code * Executing the code * It provide run-time environment to the users **Types of Memory areas allocated by the JVM:** **1. Classloader**: Classloader is a subsystem of JVM that is used to load class files. **2. Class(Method) Area**: Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods. **3. Heap**: It is the runtime data area in which objects are allocated. **4. Stack**: Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as thread. **5. Program Counter Register**: PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed. **6. Native Method Stack**: It contains all the native methods used in the application. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 3. JAVA DATA TYPES <br/> ## Q. What are autoboxing and unboxing? The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing and opposite operation is known as unboxing. **Example:** Autoboxing ```java /** * Autoboxing */ class BoxingExample { public static void main(String args[]) { int a = 50; Integer a2 = new Integer(a); // Boxing Integer a3 = 5; // Boxing System.out.println(a2 + " " + a3); } } ``` **Example:** Unboxing ```java /** * Unboxing */ class UnboxingExample { public static void main(String args[]) { Integer i = new Integer(50); int a = i; System.out.println(a); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the difference between transient and volatile variable in Java? **1. Transient:** The transient modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null for a reference type, and zero or false for a primitive type. **Example:** ```java /** * Transient */ public transient int limit = 55; // will not persist public int b; // will persist ``` **2. Volatile:** The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. **Example:** ```java /** * Volatile */ public class MyRunnable implements Runnable { private volatile boolean active; public void run() { active = true; while (active) { } } public void stop() { active = false; } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are assertions in Java? An assertion allows testing the correctness of any assumptions that have been made in the program. Assertion is achieved using the assert statement in Java. While executing assertion, it is believed to be true. If it fails, JVM throws an error named `AssertionError`. It is mainly used for testing purposes during development. The assert statement is used with a Boolean expression and can be written in two different ways. ```java // First way assert expression; // Second way assert expression1 : expression2; ``` **Example:** ```java /** * Assertions */ public class Example { public static void main(String[] args) { int age = 14; assert age <= 18 : "Cannot Vote"; System.out.println("The voter's age is " + age); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the final variable, final class, and final blank variable? **1. Final Variable:** Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized. **Example:** ```java /** * Final Variable */ class Demo { final int MAX_VALUE = 99; void myMethod() { MAX_VALUE = 101; } public static void main(String args[]) { Demo obj = new Demo(); obj.myMethod(); } } ``` Output ```java Exception in thread "main" java.lang.Error: Unresolved compilation problem: The final field Demo.MAX_VALUE cannot be assigned at beginnersbook.com.Demo.myMethod(Details.java:6) at beginnersbook.com.Demo.main(Details.java:10) ``` **2. Blank final variable:** A final variable that is not initialized at the time of declaration is known as blank final variable. We must initialize the blank final variable in constructor of the class otherwise it will throw a compilation error ( Error: `variable MAX_VALUE might not have been initialized` ). **Example:** ```java /** * Blank final variable */ class Demo { // Blank final variable final int MAX_VALUE; Demo() { // It must be initialized in constructor MAX_VALUE = 100; } void myMethod() { System.out.println(MAX_VALUE); } public static void main(String args[]) { Demo obj = new Demo(); obj.myMethod(); } } ``` Output ```java 100 ``` **3. Final Method:** A final method cannot be overridden. Which means even though a sub class can call the final method of parent class without any issues but it cannot override it. **Example:** ```java /** * Final Method */ class XYZ { final void demo() { System.out.println("XYZ Class Method"); } } class ABC extends XYZ { void demo() { System.out.println("ABC Class Method"); } public static void main(String args[]) { ABC obj = new ABC(); obj.demo(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a compile time constant in Java? If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. **Compile time constant must be:** * Declared final * Primitive or String * Initialized within declaration * Initialized with constant expression They are replaced with actual values at compile time because compiler know their value up-front and also knows that it cannot be changed during run-time. ```java private final int x = 10; ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the different access specifiers available in java? * access specifiers/modifiers helps to restrict the scope of a class, constructor, variable, method, or data member. * There are four types of access modifiers available in java: 1. `default` – No keyword required, when a class, constructor,variable, method, or data member declared without any access specifier then it is having default access scope i.e. accessible only within the same package. 2. `private` - when declared as a private , access scope is limited within the enclosing class. 3. `protected` - when declared as protocted, access scope is limited to enclosing classes, subclasses from same package as well as other packages. 4. `public` - when declared as public, accessible everywhere in the program. ```java ... /* data member variables */ String firstName="Pradeep"; /* default scope */ protected isValid=true; /* protected scope */ private String otp="AB0392"; /* private scope */ public int id = 12334; /* public scope */ ... ... /* data member functions */ String getFirstName(){ return this.firstName; } /* default scope */ protected boolean getStatus(){this.isValid;} /* protected scope */ private void generateOtp(){ /* private scope */ this.otp = this.hashCode() << 16; }; public int getId(){ return this.id; } /* public scope */ ... .../* inner classes */ class A{} /* default scope */ protected class B{} /* protected scope */ private class C{} /* private scope */ public class D{} /* public scope */ ... ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 4. JAVA METHODS <br/> ## Q. Can you have virtual functions in Java? In Java, all non-static methods are by default **virtual functions**. Only methods marked with the keyword `final`, which cannot be overridden, along with `private methods`, which are not inherited, are non-virtual. **Example:** Virtual function with Interface ```java /** * The function applyBrakes() is virtual because * functions in interfaces are designed to be overridden. **/ interface Bicycle { void applyBrakes(); } class ACMEBicycle implements Bicycle { public void applyBrakes() { // Here we implement applyBrakes() System.out.println("Brakes applied"); // function } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a native method? A native method is a Java method (either an instance method or a class method) whose implementation is also written in another programming language such as C/C++. Moreover, a method marked as native cannot have a body and should end with a semicolon: **Main.java:** ```java public class Main { public native int intMethod(int i); public static void main(String[] args) { System.loadLibrary("Main"); System.out.println(new Main().intMethod(2)); } } ``` **Main.c:** ```c #include <jni.h> #include "Main.h" JNIEXPORT jint JNICALL Java_Main_intMethod( JNIEnv *env, jobject obj, jint i) { return i * i; } ``` **Compile and Run:** ```java javac Main.java javah -jni Main gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \ -I${JAVA_HOME}/include/linux Main.c java -Djava.library.path=. Main ``` Output ```java 4 ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the restrictions that are applied to the Java static methods? If a method is declared as static, it is a member of a class rather than belonging to the object of the class. It can be called without creating an object of the class. A static method also has the power to access static data members of the class. There are a few restrictions imposed on a static method * The static method cannot use non-static data member or invoke non-static method directly. * The `this` and `super` cannot be used in static context. * The static method can access only static type data ( static type instance variable ). * There is no need to create an object of the class to invoke the static method. * A static method cannot be overridden in a subclass **Example:** ```java /** * Static Methods */ class Parent { static void display() { System.out.println("Super class"); } } public class Example extends Parent { void display() // trying to override display() { System.out.println("Sub class"); } public static void main(String[] args) { Parent obj = new Example(); obj.display(); } } ``` This generates a compile time error. The output is as follows − ```java Example.java:10: error: display() in Example cannot override display() in Parent void display() // trying to override display() ^ overridden method is static 1 error ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a lambda? What is the structure and features of using a lambda expression? A lambda is a set of instructions that can be separated into a separate variable and then repeatedly called in various places of the program. The basis of the lambda expression is the _lambda operator_ , which represents the arrow `->`. This operator divides the lambda expression into two parts: the left side contains a list of expression parameters, and the right actually represents the body of the lambda expression, where all actions are performed. The lambda expression is not executed by itself, but forms the implementation of the method defined in the functional interface. It is important that the functional interface should contain only one single method without implementation. ```java interface Operationable { int calculate ( int x , int y ); } public static void main ( String [] args) { Operationable operation = (x, y) - > x + y; int result = operation.calculate ( 10 , 20 ); System.out.println (result); // 30 } ``` In fact, lambda expressions are in some way a shorthand form of internal anonymous classes that were previously used in Java. * _Deferred execution lambda expressions_ - it is defined once in one place of the program, it is called if necessary, any number of times and in any place of the program. * _The parameters of the lambda expression_ must correspond in type to the parameters of the functional interface method: ```javascript operation = ( int x, int y) - > x + y; // When writing the lambda expression itself, the parameter type is allowed not to be specified: (x, y) - > x + y; // If the method does not accept any parameters, then empty brackets are written, for example: () - > 30 + 20 ; // If the method accepts only one parameter, then the brackets can be omitted: n - > n * n; ``` * Trailing lambda expressions are not required to return any value. ```java interface Printable { void print( String s ); } public static void main ( String [] args) { Printable printer = s - > System.out.println(s); printer.print("Hello, world"); } // _ Block lambda - expressions_ are surrounded by curly braces . The modular lambda - expressions can be used inside nested blocks, loops, `design the if ` ` switch statement ', create variables, and so on . d . If you block a lambda - expression must return a value, it explicitly applies `statement return statement ' : Operationable operation = ( int x, int y) - > { if (y == 0 ) { return 0 ; } else { return x / y; } }; ``` * Passing a lambda expression as a method parameter ```java interface Condition { boolean isAppropriate ( int n ); } private static int sum ( int [] numbers, Condition condition) { int result = 0 ; for ( int i : numbers) { if (condition.isAppropriate(i)) { result + = i; } } return result; } public static void main ( String [] args) { System.out.println(sum ( new int [] { 0 , 1 , 0 , 3 , 0 , 5 , 0 , 7 , 0 , 9 }, (n) - > n ! = 0 )); } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What variables do lambda expressions have access to? Access to external scope variables from a lambda expression is very similar to access from anonymous objects. * immutable ( effectively final - not necessarily marked as final) local variables; * class fields * static variables. The default methods of the implemented functional interface are not allowed to be accessed inside the lambda expression. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a method reference? If the method existing in the class already does everything that is necessary, then you can use the method reference mechanism (method reference) to directly pass this method. The result will be exactly the same as in the case of defining a lambda expression that calls this method. **Example:** ```java private interface Measurable { public int length(String string); } public static void main ( String [] args) { Measurable a = String::length; System.out.println(a.length("abc")); } ``` Method references are potentially more efficient than using lambda expressions. In addition, they provide the compiler with better information about the type, and if you can choose between using a reference to an existing method and using a lambda expression, you should always use a method reference. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What types of method references do you know? * on the static method; * per instance method; * to the constructor. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 5. JAVA FUNCTIONAL PROGRAMMING <br/> ## # 6. JAVA LAMBDA EXPRESSIONS <br/> ## # 7. JAVA CLASSES <br/> ## Q. What is difference between the Inner Class and Sub Class? Nested Inner class can access any private instance variable of outer class. Like any other instance variable, we can have access modifier private, protected, public and default modifier. **Example:** ```java /** * Inner Class */ class Outer { class Inner { public void show() { System.out.println("In a nested class method"); } } } class Main { public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.show(); } } ``` A subclass is class which inherits a method or methods from a superclass. **Example:** ```java /** * Sub Class */ class Car { //... } class HybridCar extends Car { //... } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Distinguish between static loading and dynamic class loading? **1. Static Class Loading:** Creating objects and instance using `new` keyword is known as static class loading. The retrieval of class definition and instantiation of the object is done at compile time. **Example:** ```java /** * Static Class Loading */ class TestClass { public static void main(String args[]) { TestClass tc = new TestClass(); } } ``` **2. Dynamic Class Loading:** Loading classes use `Class.forName()` method. Dynamic class loading is done when the name of the class is not known at compile time. **Example:** ```java /** * Dynamic Class Loading */ Class.forName (String className); ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the purpose of the Runtime class and System class? **1. Runtime Class:** The **java.lang.Runtime** class is a subclass of Object class, provide access to the Java runtime system. The runtime information like memory availability, invoking the garbage collector, etc. **Example:** ```java /** * Runtime Class */ public class RuntimeTest { static class Message extends Thread { public void run() { System.out.println(" Exit"); } } public static void main(String[] args) { try { Runtime.getRuntime().addShutdownHook(new Message()); System.out.println(" Program Started..."); System.out.println(" Wait for 5 seconds..."); Thread.sleep(5000); System.out.println(" Program Ended..."); } catch (Exception e) { e.printStackTrace(); } } } ``` **2. System Class:** The purpose of the System class is to provide access to system resources. It contains accessibility to standard input, standart output, error output streams, current time in millis, terminating the application, etc. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the ways to instantiate the Class class? **1. Using new keyword:** ```java MyObject object = new MyObject(); ``` **2. Using Class.forName():** ```java MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance(); ``` **3. Using clone():** ```java MyObject anotherObject = new MyObject(); MyObject object = (MyObject) anotherObject.clone(); ``` **4. Using object deserialization:** ```java ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject object = (MyObject) inStream.readObject(); ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is immutable object? Immutable objects are objects that don\'t change. A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field. **Creating an Immutable Object:** * Do not add any setter method * Declare all fields final and private * If a field is a mutable object create defensive copies of it for getter methods * If a mutable object passed to the constructor must be assigned to a field create a defensive copy of it * Don\'t allow subclasses to override methods. ```java /** * Immutable Object */ public class DateContainer { private final Date date; public DateContainer() { this.date = new Date(); } public Date getDate() { return new Date(date.getTime()); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How can we create an immutable class in Java? Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. **Rules to create immutable classes:** * The class must be declared as final * Data members in the class must be declared as final * A parameterized constructor * Getter method for all the variables in it * No setters ```java /** * Immutable Class */ public final class Employee { final String pancardNumber; public Employee(String pancardNumber) { this.pancardNumber = pancardNumber; } public String getPancardNumber() { return pancardNumber; } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How bootstrap class loader works in java? Bootstrap ClassLoader is repsonsible for loading standard JDK classs files from **rt.jar** and it is parent of all class loaders in java. There are three types of built-in ClassLoader in Java: **1. Bootstrap Class Loader:** It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes **2. Extensions Class Loader:** It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory. **3. System Class Loader:** It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options. ```java /** * ClassLoader */ import java.util.logging.Level; import java.util.logging.Logger; public class ClassLoaderTest { public static void main(String args[]) { try { // printing ClassLoader of this class System.out.println("ClassLoader : " + ClassLoaderTest.class.getClassLoader()); // trying to explicitly load this class again using Extension class loader Class.forName("Explicitly load class", true, ClassLoaderTest.class.getClassLoader().getParent()); } catch (ClassNotFoundException ex) { Logger.getLogger(ClassLoaderTest.class.getName()).log(Level.SEVERE, null, ex); } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How can we create a object of a class without using new operator? Different ways to create an object in Java * **Using new Keyword:** ```java class ObjectCreationExample{ String Owner; } public class MainClass { public static void main(String[] args) { // Here we are creating Object of JBT using new keyword ObjectCreationExample obj = new ObjectCreationExample(); } } ``` * **Using New Instance (Reflection)** ```java class CreateObjectClass { static int j = 10; CreateObjectClass() { i = j++; } int i; @Override public String toString() { return "Value of i :" + i; } } class MainClass { public static void main(String[] args) { try { Class cls = Class.forName("CreateObjectClass"); CreateObjectClass obj = (CreateObjectClass) cls.newInstance(); CreateObjectClass obj1 = (CreateObjectClass) cls.newInstance(); System.out.println(obj); System.out.println(obj1); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } ``` * **Using Clone:** ```java class CreateObjectWithClone implements Cloneable { @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } int i; static int j = 10; CreateObjectWithClone() { i = j++; } @Override public String toString() { return "Value of i :" + i; } } class MainClass { public static void main(String[] args) { CreateObjectWithClone obj1 = new CreateObjectWithClone(); System.out.println(obj1); try { CreateObjectWithClone obj2 = (CreateObjectWithClone) obj1.clone(); System.out.println(obj2); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } } ``` * **Using ClassLoader** ```java class CreateObjectWithClassLoader { static int j = 10; CreateObjectWithClassLoader() { i = j++; } int i; @Override public String toString() { return "Value of i :" + i; } } public class MainClass { public static void main(String[] args) { CreateObjectWithClassLoader obj = null; try { obj = (CreateObjectWithClassLoader) new MainClass().getClass() .getClassLoader().loadClass("CreateObjectWithClassLoader").newInstance(); // Fully qualified classname should be used. } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println(obj); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are methods of Object Class? The Object class is the parent class of all the classes in java by default. <table class="alt"> <tbody><tr><th>Method</th><th>Description</th></tr> <tr><td>public final Class getClass()</td><td>returns the Class class object of this object. The Class class can further be used to get the metadata of this class.</td></tr> <tr><td>public int hashCode()</td><td> returns the hashcode number for this object.</td></tr> <tr><td>public boolean equals(Object obj)</td><td> compares the given object to this object.</td></tr> <tr><td>protected Object clone() throws CloneNotSupportedException</td><td> creates and returns the exact copy (clone) of this object.</td></tr> <tr><td>public String toString()</td><td> returns the string representation of this object.</td></tr> <tr><td>public final void notify()</td><td> wakes up single thread, waiting on this object\'s monitor.</td></tr> <tr><td>public final void notifyAll()</td><td> wakes up all the threads, waiting on this object\'s monitor.</td></tr> <tr><td>public final void wait(long timeout)throws InterruptedException</td><td> causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).</td></tr> <tr><td>public final void wait(long timeout,int nanos)throws InterruptedException</td><td>causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).</td></tr> <tr><td>public final void wait()throws InterruptedException</td><td> causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).</td></tr> <tr><td>protected void finalize()throws Throwable</td><td> is invoked by the garbage collector before object is being garbage collected.</td></tr> </tbody></table> <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is Optional An optional value `Optional`is a container for an object that may or may not contain a value `null`. Such a wrapper is a convenient means of prevention `NullPointerException`, as has some higher-order functions, eliminating the need for repeating `if null/notNullchecks`: ```java Optional < String > optional = Optional.of( " hello " ); optional.isPresent(); // true optional.ifPresent(s -> System.out.println(s.length())); // 5 optional.get(); // "hello" optional.orElse( " ops ... " ); // "hello" ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 8. JAVA CONSTRUCTORS <br/> ## Q. How many types of constructors are used in Java? In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. **Types of Java Constructors:** * Default Constructor (or) no-arg Constructor * Parameterized Constructor **Example:** Default Constructor (or) no-arg constructor ```java /** * Default Constructor */ public class Car { Car() { System.out.println("Default Constructor of Car class called"); } public static void main(String args[]) { // Calling the default constructor Car c = new Car(); } } ``` Output ```java Default Constructor of Car class called ``` **Example:** Parameterized Constructor ```java /** * Parameterized Constructor */ public class Car { String carColor; Car(String carColor) { this.carColor = carColor; } public void display() { System.out.println("Color of the Car is : " + carColor); } public static void main(String args[]) { // Calling the parameterized constructor Car c = new Car("Blue"); c.display(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How can constructor chaining be done using this keyword? Java constructor chaining is a method of calling one constructor with the help of another while considering the present object. It can be done in 2 ways – * **Within same class**: It can be done using `this()` keyword for constructors in the same class. * **From base class**: By using `super()` keyword to call a constructor from the base class. ```java /** * Constructor Chaining * within same class Using this() keyword */ class Temp { // default constructor 1 // default constructor will call another constructor // using this keyword from same class Temp() { // calls constructor 2 this(5); System.out.println("The Default constructor"); } // parameterized constructor 2 Temp(int x) { // calls constructor 3 this(10, 20); System.out.println(x); } // parameterized constructor 3 Temp(int x, int y) { System.out.println(10 + 20); } public static void main(String args[]) { // invokes default constructor first new Temp(); } } ``` Ouput: ```java 30 10 The Default constructor ``` ```java /** * Constructor Chaining to * other class using super() keyword */ class Base { String name; // constructor 1 Base() { this(""); System.out.println("No-argument constructor of base class"); } // constructor 2 Base(String name) { this.name = name; System.out.println("Calling parameterized constructor of base"); } } class Derived extends Base { // constructor 3 Derived() { System.out.println("No-argument constructor of derived"); } // parameterized constructor 4 Derived(String name) { // invokes base class constructor 2 super(name); System.out.println("Calling parameterized constructor of derived"); } public static void main(String args[]) { // calls parameterized constructor 4 Derived obj = new Derived("test"); // Calls No-argument constructor // Derived obj = new Derived(); } } ``` Output: ```java Calling parameterized constructor of base Calling parameterized constructor of derived ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a private constructor? * A constructor with private access specifier/modifier is private constructor. * It is only accessible inside the class by its data members(instance fields,methods,inner classes) and in static block. * Private Constructor be used in **Internal Constructor chaining and Singleton class design pattern** ```java public class MyClass { static{ System.out.println("outer static block.."); new MyClass(); } private MyInner in; { System.out.println("outer instance block.."); //new MyClass(); //private constructor accessbile but bad practive will cause infinite loop } private MyClass(){ System.out.println("outer private constructor.."); } public void getInner(){ System.out.println("outer data member function.."); new MyInner(); } private static class MyInner{ { System.out.println("inner instance block.."); new MyClass(); } MyInner(){ System.out.println("inner constructor.."); } } public static void main(String args[]) { System.out.println("static main method.."); MyClass m=new MyClass(); m.getInner(); } } class Visitor{ { new MyClass();//gives compilation error as MyClass() has private access in MyClass } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 9. JAVA ARRAY <br/> ## Q. What is copyonwritearraylist in java? * `CopyOnWriteArrayList` class implements `List` and `RandomAccess` interfaces and thus provide all functionalities available in `ArrayList` class. * Using `CopyOnWriteArrayList` is costly for update operations, because each mutation creates a cloned copy of underlying array and add/update element to it. * It is `thread-safe` version of ArrayList. Each thread accessing the list sees its own version of snapshot of backing array created while initializing the iterator for this list. * Because it gets `snapshot` of underlying array while creating iterator, it does not throw `ConcurrentModificationException`. * Mutation operations on iterators (remove, set, and add) are not supported. These methods throw `UnsupportedOperationException`. * CopyOnWriteArrayList is a concurrent `replacement for a synchronized List` and offers better concurrency when iterations outnumber mutations. * It `allows duplicate elements and heterogeneous Objects` (use generics to get compile time errors). * Because it creates a new copy of array everytime iterator is created, `performance is slower than ArrayList`. * We can prefer to use CopyOnWriteArrayList over normal ArrayList in following cases: - When list is to be used in concurrent environemnt. - Iterations outnumber the mutation operations. - Iterators must have snapshot version of list at the time when they were created. - We don\'t want to synchronize the thread access programatically. ```java import java.util.concurrent.CopyOnWriteArrayList; CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<String>(); copyOnWriteArrayList.add("captain america"); Iterator it = copyOnWriteArrayList.iterator(); //iterator creates separate snapshot copyOnWriteArrayList.add("iron man"); //doesn't throw ConcurrentModificationException while(it.hasNext()) System.out.println(it.next()); // prints captain america only , since add operation is after returning iterator it = copyOnWriteArrayList.iterator(); //fresh snapshot while(it.hasNext()) System.out.println(it.next()); // prints captain america and iron man, it = copyOnWriteArrayList.iterator(); //fresh snapshot while(it.hasNext()){ System.out.println(it.next()); it.remove(); //mutable operation 'remove' not allowed ,throws UnsupportedOperationException } ArrayList<String> list = new ArrayList<String>(); list.add("A"); Iterator ait = list.iterator(); list.add("B"); // immediately throws ConcurrentModificationException while(ait.hasNext()) System.out.println(ait.next()); ait = list.iterator(); while(ait.hasNext()){ System.out.println(ait.next()); ait.remove(); //mutable operation 'remove' allowed without any exception } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 10. JAVA STRINGS <br/> ## Q. What is the difference between creating String as new() and literal? When you create String object using `new()` operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. "Java", it may return an existing object from String pool ( a cache of String object in Perm gen space, which is now moved to heap space in recent Java release ), if it\'s already exists. Otherwise it will create a new string object and put in string pool for future re-use. **Example:** ```java /** * String literal */ String a = "abc"; String b = "abc"; System.out.println(a == b); // true /** * Using new() */ String c = new String("abc"); String d = new String("abc"); System.out.println(c == d); // false ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between String, StringBuffer and StringBuilder? **1. Mutability Difference:** `String` is **immutable**, if you try to alter their values, another object gets created, whereas `StringBuffer` and `StringBuilder` are **mutable** so they can change their values. **2. Thread-Safety Difference:** The difference between `StringBuffer` and `StringBuilder` is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer. **Example:** ```java /** * StringBuffer */ public class BufferTest { public static void main(String[] args) { StringBuffer buffer = new StringBuffer("Hello"); buffer.append(" World"); System.out.println(buffer); } } ``` **Example:** ```java /** * StringBuilder */ public class BuilderTest { public static void main(String[] args) { StringBuilder builder = new StringBuilder("Hello"); builder.append(" World"); System.out.println(builder); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Why string is immutable in java? The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client\'s action would affect all another client. Since string is immutable it can safely share between many threads and avoid any synchronization issues in java. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is Java String Pool? String Pool in java is a pool of Strings stored in Java Heap Memory. String pool helps in saving a lot of space for Java Runtime although it takes more time to create the String. When we use double quotes to create a String, it first looks for String with the same value in the String pool, if found it just returns the reference else it creates a new String in the pool and then returns the reference. However using **new** operator, we force String class to create a new String object in heap space. ```java /** * String Pool */ public class StringPool { public static void main(String[] args) { String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println("s1 == s2 :" + (s1 == s2)); // true System.out.println("s1 == s3 :" + (s1 == s3)); // false } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between String, StringBuilder and StringBuffer? String is `immutable`, if you try to alter their values, another object gets created, whereas `StringBuffer` and `StringBuilder` are mutable so they can change their values. The difference between `StringBuffer` and `StringBuilder` is that `StringBuffer` is thread-safe. So when the application needs to be run only in a single thread then it is better to use `StringBuilder`. `StringBuilder` is more efficient than StringBuffer. **Situations:** * If your string is not going to change use a String class because a `String` object is immutable. * If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a `StringBuilder` is good enough. * If your string can change, and will be accessed from multiple threads, use a `StringBuffer` because `StringBuffer` is synchronous so you have thread-safety. **Example:** ```java class StringExample { // Concatenates to String public static void concat1(String s1) { s1 = s1 + "World"; } // Concatenates to StringBuilder public static void concat2(StringBuilder s2) { s2.append("World"); } // Concatenates to StringBuffer public static void concat3(StringBuffer s3) { s3.append("World"); } public static void main(String[] args) { String s1 = "Hello"; concat1(s1); // s1 is not changed System.out.println("String: " + s1); StringBuilder s2 = new StringBuilder("Hello"); concat2(s2); // s2 is changed System.out.println("StringBuilder: " + s2); StringBuffer s3 = new StringBuffer("Hello"); concat3(s3); // s3 is changed System.out.println("StringBuffer: " + s3); } } ``` Output ```java String: Hello StringBuilder: World StringBuffer: World ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is StringJoiner? The class is StringJoinerused to create a sequence of strings separated by a separator with the ability to append a prefix and suffix to the resulting string: ```java StringJoiner joiner = new StringJoiner ( " . " , " Prefix- " , " -suffix " ); for ( String s : " Hello the brave world " . split ( " " )) { , joiner, . add (s); } System.out.println(joiner); // prefix-Hello.the.brave.world-suffix ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 11. JAVA REFLECTION <br/> ## Q. What is Java Reflection API? Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc. at **runtime**. The **java.lang.Class** class provides many methods that can be used to get metadata, examine and change the run time behavior of a class. There are 3 ways to get the instance of Class class. * forName() method of Class class * getClass() method of Object class * the .class syntax **1. forName() method:** * is used to load the class dynamically. * returns the instance of Class class. * It should be used if you know the fully qualified name of class.This cannot be used for primitive types. ```java /** * forName() */ class Simple { } class Test { public static void main(String args[]) { Class c = Class.forName("Simple"); System.out.println(c.getName()); } } ``` Output ```java Simple ``` **2. getClass() method:** It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives. ```java /** * getClass */ class Simple { } class Test { void printName(Object obj) { Class c = obj.getClass(); System.out.println(c.getName()); } public static void main(String args[]) { Simple s = new Simple(); Test t = new Test(); t.printName(s); } } ``` Output ```java Simple ``` **3. The .class syntax:** If a type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. It can be used for primitive data type also. ```java /** * .class Syntax */ class Test { public static void main(String args[]) { Class c = boolean.class; System.out.println(c.getName()); Class c2 = Test.class; System.out.println(c2.getName()); } } ``` Output ```java boolean Test ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 12. JAVA STREAMS <br/> ## Q. What is Stream? An interface `java.util.Stream` is a sequence of elements on which various operations can be performed. Operations on streams can be either intermediate (intermediate) or final (terminal) . Final operations return a result of a certain type, and intermediate operations return the same stream. Thus, you can build chains of several operations on the same stream. A stream can have any number of calls to intermediate operations and the last call to the final operation. At the same time, all intermediate operations are performed lazily and until the final operation is called, no actions actually happen (similar to creating an object `Thread`or `Runnable`, without a call `start()`). Streams are created based on sources of some, for example, classes from `java.util.Collection`. Associative arrays (maps), for example `HashMap`, are not supported. Operations on streams can be performed both sequentially and in parallel. Streams cannot be reused. As soon as some final operation has been called, the flow is closed. In addition to the universal object, there are special types of streams to work with primitive data types `int`, `long`and `double`: `IntStream`, `LongStream`and `DoubleStream`. These primitive streams work just like regular object streams, but with the following differences: * use specialized lambda expressions, for example, `IntFunction`or `IntPredicate`instead of `Function`and `Predicate`; * support additional end operations `sum()`, `average()`, `mapToObj()`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the ways to create a stream? * Using collection: ```java Stream < String > fromCollection = Arrays.asList ( " x " , " y " , " z " ).stream (); ``` * Using set of values: ```java Stream < String > fromValues = Stream.of( " x " , " y " , " z " ); ``` * Using Array ```java Stream < String > fromArray = Arrays.stream( new String [] { " x " , " y " , " z " }); ``` * Using file (each line in the file will be a separate element in the stream): ```java Stream < String > fromFile = Files.lines( Paths.get(" input.txt ")); ``` * From the line: ```java IntStream fromString = " 0123456789 " . chars (); ``` * With the help of `Stream.builder()`: ```java Stream < String > fromBuilder = Stream.builder().add (" z ").add(" y ").add(" z ").build (); ``` * Using `Stream.iterate()(infinite)`: ```java Stream < Integer > fromIterate = Stream.iterate ( 1 , n - > n + 1 ); ``` * Using `Stream.generate()(infinite)`: ```java Stream < String > fromGenerate = Stream.generate(() -> " 0 " ); ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the difference between `Collection` and `Stream`? Collections allow you to work with elements separately, while streams do not allow this, but instead provides the ability to perform functions on data as one. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the method `collect()`for streams for? A method `collect()`is the final operation that is used to represent the result as a collection or some other data structure. `collect()`accepts an input that contains four stages: * **supplier** — initialization of the battery, * **accumulator** — processing of each element, * **combiner** — connection of two accumulators in parallel execution, * **[finisher]** —a non-mandatory method of the last processing of the accumulator. In Java 8, the class `Collectors` implements several common collectors: * `toList()`, `toCollection()`, `toSet()`- present stream in the form of a list, collection or set; * `toConcurrentMap()`, `toMap()`- allow you to convert the stream to `Map`; * `averagingInt()`, `averagingDouble()`, `averagingLong()`- return the average value; * `summingInt()`, `summingDouble()`, `summingLong()`- returns the sum; * `summarizingInt()`, `summarizingDouble()`, `summarizingLong()`- return SummaryStatisticswith different values of the aggregate; * `partitioningBy()`- divides the collection into two parts according to the condition and returns them as `Map<Boolean, List>`; * `groupingBy()`- divides the collection into several parts and returns `Map<N, List<T>>`; * `mapping()`- Additional value conversions for complex Collectors. There is also the possibility of creating your own collector through `Collector.of()`: ```java Collector < String , a List < String > , a List < String > > toList = Collector.of ( ArrayList :: new , List :: add, (l1, l2) -> {l1 . addAll (l2); return l1; } ); ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Why do streams use `forEach()`and `forEachOrdered()` methods? * `forEach()` applies a function to each stream object; ordering in parallel execution is not guaranteed; * `forEachOrdered()` applies a function to each stream object while maintaining the order of the elements. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are `map()`, `mapToInt()`, `mapToDouble()` and `mapToLong()` methods in Stream? The method `map()`is an intermediate operation, which transforms each element of the stream in a specified way. `mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`, returns the corresponding numerical stream (ie the stream of numerical primitives): ```java Stream .of ( " 12 " , " 22 " , " 4 " , " 444 " , " 123 " ) .mapToInt ( Integer :: parseInt) .toArray (); // [12, 22, 4, 444, 123] ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the purpose of `filter()` method in streams? The method `filter()` is an intermediate operation receiving a predicate that filters all elements, returning only those that match the condition. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the use of `limit()` method in streams? The method `limit()`is an intermediate operation, which allows you to limit the selection to a certain number of first elements. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the use of `sorted()` method in streams? The method `sorted()`is an intermediate operation, which allows you to sort the values ​​either in natural order or by setting Comparator. The order of the elements in the original collection remains untouched - `sorted()`it just creates its sorted representation. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What streamers designed methods `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`? The method `flatMap()` is similar to map, but can create several from one element. Thus, each object will be converted to zero, one or more other objects supported by the stream. The most obvious way to use this operation is to convert container elements using functions that return containers. ```java Stream .of ( " Hello " , " world! " ) .flatMap ((p) -> Arrays.stream (p . split ( " , " ))) .toArray ( String [] :: new ); // ["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"] ``` `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- are analogues `flatMap()`, returns the corresponding numerical stream. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the final methods of working with streams you know? * `findFirst()` returns the first element * `findAny()` returns any suitable item * `collect()` presentation of results in the form of collections and other data structures * `count()` returns the number of elements * `anyMatch()`returns trueif the condition is satisfied for at least one element * `noneMatch()`returns trueif the condition is not satisfied for any element * `allMatch()`returns trueif the condition is satisfied for all elements * `min()`returns the minimum element, using as a condition Comparator * `max()`returns the maximum element, using as a condition Comparator * `forEach()` applies a function to each object (order is not guaranteed in parallel execution) * `forEachOrdered()` applies a function to each object while preserving the order of elements * `toArray()` returns an array of values * `reduce()`allows you to perform aggregate functions and return a single result. * `sum()` returns the sum of all numbers * `average()` returns the arithmetic mean of all numbers. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What intermediate methods of working with streams do you know? * `filter()` filters records, returning only records matching the condition; * `skip()` allows you to skip a certain number of elements at the beginning; * `distinct()`returns a stream without duplicates (for a method `equals()`); * `map()` converts each element; * `peek()` returns the same stream, applying a function to each element; * `limit()` allows you to limit the selection to a certain number of first elements; * `sorted()`allows you to sort values ​​either in natural order or by setting `Comparator`; * `mapToInt()`, `mapToDouble()`, `mapToLong()`- analogues `map()`return stream numeric primitives; * `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`- similar to `map()`, but can create a single element more. For numerical streams, an additional method is available `mapToObj()`that converts the numerical stream back to the object stream. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> #### Q. Explain Difference between Collection API and Stream API? *ToDo* <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 13. JAVA REGULAR EXPRESSIONS <br/> ## Q. Name some classes present in java.util.regex package? The Java Regex or Regular Expression is an API to define a pattern for searching or manipulating strings. **Regular Expression Package:** * MatchResult interface * Matcher class * Pattern class * PatternSyntaxException class **Example:** ```java /** * Regular Expression */ import java.util.regex.*; public class Index { public static void main(String args[]) { // Pattern, String boolean b = Pattern.matches(".s", "as"); System.out.println("Match: " + b); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 14. JAVA FILE HANDLING <br/> ## Q. What is the purpose of using BufferedInputStream and BufferedOutputStream classes? `BufferedInputStream` and `BufferedOutputStream` class is used for buffering an input and output stream while reading and writing, respectively. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast. **Example:** ```java /** * BufferedInputStream */ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class BufferedInputStreamExample { public static void main(String[] args) { File file = new File("file.txt"); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; try { fileInputStream = new FileInputStream(file); bufferedInputStream = new BufferedInputStream(fileInputStream); // Create buffer byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = bufferedInputStream.read(buffer)) != -1) { System.out.println(new String(buffer, 0, bytesRead)); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileInputStream != null) { fileInputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` Output ```java This is an example of reading data from file ``` **Example:** ```java /** * BufferedOutputStream */ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class BufferedOutputStreamExample { public static void main(String[] args) { File file = new File("outfile.txt"); FileOutputStream fileOutputStream = null; BufferedOutputStream bufferedOutputStream = null; try { fileOutputStream = new FileOutputStream(file); bufferedOutputStream = new BufferedOutputStream(fileOutputStream); bufferedOutputStream.write("This is an example of writing data to a file".getBytes()); bufferedOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } if (bufferedOutputStream != null) { bufferedOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` Output ```java This is an example of writing data to a file ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to set the Permissions to a file in Java? Java 7 has introduced PosixFilePermission Enum and **java.nio.file.Files** includes a method setPosixFilePermissions( Path path, `Set<PosixFilePermission> perms` ) that can be used to set file permissions easily. **Example:** ```java /** * FilePermissions */ import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.attribute.PosixFilePermission; import java.util.HashSet; import java.util.Set; public class FilePermissions { public static void main(String[] args) throws IOException { File file = new File("/Users/file.txt"); // change permission to 777 for all the users // no option for group and others file.setExecutable(true, false); file.setReadable(true, false); file.setWritable(true, false); // using PosixFilePermission to set file permissions 777 Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); perms.add(PosixFilePermission.OWNER_EXECUTE); // add group permissions perms.add(PosixFilePermission.GROUP_READ); perms.add(PosixFilePermission.GROUP_WRITE); perms.add(PosixFilePermission.GROUP_EXECUTE); // add others permissions perms.add(PosixFilePermission.OTHERS_READ); perms.add(PosixFilePermission.OTHERS_WRITE); perms.add(PosixFilePermission.OTHERS_EXECUTE); Files.setPosixFilePermissions(Paths.get("/Users/run.sh"), perms); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Give the hierarchy of InputStream and OutputStream classes? A stream can be defined as a sequence of data. There are two kinds of Streams − * **InPutStream** − The InputStream is used to read data from a source. * **OutPutStream** − The OutputStream is used for writing data to a destination. **1. Byte Streams:** Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. **Example:** ```java /** * Byte Streams */ import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } ``` **2. Character Streams:** Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. **Example:** ```java /** * Character Streams */ import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader("input.txt"); out = new FileWriter("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How serialization works in java? Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. **Example:** ```java /** * Serialization and Deserialization */ import java.io.*; class Employee implements Serializable { private static final long serialversionUID = 129348938L; transient int a; static int b; String name; int age; // Default constructor public Employee(String name, int age, int a, int b) { this.name = name; this.age = age; this.a = a; this.b = b; } } public class SerialExample { public static void printdata(Employee object1) { System.out.println("name = " + object1.name); System.out.println("age = " + object1.age); System.out.println("a = " + object1.a); System.out.println("b = " + object1.b); } public static void main(String[] args) { Employee object = new Employee("ab", 20, 2, 1000); String filename = "file.txt"; // Serialization try { // Saving of object in a file FileOutputStream file = new FileOutputStream(filename); ObjectOutputStream out = new ObjectOutputStream(file); // Method for serialization of object out.writeObject(object); out.close(); file.close(); System.out.println("Object has been serialized\n" + "Data before Deserialization."); printdata(object); // value of static variable changed object.b = 2000; } catch (IOException ex) { System.out.println("IOException is caught"); } object = null; // Deserialization try { // Reading the object from a file FileInputStream file = new FileInputStream(filename); ObjectInputStream in = new ObjectInputStream(file); // Method for deserialization of object object = (Employee) in.readObject(); in.close(); file.close(); System.out.println("Object has been deserialized\n" + "Data after Deserialization."); printdata(object); System.out.println("z = " + object1.z); } catch (IOException ex) { System.out.println("IOException is caught"); } catch (ClassNotFoundException ex) { System.out.println("ClassNotFoundException is caught"); } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 15. JAVA EXCEPTIONS <br/> ## Q. What are the types of Exceptions? Exception is an error event that can happen during the execution of a program and disrupts its normal flow. **1. Checked Exception**: The classes which directly inherit **Throwable class** except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time. **2. Unchecked Exception**: The classes which inherit **RuntimeException** are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime. **3. Error**: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Explain hierarchy of Java Exception classes? The **java.lang.Throwable** class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. <p align="center"> <img src="assets/exception.png" alt="Exception in Java" width="500px" /> </p> **Example:** ```java /** * Exception classes */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class CustomExceptionExample { public static void main(String[] args) throws MyException { try { processFile("file.txt"); } catch (MyException e) { processErrorCodes(e); } } private static void processErrorCodes(MyException e) throws MyException { switch(e.getErrorCode()){ case "BAD_FILE_TYPE": System.out.println("Bad File Type, notify user"); throw e; case "FILE_NOT_FOUND_EXCEPTION": System.out.println("File Not Found, notify user"); throw e; case "FILE_CLOSE_EXCEPTION": System.out.println("File Close failed, just log it."); break; default: System.out.println("Unknown exception occured," +e.getMessage()); e.printStackTrace(); } } private static void processFile(String file) throws MyException { InputStream fis = null; try { fis = new FileInputStream(file); } catch (FileNotFoundException e) { throw new MyException(e.getMessage(),"FILE_NOT_FOUND_EXCEPTION"); } finally { try { if(fis !=null) fis.close(); } catch (IOException e) { throw new MyException(e.getMessage(),"FILE_CLOSE_EXCEPTION"); } } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between Error and Exception? |BASIS FOR COMPARISON |ERROR |EXCEPTION | |-----------------------|-----------------------------------------|----------------------------------------| |Basic |An error is caused due to lack of system resources.|An exception is caused because of the code.| |Recovery |An error is irrecoverable. |An exception is recoverable.| |Keywords |There is no means to handle an error by the program code.| Exceptions are handled using three keywords "try", "catch", and "throw".| |Consequences |As the error is detected the program will terminated abnormally.|As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly.| |Types |Errors are classified as unchecked type.|Exceptions are classified as checked or unchecked type.| |Package |In Java, errors are defined "java.lang.Error" package.|In Java, an exceptions are defined in"java.lang.Exception".| |Example |OutOfMemory, StackOverFlow.|Checked Exceptions: NoSuchMethod, ClassNotFound.Unchecked Exceptions: NullPointer, IndexOutOfBounds.| <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Explain about Exception Propagation? An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation. **Example:** ```java /** * Exception Propagation */ class TestExceptionPropagation { void method1() { int data = 10 / 0; // generates an exception System.out.println(data); } void method2() { method1(); // doesn't catch the exception } void method3() { // method3 catches the exception try { method2(); } catch (Exception e) { System.out.println("Exception is caught"); } } public static void main(String args[]) { TestExceptionPropagation obj = new TestExceptionPropagation(); obj.method3(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are different scenarios causing "Exception in thread main"? Some of the common main thread exception are as follows: * **Exception in thread main java.lang.UnsupportedClassVersionError**: This exception comes when your java class is compiled from another JDK version and you are trying to run it from another java version. * **Exception in thread main java.lang.NoClassDefFoundError**: There are two variants of this exception. The first one is where you provide the class full name with .class extension. The second scenario is when Class is not found. * **Exception in thread main java.lang.NoSuchMethodError: main**: This exception comes when you are trying to run a class that doesn\'t have main method. * **Exception in thread "main" java.lang.ArithmeticException**: Whenever any exception is thrown from main method, it prints the exception is console. The first part explains that exception is thrown from main method, second part prints the exception class name and then after a colon, it prints the exception message. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the differences between throw and throws? **Throw** keyword is used in the method body to throw an exception, while **throws** is used in method signature to declare the exceptions that can occur in the statements present in the method. **Example:** ```java /** * Throw in Java */ public class ThrowExample { void checkAge(int age) { if (age < 18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]) { ThrowExample obj = new ThrowExample(); obj.checkAge(13); System.out.println("End Of Program"); } } ``` Output ```java Exception in thread "main" java.lang.ArithmeticException: Not Eligible for voting at Example1.checkAge(Example1.java:4) at Example1.main(Example1.java:10) ``` **Example:** ```java /** * Throws in Java */ public class ThrowsExample { int division(int a, int b) throws ArithmeticException { int t = a / b; return t; } public static void main(String args[]) { ThrowsExample obj = new ThrowsExample(); try { System.out.println(obj.division(15, 0)); } catch (ArithmeticException e) { System.out.println("You shouldn't divide number by zero"); } } } ``` Output ```java You shouldn\'t divide number by zero ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. While overriding a method can you throw another exception or broader exception? If a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass. This is because of polymorphism. **Example:** ```java class A { public void message() throws IOException {..} } class B extends A { @Override public void message() throws SocketException {..} // allowed @Override public void message() throws SQLException {..} // NOT allowed public static void main(String args[]) { A a = new B(); try { a.message(); } catch (IOException ex) { // forced to catch this by the compiler } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is checked, unchecked exception and errors? **1. Checked Exception**: * These are the classes that extend **Throwable** except **RuntimeException** and **Error**. * They are also known as compile time exceptions because they are checked at **compile time**, meaning the compiler forces us to either handle them with try/catch or indicate in the function signature that it **throws** them and forcing us to deal with them in the caller. * They are programmatically recoverable problems which are caused by unexpected conditions outside the control of the code (e.g. database down, file I/O error, wrong input, etc). **Example:** **IOException, SQLException** etc. ```java import java.io.*; class Main { public static void main(String[] args) { FileReader file = new FileReader("C:\\assets\\file.txt"); BufferedReader fileInput = new BufferedReader(file); for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } } ``` output: ```java Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown at Main.main(Main.java:5) ``` After adding IOException ```java import java.io.*; class Main { public static void main(String[] args) throws IOException { FileReader file = new FileReader("C:\\assets\\file.txt"); BufferedReader fileInput = new BufferedReader(file); for (int counter = 0; counter < 3; counter++) System.out.println(fileInput.readLine()); fileInput.close(); } } ``` output: ```java Output: First three lines of file “C:\assets\file.txt” ``` **2. Unchecked Exception**: * The classes that extend **RuntimeException** are known as unchecked exceptions. * Unchecked exceptions are not checked at compile-time, but rather at **runtime**, hence the name. * They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration. **Example:** **ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException** etc. ```java class Main { public static void main(String args[]) { int x = 0; int y = 10; int z = y/x; } } ``` Output: ```java Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:5) Java Result: 1 ``` **3. Error**: **Error** refers to an irrecoverable situation that is not being handled by a **try/catch**. Example: **OutOfMemoryError, VirtualMachineError, AssertionError** etc. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between ClassNotFoundException and NoClassDefFoundError? `ClassNotFoundException` and `NoClassDefFoundError` occur when a particular class is not found at runtime. However, they occur at different scenarios. `ClassNotFoundException` is an exception that occurs when you try to load a class at run time using `Class.forName()` or `loadClass()` methods and mentioned classes are not found in the classpath. `NoClassDefFoundError` is an error that occurs when a particular class is present at compile time, but was missing at run time. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 16. JAVA INHERITANCE <br/> ## Q. What is the difference between aggregation and composition? **1. Aggregation:** We call aggregation those relationships whose **objects have an independent lifecycle, but there is ownership**, and child objects cannot belong to another parent object. **Example:** Since Organization has Person as employees, the relationship between them is Aggregation. Here is how they look like in terms of Java classes ```java /** * Aggregation */ public class Organization { private List employees; } public class Person { private String name; } ``` **2. Composition:** We use the term composition to refer to relationships whose objects **don\'t have an independent lifecycle**, and if the parent object is deleted, all child objects will also be deleted. **Example:** Since Engine is-part-of Car, the relationship between them is Composition. Here is how they are implemented between Java classes. ```java /** * Composition */ public class Car { //final will make sure engine is initialized private final Engine engine; public Car(){ engine = new Engine(); } } class Engine { private String type; } ``` <p align="center"> <img src="assets/aggregation.png" alt="Aggregation" width="400px" /> </p> <table class="alt"> <tbody><tr><th>Aggregation</th><th>Composition</th></tr> <tr><td>Aggregation is a weak Association.</td><td>Composition is a strong Association.</td></tr> <tr><td>Class can exist independently without owner.</td><td>Class can not meaningfully exist without owner.</td></tr> <tr><td>Have their own Life Time.</td><td>Life Time depends on the Owner.</td></tr> <tr><td>A uses B.</td><td>A owns B.</td></tr> <tr><td>Child is not owned by 1 owner.</td><td>Child can have only 1 owner.</td></tr> <tr><td>Has-A relationship. A has B.</td><td>Part-Of relationship. B is part of A.</td></tr> <tr><td>Denoted by a empty diamond in UML.</td><td>Denoted by a filled diamond in UML.</td></tr> <tr><td>We do not use "final" keyword for Aggregation.</td><td>"final" keyword is used to represent Composition.</td></tr> <tr><td>Examples:<br>- Car has a Driver.<br>- A Human uses Clothes.<br>- A Company is an aggregation of People.<br>- A Text Editor uses a File.<br>- Mobile has a SIM Card.</td><td>Examples:<br>- Engine is a part of Car.<br>- A Human owns the Heart.<br>- A Company is a composition of Accounts.<br>- A Text Editor owns a Buffer.<br>- IMEI Number is a part of a Mobile.</td></tr> </tbody></table> *Note: "final" keyword is used in Composition to make sure child variable is initialized.* <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. The difference between Inheritance and Composition? Though both Inheritance and Composition provides code reusablility, main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance you must extend the class for any reuse of code or functionality. Inheritance is an **"is-a"** relationship. Composition is a **"has-a"**. **Example:** Inheritance ```java /** * Inheritance */ class Fruit { // ... } class Apple extends Fruit { // ... } ``` **Example:** Composition ```java /** * Composition */ class Fruit { // ... } class Apple { private Fruit fruit = new Fruit(); // ... } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Can you declare the main method as final? Yes. We can declare main method as final. But, In inheritance concept we cannot declare main method as final in parent class. It give compile time error. The main method has to be public because it has to be called by JVM which is outside the scope of the package and hence would need the access specifier-public. **Example:** ```java public class Test { public final static void main(String[] args) throws Exception { System.out.println("This is Test Class"); } } class Child extends Test { public static void main(String[] args) throws Exception { System.out.println("This is Child Class"); } } ``` Output ```java Cannot override the final method from Test. ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is covariant return type? It is possible to have different return type for a overriding method in child class, but child\'s return type should be sub-type of parent\'s return type. Overriding method becomes variant with respect to return type. The covariant return type specifies that the return type may vary in the same direction as the subclass. **Example:** ```java /** * Covariant Return Type */ class SuperClass { SuperClass get() { System.out.println("SuperClass"); return this; } } public class Tester extends SuperClass { Tester get() { System.out.println("SubClass"); return this; } public static void main(String[] args) { SuperClass tester = new Tester(); tester.get(); } } ``` Output: ```java Subclass ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Can you explain Liskov Substitution principle? Liskov Substitution principle (LSP) states that **sub/child/derived-classes should be substitutable for their base/parent-classes.** Given a class B is subclass of class A , we should be able to pass an object of class B to any method that expects(takes as an argument/parameter) an object of class A and the method should not give any weird output in that case. `ClientTestProgram` class has a method `playVideoInAllMediaPlayers()` which accepts list of all `MediaPlayer` objects and plays video for each , but method fails at `WinampMediaPlayer` ? Let's check whether it satisfies **LSP**. ```java public class MediaPlayer { // Play audio implementation public void playAudio() { System.out.println("Playing audio..."); } // Play video implementation public void playVideo() { System.out.println("Playing video..."); } } public class VlcMediaPlayer extends MediaPlayer {} public class WinampMediaPlayer extends MediaPlayer { // Play video is not supported in Winamp player public void playVideo() { throw new VideoUnsupportedException(); } } public class VideoUnsupportedException extends RuntimeException { private static final long serialVersionUID = 1 L; } public class ClientTestProgram { public static void main(String[] args) { // Created list of players List < MediaPlayer > allPlayers = new ArrayList < MediaPlayer > (); allPlayers.add(new VlcMediaPlayer()); allPlayers.add(new DivMediaPlayer()); // Play video in all players playVideoInAllMediaPlayers(allPlayers); // Well - all works as of now...... :-) System.out.println("---------------------------"); // Now adding new Winamp player allPlayers.add(new WinampMediaPlayer()); // Again play video in all players & Oops it broke the program... :-( // Why we got unexpected behavior in client? --- Because LSP is violated in WinampMediaPlayer.java, // as it changed the original behavior of super class MediaPlayer.java playVideoInAllMediaPlayers(allPlayers); } /** * This method is playing video in all players * * @param allPlayers */ public static void playVideoInAllMediaPlayers(List < MediaPlayer > allPlayers) { for (MediaPlayer player: allPlayers) { player.playVideo(); } } } ``` Let\'s refactor the code to make "good" design using **LSP**? - `MediaPlayer` is super class having play audio ability. - `VideoMediaPlayer` extends `MediaPlayer` and adds play video ability. - `DivMediaPlayer` and `VlcMediaPlayer` both extends `VideoMediaPlayer` for playing audio and video ability. - `WinampMediaPlayer` which extends `MediaPlayer` for playing audio ability only. - so client program can substitute `DivMediaPlayer` or `VlcMediaPlayer` for their super class `VideoMediaPlayer` lets reimplement the refactored code ```java public class MediaPlayer { // Play audio implementation public void playAudio() { System.out.println("Playing audio..."); } } //separated video playing ability from base class public class VideoMediaPlayer extends MediaPlayer { // Play video implementation public void playVideo() { System.out.println("Playing video..."); } } public class DivMediaPlayer extends VideoMediaPlayer {} public class VlcMediaPlayer extends VideoMediaPlayer {} //as Winamp expects only audio playing ability, so it must only extend relative base class behaviour, no need to inherit unnecessary behaviour public class WinampMediaPlayer extends MediaPlayer {} /** * This method is playing video in all players * * @param allPlayers */ public static void playVideoInAllMediaPlayers(List <VideoMediaPlayer> allPlayers) { for (VideoMediaPlayer player: allPlayers) { player.playVideo(); } } ``` Now, in `ClientTestProgram` , instead of creating list of type `MediaPlayer`, we will create list of `VideoMediaPlayer` type that should give us compile time error at statement `allPlayers.add(new WinampMediaPlayer()); ` as `WinampMediaPlayer` isnt subclass of `VideoMediaPlayer`.But in case of `DivMediaPlayer` and `VlcMediaPlayer` they are substitutable for their parent class as seen in `playVideoInAllMediaPlayers()` method that satisefies *Liskov's substitution principle*. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 17. JAVA METHOD OVERRIDING <br/> ## # 18. JAVA POLYMORPHISM <br/> ## Q. What is the difference between compile-time polymorphism and runtime polymorphism? There are two types of polymorphism in java: 1. Static Polymorphism also known as Compile time polymorphism 2. Runtime polymorphism also known as Dynamic Polymorphism **1. Static Polymorphism:** Method overloading is one of the way java supports static polymorphism. Here we have two definitions of the same method add() which add method would be called is determined by the parameter list at the compile time. That is the reason this is also known as compile time polymorphism. **Example:** ```java /** * Static Polymorphism */ class SimpleCalculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } public class Demo { public static void main(String args[]) { SimpleCalculator obj = new SimpleCalculator(); System.out.println(obj.add(10, 20)); System.out.println(obj.add(10, 20, 30)); } } ``` Output ```java 30 60 ``` **2. Runtime Polymorphism:** It is also known as **Dynamic Method Dispatch**. Dynamic polymorphism is a process in which a call to an overridden method is resolved at runtime, thats why it is called runtime polymorphism. **Example:** ```java /** * Runtime Polymorphism */ class ABC { public void myMethod() { System.out.println("Overridden Method"); } } public class XYZ extends ABC { public void myMethod() { System.out.println("Overriding Method"); } public static void main(String args[]) { ABC obj = new XYZ(); obj.myMethod(); } } ``` Output: ```java Overriding Method ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What do you mean Run time Polymorphism? `Polymorphism` in Java is a concept by which we can perform a single action in different ways. There are two types of polymorphism in java: * **Static Polymorphism** also known as compile time polymorphism * **Dynamic Polymorphism** also known as runtime polymorphism **Example:** Static Polymorphism ```java class SimpleCalculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } public class MainClass { public static void main(String args[]) { SimpleCalculator obj = new SimpleCalculator(); System.out.println(obj.add(10, 20)); System.out.println(obj.add(10, 20, 30)); } } ``` Output ```java 30 60 ``` **Example:** Runtime polymorphism ```java class ABC { public void myMethod() { System.out.println("Overridden Method"); } } public class XYZ extends ABC { public void myMethod() { System.out.println("Overriding Method"); } public static void main(String args[]) { ABC obj = new XYZ(); obj.myMethod(); } } ``` Output ```java Overriding Method ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is runtime polymorphism in java? **Runtime polymorphism** or **Dynamic Method Dispatch** is a process in which a call to an overridden method is resolved at runtime rather than compile-time. An overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred. ```java class Bank{ public float roi=0.0f; float getRateOfInterest(){return this.roi;} } class SBI extends Bank{ float roi=8.4f; float getRateOfInterest(){return this.roi;} } class ICICI extends Bank{ float roi=7.3f; float getRateOfInterest(){return this.roi;} } class AXIS extends Bank{ float roi=9.7f; float getRateOfInterest(){return this.roi;} } Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); System.out.println("Bank Rate of Interest: "+b.roi); /**output: SBI Rate of Interest: 8.4 ICICI Rate of Interest: 7.3 AXIS Rate of Interest: 9.7 Bank Rate of Interest: 0.0 //you might think it should be 9.7 , as recent object being refered to is of AXIS but method is overridden, not the data members, so runtime polymorphism can't be achieved by data members/instance variables. **/ ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 19. JAVA ABSTRACTION <br/> ## Q. What is the difference between abstract class and interface? Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can\'t be instantiated. |Abstract Class |Interface | |-----------------------------|---------------------------------| |Abstract class can have abstract and non-abstract methods.|Interface can have only abstract methods. Since Java 8, it can have default and static methods also.| |Abstract class doesn\'t support multiple inheritance.|Interface supports multiple inheritance.| |Abstract class can have final, non-final, static and non-static variables.|Interface has only static and final variables.| |Abstract class can provide the implementation of interface.|Interface can\'t provide the implementation of abstract class.| |An abstract class can extend another Java class and implement multiple Java interfaces.|An interface can extend another Java interface only.| |An abstract class can be extended using keyword "extends".|An interface can be implemented using keyword "implements".| |A Java abstract class can have class members like private, protected, etc.|Members of a Java interface are public by default.| <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are Wrapper classes? The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive. **Use of Wrapper classes in Java:** * **Change the value in Method**: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value. * **Serialization**: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes. * **Synchronization**: Java synchronization works with objects in Multithreading. * **java.util package**: The java.util package provides the utility classes to deal with objects. * **Collection Framework**: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only. | Sl.No|Primitive Type | Wrapper class | |------|----------------|----------------------| | 01. |boolean |Boolean| | 02. |char |Character| | 03. |byte |Byte| | 04. |short |Short| | 05. |int |Integer| | 06. |long |Long| | 07. |float |Float| | 08. |double |Double| **Example:** Primitive to Wrapper ```java /** * Java program to convert primitive into objects * Autoboxing example of int to Integer */ class WrapperExample { public static void main(String args[]) { int a = 20; Integer i = Integer.valueOf(a); // converting int into Integer explicitly Integer j = a; // autoboxing, now compiler will write Integer.valueOf(a) internally System.out.println(a + " " + i + " " + j); } } ``` Output ```java 20 20 20 ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the difference between abstraction and encapsulation? In Java, Abstraction is supported using `interface` and `abstract class` while Encapsulation is supported using access modifiers e.g. public, private and protected. Abstraction solves the problem at design level while Encapsulation solves it implementation level. Abstraction is about hiding unwanted details while giving out most essential details, while Encapsulation means hiding the code and data into a single unit e.g. class or method to protect inner working of an object from outside world. **Difference:** <table class="alt"> <tbody><tr><th>Abstraction</th><th>Encapsulation</th></tr> <tr><td>Abstraction is a process of hiding the implementation details and showing only functionality to the user.</td> <td> Encapsulation is a process of wrapping code and data together into a single unit</td></tr> <tr><td>Abstraction lets you focus on what the object does instead of how it does it.</td> <td>Encapsulation provides you the control over the data and keeping it safe from outside misuse.</td></tr> <tr><td>Abstraction solves the problem in the Design Level.</td> <td>Encapsulation solves the problem in the Implementation Level.</td></tr> <tr><td>Abstraction is implemented by using Interfaces and Abstract Classes.</td> <td>Encapsulation is implemented by using Access Modifiers (private, default, protected, public)</td></tr> <tr><td>Abstraction means hiding implementation complexities by using interfaces and abstract class.</td> <td>Encapsulation means hiding data by using setters and getters.</td></tr> </tbody></table> <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 20. JAVA INTERFACES <br/> ## Q. Can we use private or protected member variables in an interface? The java compiler adds public and abstract keywords before the interface method and **public, static and final keyword** before data members automatically ```java public interface Test { public string name1; private String email; protected pass; } ``` as you have declare variable in test interface with private and protected it will give error. if you do not specify the modifier the compiler will add public static final automatically. ```java public interface Test { public static final string name1; public static final String email; public static final pass; } ``` * Interfaces cannot be instantiated that is why the variable are **static** * Interface are used to achieve the 100% abstraction there for the variable are **final** * An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them. that is why variable are **public** <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. When can an object reference be cast to a Java interface reference? An interface reference can point to any object of a class that implements this interface ```java /** * Interface */ interface MyInterface { void display(); } public class TestInterface implements MyInterface { void display() { System.out.println("Hello World"); } public static void main(String[] args) { MyInterface myInterface = new TestInterface(); MyInterface.display(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How can you avoid serialization in child class if the base class is implementing the Serializable interface? If superClass has implemented Serializable that means subclass is also Serializable ( as subclass always inherits all features from its parent class ), for avoiding Serialization in sub-class we can define **writeObject()** method and throw **NotSerializableException()** from there as done below. ```java /** * Serialization */ import java.io.FileOutputStream; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; class Super implements Serializable { private static final long serialVersionUID = 1L; } class Sub extends Super { private static final long serialVersionUID = 1L; private Integer id; public Sub(Integer id) { this.id = id; } @Override public String toString() { return "Employee [id=" + id + "]"; } /* * define how Serialization process will write objects. */ private void writeObject(ObjectOutputStream os) throws NotSerializableException { throw new NotSerializableException("This class cannot be Serialized"); } } public class SerializeDeserialize { public static void main(String[] args) { Sub object1 = new Sub(8); try { OutputStream fout = new FileOutputStream("ser.txt"); ObjectOutput oout = new ObjectOutputStream(fout); System.out.println("Serialization process has started, serializing objects..."); oout.writeObject(object1); fout.close(); oout.close(); System.out.println("Object Serialization completed."); } catch (IOException e) { e.printStackTrace(); } } } ``` Output ```java Serialization process has started, serializing objects... java.io.NotSerializableException: This class cannot be Serialized at SerDeser11throwNotSerExc.Sub.writeObject(SerializeConstructorCheck.java:35) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SerDeser11throwNotSerExc.SerializeConstructorCheck.main(SerializeConstructorCheck.java:51) ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the difference between Serializable and Externalizable interface? |SERIALIZABLE |EXTERNALIZABLE | |----------------|-----------------------| |Serializable is a marker interface i.e. does not contain any method.| Externalizable interface contains two methods writeExternal() and readExternal() which implementing classes MUST override.| |Serializable interface pass the responsibility of serialization to JVM and it\'s default algorithm.| Externalizable provides control of serialization logic to programmer – to write custom logic.| |Mostly, default serialization is easy to implement, but has higher performance cost.|Serialization done using Externalizable, add more responsibility to programmer but often result in better performance.| |It\'s hard to analyze and modify class structure because any change may break the serialization.| It\'s more easy to analyze and modify class structure because of complete control over serialization logic.| |Default serialization does not call any class constructor.|A public no-arg constructor is required while using Externalizable interface. | <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to create marker interface? An interface with no methods is known as marker or tagged interface. It provides some useful information to JVM/compiler so that JVM/compiler performs some special operations on it. It is used for better readability of code. For example Serializable, Clonnable etc. **Syntax:** ```java public interface Interface_Name { } ``` **Example:** ```java /** * Maker Interface */ interface Marker { } class MakerExample implements Marker { // do some task } class Main { public static void main(String[] args) { MakerExample obj = new MakerExample(); if (obj instanceOf Marker) { // do some task } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Can you declare an interface method static? Java 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a Functional Interface? A **functional interface** is an interface that defines only one abstract method. To accurately determine the interface as functional, an annotation has been added `@FunctionalInterface` that works on the principle of `@Override`. It will designate a plan and will not allow to define the second abstract method in the interface. An interface can include as many `default` methods as you like while remaining functional, because `default` methods are not abstract. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are `default` interface methods? Java 8 allows you to add non-abstract method implementations to an interface using the keyword default: ```java interface Example { int process ( int a ); default void show () { System.out.println("default show ()"); } } ``` * If a class implements an interface, it can, but does not have to, implement the default methods already implemented in the * interface. The class inherits the default implementation. * If a class implements several interfaces that have the same default method, then the class must implement the method with the same signature on its own. The situation is similar if one interface has a default method, and in the other the same method is abstract - no class default implementation is inherited. * The default method cannot override the class method `java.lang.Object`. * They help implement interfaces without fear of disrupting other classes. * Avoid creating utility classes, since all the necessary methods can be represented in the interfaces themselves. * They give classes the freedom to choose the method to be redefined. * One of the main reasons for introducing default methods is the ability of collections in Java 8 to use lambda expressions. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to call `default` interface method in a class that implements this interface? Using the keyword superalong with the interface name: ```java interface Paper { default void show () { System.out.println(" default show ()"); } } class License implements Paper { public void show () { Paper.super.show(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is `static` interface method? Static interface methods are similar to default methods, except that there is no way to override them in classes that implement the interface. * Static methods in the interface are part of the interface without the ability to use them for objects of the implementation class * Class methods `java.lang.Object`cannot be overridden as static * Static methods in the interface are used to provide helper methods, for example, checking for null, sorting collections, etc. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to call `static` interface method? Using the interface name: ```java interface Paper { static void show () { System.out.println( " static show () " ); } } class License { public void showPaper () { Paper.show (); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `Function<T,R>`, `DoubleFunction<R>`, `IntFunction<R>` and `LongFunction<R>`? `Function<T, R>`- the interface with which a function is implemented that receives an instance of the class `T` and returns an instance of the class at the output `R`. Default methods can be used to build call chains ( `compose`, `andThen`). ```java Function < String , Integer > toInteger = Integer :: valueOf; Function < String , String > backToString = toInteger.andThen ( String :: valueOf); backToString.apply("123"); // "123" ``` * `DoubleFunction<R>`- a function that receives input `Double` and returns an instance of the class at the output `R`; * `IntFunction<R>`- a function that receives input `Integer`and returns an instance of the class at the output `R`; * `LongFunction<R>`- a function that receives input `Long`and returns an instance of the class at the output `R`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `UnaryOperator<T>`, `DoubleUnaryOperator`, `IntUnaryOperator`and `LongUnaryOperator`? `UnaryOperator<T>`(**unary operator**) takes an object of type as a parameter `T`, performs operations on them and returns the result of operations in the form of an object of type `T`: ```java UnaryOperator < Integer > operator = x - > x * x; System.out.println(operator.apply ( 5 )); // 25 ``` * `DoubleUnaryOperator`- unary operator receiving input `Double`; * `IntUnaryOperator`- unary operator receiving input `Integer`; * `LongUnaryOperator`- unary operator receiving input `Long`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `BinaryOperator<T>`, `DoubleBinaryOperator`, `IntBinaryOperator`and `LongBinaryOperator`? `BinaryOperator<T>`(**binary operator**) - an interface through which a function is implemented that receives two instances of the class `T`and returns an instance of the class at the output `T`. ```java BinaryOperator < Integer > operator = (a, b) -> a + b; System.out.println(operator.apply ( 1 , 2 )); // 3 ``` * `DoubleBinaryOperator`- binary operator receiving input Double; * `IntBinaryOperator`- binary operator receiving input Integer; * `LongBinaryOperator`- binary operator receiving input Long. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `Predicate<T>`, `DoublePredicate`, `IntPredicateand` `LongPredicate`? `Predicate<T>`(**predicate**) - the interface with which a function is implemented that receives an instance of the class as input `T`and returns the type value at the output `boolean`. The interface contains a variety of methods by default, allow to build complex conditions ( `and`, `or`, `negate`). ```java Predicate < String > predicate = (s) -> s.length () > 0 ; predicate.test("foo"); // true predicate.negate().test("foo"); // false ``` * `DoublePredicate`- predicate receiving input `Double`; * `IntPredicate`- predicate receiving input `Integer`; * `LongPredicate`- predicate receiving input `Long`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `Consumer<T>`, `DoubleConsumer`, `IntConsumer`and `LongConsumer`? `Consumer<T>`(**consumer**) - the interface through which a function is implemented that receives an instance of the class as an input `T`, performs some action with it, and returns nothing. ```java Consumer<String> hello = (name) -> System.out.println( " Hello, " + name); hello.accept( " world " ); ``` * `DoubleConsumer`- the consumer receiving the input `Double`; * `IntConsumer`- the consumer receiving the input `Integer`; * `LongConsumer`- the consumer receiving the input `Long`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the functional interfaces `Supplier<T>`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier`and `LongSupplier`? `Supplier<T>`(**provider**) - the interface through which a function is implemented that takes nothing to the input, but returns the result of the class to the output `T`; ```java Supplier < LocalDateTime > now = LocalDateTime::now; now.get(); ``` * `DoubleSupplier`- the supplier is returning `Double`; * `IntSupplier`- the supplier is returning `Integer`; * `LongSupplier`- the supplier is returning `Long`. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> #### Q. What is Spliterator in Java SE 8? #### Q. What is Type Inference in Java 8? #### Q. What is difference between External Iteration and Internal Iteration? *ToDo* <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 21. JAVA ENCAPSULATION <br/> ## Q. How Encapsulation concept implemented in JAVA? Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as `data hiding`. To achieve encapsulation in Java − * Declare the variables of a class as private. * Provide public setter and getter methods to modify and view the variables values. **Example:** ```java public class EncapClass { private String name; public String getName() { return name; } public void setName(String newName) { name = newName; } } public class MainClass { public static void main(String args[]) { EncapClass obj = new EncapClass(); obj.setName("Pradeep Kumar"); System.out.print("Name : " + obj.getName()); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 22. JAVA GENERICS <br/> ## Q. Do you know Generics? How did you used in your coding? `Generics` allows type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. **Advantages:** * **Type-safety**: We can hold only a single type of objects in generics. It doesn\'t allow to store other objects. * **Type Casting**: There is no need to typecast the object. * **Compile-Time Checking**: It is checked at compile time so problem will not occur at runtime. **Example:** ```java /** * A Simple Java program to show multiple * type parameters in Java Generics * * We use < > to specify Parameter type * **/ class GenericClass<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor GenericClass(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } // To print objects of T and U public void print() { System.out.println(obj1); System.out.println(obj2); } } // Driver class to test above class MainClass { public static void main (String[] args) { GenericClass <String, Integer> obj = new GenericClass<String, Integer>("Generic Class Example !", 100); obj.print(); } } ``` Output: ```java Generic Class Example ! 100 ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## # 23. MISCELLANEOUS <br/> ## Q. How will you invoke any external process in Java? In java, external process can be invoked using **exec()** method of **Runtime Class**. **Example:** ```java /** * exec() */ import java.io.IOException; class ExternalProcessExample { public static void main(String[] args) { try { // Command to create an external process String command = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; // Running the above command Runtime run = Runtime.getRuntime(); Process proc = run.exec(command); } catch (IOException e) { e.printStackTrace(); } } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the static import? The static import feature of Java 5 facilitate the java programmer to access any static member of a class directly. There is no need to qualify it by the class name. ```java /** * Static Import */ import static java.lang.System.*; class StaticImportExample { public static void main(String args[]) { out.println("Hello");// Now no need of System.out out.println("Java"); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is the difference between factory and abstract factory pattern? The Factory Method is usually categorised by a switch statement where each case returns a different class, using the same root interface so that the calling code never needs to make decisions about the implementation. **Example:** credit card validator factory which returns a different validator for each card type. ```java /** * Abstract Factory Pattern */ public ICardValidator GetCardValidator (string cardType) { switch (cardType.ToLower()) { case "visa": return new VisaCardValidator(); case "mastercard": case "ecmc": return new MastercardValidator(); default: throw new CreditCardTypeException("Do not recognise this type"); } } ``` Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the methods used to implement for key Object in HashMap? **1. equals()** and **2. hashcode()** Class inherits methods from the following classes in terms of HashMap * java.util.AbstractMap * java.util.Object * java.util.Map <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is a Memory Leak? The standard definition of a memory leak is a scenario that occurs when **objects are no longer being used by the application, but the Garbage Collector is unable to remove them from working memory** – because they\'re still being referenced. As a result, the application consumes more and more resources – which eventually leads to a fatal OutOfMemoryError. Some tools that do memory management to identifies useless objects or memeory leaks like: * <a href="https://support.hpe.com/hpsc/doc/public/display?docId=emr_na-c00990822&docLocale=en_US">HP OpenView</a> * <a href="https://h20392.www2.hpe.com/portal/swdepot/displayProductInfo.do?productNumber=HPJMETER">HP JMETER</a> * <a href="http://www.javaperformancetuning.com/tools/jprobe/index.shtml">JProbe</a> * <a href="https://www.ibm.com/support/knowledgecenter/en/SSTFXA_6.3.0/com.ibm.itm.doc_6.3/install/itm_over.htm">IBM Tivoli</a> **Example:** ```java /** * Memory Leaks */ import java.util.Vector; public class MemoryLeaksExample { public static void main(String[] args) { Vector v = new Vector(214444); Vector v1 = new Vector(214744444); Vector v2 = new Vector(214444); System.out.println("Memory Leaks Example"); } } ``` Output ```java Exception in thread "main" java.lang.OutOfMemoryError: Java heap space exceed ``` **Types of Memory Leaks in Java:** * Memory Leak through static Fields * Unclosed Resources/connections * Adding Objects With no `hashCode()` and `equals()` Into a HashSet * Inner Classes that Reference Outer Classes * Through `finalize()` Methods * Calling `String.intern()` on Long String <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. The difference between Serial and Parallel Garbage Collector? **1. Serial Garbage Collector:** Serial garbage collector works by holding all the application threads. It is designed for the single-threaded environments. It uses just a single thread for garbage collection. The way it works by freezing all the application threads while doing garbage collection may not be suitable for a server environment. It is best suited for simple command-line programs. Turn on the `-XX:+UseSerialGC` JVM argument to use the serial garbage collector. **2. Parallel Garbage Collector:** Parallel garbage collector is also called as throughput collector. It is the default garbage collector of the JVM. Unlike serial garbage collector, this uses multiple threads for garbage collection. Similar to serial garbage collector this also freezes all the application threads while performing garbage collection. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is difference between WeakReference and SoftReference in Java? **1. Weak References:** Weak Reference Objects are not the default type/class of Reference Object and they should be explicitly specified while using them. ```java /** * Weak Reference */ import java.lang.ref.WeakReference; class MainClass { public void message() { System.out.println("Weak References Example"); } } public class Example { public static void main(String[] args) { // Strong Reference MainClass g = new MainClass(); g.message(); // Creating Weak Reference to MainClass-type object to which 'g' // is also pointing. WeakReference<MainClass> weakref = new WeakReference<MainClass>(g); g = null; g = weakref.get(); g.message(); } } ``` **2. Soft References:** In Soft reference, even if the object is free for garbage collection then also its not garbage collected, until JVM is in need of memory badly.The objects gets cleared from the memory when JVM runs out of memory.To create such references java.lang.ref.SoftReference class is used. ```java /** * Soft Reference */ import java.lang.ref.SoftReference; class MainClass { public void message() { System.out.println("Soft References Example"); } } public class Example { public static void main(String[] args) { // Strong Reference MainClass g = new MainClass(); g.message(); // Creating Soft Reference to MainClass-type object to which 'g' // is also pointing. SoftReference<MainClass> softref = new SoftReference<MainClass>(g); g = null; g = softref.get(); g.message(); } } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How Garbage collector algorithm works? Garbage collection works on **Mark** and **Sweep** algorithm. In Mark phase it detects all the unreachable objects and Sweep phase it reclaim the heap space used by the garbage objects and make the space available again to the program. There are methods like `System.gc()` and `Runtime.gc()` which is used to send request of Garbage collection to JVM but it\'s not guaranteed that garbage collection will happen. If there is no memory space for creating a new object in Heap Java Virtual Machine throws `OutOfMemoryError` or `java.lang.OutOfMemoryError` heap space <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. Java Program to Implement Singly Linked List? The singly linked list is a linear data structure in which each element of the list contains a pointer which points to the next element in the list. Each element in the singly linked list is called a node. Each node has two components: data and a pointer next which points to the next node in the list. **Example:** ```java public class SinglyLinkedList { // Represent a node of the singly linked list class Node{ int data; Node next; public Node(int data) { this.data = data; this.next = null; } } // Represent the head and tail of the singly linked list public Node head = null; public Node tail = null; // addNode() will add a new node to the list public void addNode(int data) { // Create a new node Node newNode = new Node(data); // Checks if the list is empty if(head == null) { // If list is empty, both head and tail will point to new node head = newNode; tail = newNode; } else { // newNode will be added after tail such that tail's next will point to newNode tail.next = newNode; // newNode will become new tail of the list tail = newNode; } } // display() will display all the nodes present in the list public void display() { // Node current will point to head Node current = head; if(head == null) { System.out.println("List is empty"); return; } System.out.println("Nodes of singly linked list: "); while(current != null) { // Prints each node by incrementing pointer System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { SinglyLinkedList sList = new SinglyLinkedList(); // Add nodes to the list sList.addNode(10); sList.addNode(20); sList.addNode(30); sList.addNode(40); // Displays the nodes present in the list sList.display(); } } ``` **Output:** ```java Nodes of singly linked list: 10 20 30 40 ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What do we mean by weak reference? A weakly referenced object is cleared by the Garbage Collector when it\'s weakly reachable. Weak reachability means that an object has neither strong nor soft references pointing to it. The object can be reached only by traversing a weak reference. To create such references `java.lang.ref.WeakReference` class is used. ```java /** * Weak reference */ import java.lang.ref.WeakReference; class WeakReferenceExample { public void message() { System.out.println("Weak Reference Example!"); } } public class MainClass { public static void main(String[] args) { // Strong Reference WeakReferenceExample obj = new WeakReferenceExample(); obj.message(); // Creating Weak Reference to WeakReferenceExample-type object to which 'obj' // is also pointing. WeakReference<WeakReferenceExample> weakref = new WeakReference<WeakReferenceExample>(obj); obj = null; // is available for garbage collection. obj = weakref.get(); obj.message(); } } ``` Output ```java Weak Reference Example! Weak Reference Example! ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What are the different types of JDBC Driver? JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers: 1. **JDBC-ODBC bridge driver**: The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver. 1. **Native-API driver**: The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. 1. **Network Protocol driver**: The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. 1. **Thin driver**: The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What additional methods for working with associative arrays (maps) appeared in Java 8? * `putIfAbsent()` adds a key-value pair only if the key was missing: ```java map.putIfAbsent("a", "Aa"); ``` * `forEach()` accepts a function that performs an operation on each element: ```java map.forEach((k, v) -> System.out.println(v)); ``` * `compute()` creates or updates the current value to the result of the calculation (it is possible to use the key and the current value): ```java map.compute("a", (k, v) -> String.valueOf(k).concat(v)); //["a", "aAa"] ``` * `computeIfPresent()` if the key exists, updates the current value to the result of the calculation (it is possible to use the key and the current value): ```java map.computeIfPresent("a", (k, v) -> k.concat(v)); ``` * `computeIfAbsent()` if the key is missing, creates it with the value that is calculated (it is possible to use the key): ```java map.computeIfAbsent("a", k -> "A".concat(k)); //["a","Aa"] ``` * `getOrDefault()` if there is no key, returns the passed value by default: ```java map.getOrDefault("a", "not found"); ``` * `merge()` accepts a key, a value, and a function that combines the transmitted and current values. If there is no value under the specified key, then it writes the transmitted value there. ```java map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"] ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is LocalDateTime? `LocalDateTime`combines together `LocaleDate`and `LocalTime`contains the date and time in the calendar system ISO-8601 without reference to the time zone. Time is stored accurate to the nanosecond. It contains many convenient methods such as plusMinutes, plusHours, isAfter, toSecondOfDay, etc. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What is ZonedDateTime? `java.time.ZonedDateTime`- an analogue `java.util.Calendar`, a class with the most complete amount of information about the temporary context in the calendar system ISO-8601. It includes a time zone, therefore, this class carries out all operations with time shifts taking into account it. <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to determine repeatable annotation? To define a repeatable annotation, you must create a container annotation for the list of repeatable annotations and designate a repeatable meta annotation `@Repeatable`: ```java @interface Schedulers { Scheduler [] value (); } @Repeatable ( Schedulers . Class) @interface Scheduler { String birthday () default "Jan 8 2000"; } ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. What class appeared in Java 8 for encoding / decoding data? `Base64`- a thread-safe class that implements a data encoder and decoder using a base64 encoding scheme according to RFC 4648 and RFC 2045 . Base64 contains 6 basic methods: `getEncoder() / getDecoder()`- returns a base64 encoder / decoder conforming to the RFC 4648 standard ; getUrlEncoder()/ `getUrlDecoder()`- returns URL-safe base64 encoder / decoder conforming to RFC 4648 standard ; `getMimeEncoder() / getMimeDecoder()`- returns a MIME encoder / decoder conforming to RFC 2045 . <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> ## Q. How to create a Base64 encoder and decoder? ```java // Encode String b64 = Base64.getEncoder().encodeToString ( " input " . getBytes ( " utf-8 " )); // aW5wdXQ == // Decode new String ( Base64.getDecoder().decode ( " aW5wdXQ == " ), " utf-8 " ); // input ``` <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div> #### Q. Give me an example of design pattern which is based upon open closed principle? #### Q. How do you test static method? #### Q. How to do you test a method for an exception using JUnit? #### Q. Which unit testing libraries you have used for testing Java programs? #### Q. What is the difference between @Before and @BeforeClass annotation? <div align="right"> <b><a href="#related-topics">↥ back to top</a></b> </div>
0
AxonFramework/AxonFramework
Framework for Evolutionary Message-Driven Microservices on the JVM
2011-12-02T16:04:42Z
null
# Axon Framework [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.axonframework/axon/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.axonframework/axon) ![Build Status](https://github.com/AxonFramework/AxonFramework/workflows/Axon%20Framework/badge.svg?branch=master) [![SonarCloud Status](https://sonarcloud.io/api/project_badges/measure?project=AxonFramework_AxonFramework&metric=alert_status)](https://sonarcloud.io/dashboard?id=AxonFramework_AxonFramework) [Axon Framework](https://developer.axoniq.io/axon-framework/overview) is a framework for building evolutionary, event-driven microservice systems based on the principles of Domain-Driven Design (DDD), Command-Query Responsibility Separation (CQRS), and Event Sourcing. Axon Framework provides you with the necessary building blocks to follow these principles. Examples of building blocks are aggregate design handles, aggregate repositories, command buses, saga design handles, event stores, query buses, and more. The framework provides sensible defaults for all of these components out of the box. The messaging support for commands, events, and queries is at the core of these building blocks. It is the messaging basics that enable an evolutionary approach towards microservices through the [location transparency](https://en.wikipedia.org/wiki/Location_transparency) they provide. Axon will also assist in distributing applications to support scalability or fault tolerance, for example. The most accessible and quick road forward would be to use [Axon Server](https://developer.axoniq.io/axon-server/overview) to seamlessly adjust message buses to distributed implementations. Axon Server provides a distributed command bus, event bus, query bus, and an efficient event store implementation for scalable event sourcing. Additionally, the [Axon Framework organization](https://github.com/AxonFramework) has several extensions that can help in this space. All this helps to create a well-structured application without worrying about the infrastructure. Hence, your focus can shift from non-functional requirements to your business functionality. For more information on anything Axon, please visit our website, [http://axoniq.io](http://axoniq.io). ## Getting started Numerous resources can help you on your journey in using Axon Framework. A good starting point is [AxonIQ Developer Portal](https://developer.axoniq.io/), which provides links to resources like blogs, videos, and descriptions. Furthermore, below are several other helpful resources: * The [quickstart page](https://docs.axoniq.io/reference-guide/getting-started/quick-start) of the documentation provides a simplified entry point into the framework with the [quickstart project](https://download.axoniq.io/quickstart/AxonQuickStart.zip). * We have our very own [academy](https://academy.axoniq.io/)! The introductory courses are free, followed by more in-depth (paid) courses. * When ready, you can quickly and easily start your very own Axon Framework based application at https://start.axoniq.io/. Note that this solution is only feasible if you want to stick to the Spring ecosphere. * The [reference guide](https://docs.axoniq.io) explains all of the components maintained within Axon Framework's products. * If the guide doesn't help, our [forum](https://discuss.axoniq.io/) provides a place to ask questions you have during development. * The [hotel demo](https://github.com/AxonIQ/hotel-demo) shows a fleshed-out example of using Axon Framework. * The [code samples repository](https://github.com/AxonIQ/code-samples) contains more in-depth samples you can benefit from. ## Receiving help Are you having trouble using any of our libraries or products? Know that we want to help you out the best we can! There are a couple of things to consider when you're traversing anything Axon: * Checking the [reference guide](https://docs.axoniq.io) should be your first stop. * When the reference guide does not cover your predicament, we would greatly appreciate it if you could file an [issue](https://github.com/AxonIQ/reference-guide/issues) for it. * Our [forum](https://discuss.axoniq.io/) provides a space to communicate with the Axon community to help you out. AxonIQ developers will help you out on a best-effort basis. And if you know how to help someone else, we greatly appreciate your contributions! * We also monitor Stack Overflow for any question tagged with [**axon**](https://stackoverflow.com/questions/tagged/axon). Similarly to the forum, AxonIQ developers help out on a best-effort basis. ## Feature requests and issue reporting We use GitHub's [issue tracking system](https://github.com/AxonFramework/AxonFramework/issues)) for new feature requests, framework enhancements, and bugs. Before filing an issue, please verify that it's not already reported by someone else. Furthermore, make sure you are adding the issue to the correct repository! When filing bugs: * A description of your setup and what's happening helps us figure out what the issue might be. * Do not forget to provide the versions of the Axon products you're using, as well as the language and version. * If possible, share a stack trace. Please use Markdown semantics by starting and ending the trace with three backticks (```). When filing a feature or enhancement: * Please provide a description of the feature or enhancement at hand. Adding why you think this would be beneficial is also a great help to us. * (Pseudo-)Code snippets showing what it might look like will help us understand your suggestion better. Similarly as with bugs, please use Markdown semantics for code snippets, starting and ending with three backticks (```). * If you have any thoughts on where to plug this into the framework, that would be very helpful too. * Lastly, we value contributions to the framework highly. So please provide a Pull Request as well!
0
vaadin/framework
Vaadin 6, 7, 8 is a Java framework for modern Java web applications.
2012-10-19T10:41:30Z
null
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/vaadin/framework-8?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) # Vaadin Framework *[Vaadin](https://vaadin.com) allows you to build modern web apps efficiently in plain Java, without touching low level web technologies.* This repository serves as an archive of the source code and issue tracking for Vaadin 8 and Vaadin 7. Both use GWT as the base of client-side implementations. Vaadin 8 includes Vaadin 7 compatibility classes. You can find source code and issue tracking for newer, web component based Vaadin versions in [vaadin/platform](https://github.com/vaadin/platform). The code in this repository reflects the state of Vaadin 8.14.3 and Vaadin 7.7.17, the last releases made available under the Apache-2 license, and will be left as-is. ## NOTICE Starting with versions 7.7.30\* and 8.15.0, no new code is being released here, as development now happens in a private repository. However, releases are being published as courtesy notifications to the users who have subscribed to the release feed of this repository. The source code attached to Github releases in this repository reflects the state of code ***in this respository*** at time of release. It is ***NOT*** the source code of the corresponding Extended Maintenance release. \* Note: 7.7.17 is the last Apache-2 licensed version, however in the beginning of the transition phase extended maintenance version changes to the 7.7 branch were being made here. In order to be in compliance with the license terms, you are only allowed to use 7.7 code up to [release 7.7.17](https://github.com/vaadin/framework/releases/tag/7.7.17). ## Vaadin Framework has entered extended maintenance Vaadin Framework 7 and 8 are now being maintained under a closed-source model by the Vaadin Expertise Team. You are free to continue using Vaadin Framework releases up to [8.14.3](https://github.com/vaadin/framework/releases/tag/8.14.3) and [7.7.17](https://github.com/vaadin/framework/releases/tag/7.7.17) as made available through this repository, and you are free to fork and maintain the framework yourself. * Vaadin 8 open source maintenance ended in February 2022, [extended support](https://vaadin.com/vaadin-8-extended-maintenance) is available until February 2032. Starting with version 8.15.0, Vaadin 8 is subject to commercial Vaadin licenses (CVDLv4 from 8.15.0 onward, VCL-1 from 8.19.0 onward, and VCL-2 starting with 8.21.0). The current license is [Vaadin Commercial License, version 2](https://vaadin.com/commercial-license-and-service-terms). * Vaadin 7 open source maintenance ended in Febraury 2019, [extended support](https://vaadin.com/support/vaadin-7-extended-maintenance) is available until February 2029. Starting with version 7.7.18, Vaadin 7 is subject to commercial Vaadin licenses (CVDLv4 from 7.7.18 onward, VCL-1 from 7.7.37 onward, and VCL-2 starting with 7.7.41). The current license is [Vaadin Commercial License, version 2](https://vaadin.com/commercial-license-and-service-terms). Extended Maintenance versions of Vaadin Framework are being made available through Maven Central. In order to get access to extended maintenance Framework source code, [contact sales](https://pages.vaadin.com/contact). ## Changelog For a changelog of Vaadin 8 starting with 8.15.0, see the [Vaadin 8 Changelog](CHANGELOG-VAADIN8.md). For a changelog of Vaadin 7 starting with 7.7.30, see the [Vaadin 7 Changelog](CHANGELOG-VAADIN7.md). ## Using Vaadin 8 to develop applications Please refer to [Vaadin tutorial](https://vaadin.com/docs/v8/framework/tutorial.html) and other [documentation](https://vaadin.com/docs/v8/index.html). For known issues within Vaadin framework, see [Issue Tracker](https://github.com/vaadin/framework/issues). Comment or react to an existing issue to mark your interest in resolving it. If you don't find an existing report of an issue you are experiencing, [submit a new issue](https://github.com/vaadin/framework/issues/new/choose). ## Developing Vaadin Framework For instructions on how to set up a working environment for developing the Vaadin framework, please visit [Development Instructions](README-DEV.md). Pay special attention to workspace preferences. ## Contributing As of February 2022, this repository is used for issue tracking. Since we are no longer building releases from this repository, we are no longer accepting pull requests. You may file bug reports here against extended maintenance releases.
0
Audiveris/audiveris
Latest generation of Audiveris OMR engine
2016-09-07T13:31:03Z
null
![](https://github.com/Audiveris/docs/blob/master/images/SplashLogo.png) Logo by [Katka](https://www.facebook.com/katkastreetart/) # Audiveris - Open-source Optical Music Recognition The goal of an OMR application is to allow the end-user to transcribe a score image into its symbolic counterpart. This opens the door to its further use by many kinds of digital processing such as playback, music edition, searching, republishing, etc. The Audiveris application is built around the tight integration of two main components: an OMR engine and an OMR editor. - The OMR engine combines many techniques, depending on the type of entities to be recognized -- *ad-hoc* methods for lines, image morphological closing for beams, external OCR for texts, template matching for heads, neural network for all other fixed-size shapes. Significant progresses have been made, especially regarding poor-quality scores, but experience tells us that a 100% recognition ratio is simply out of reach in many cases. - The OMR editor thus comes into play to overcome engine weaknesses in convenient ways. The user can preselect processing switches to adapt the OMR engine before launching the transcription of the current score. Then the remaining mistakes can generally be quickly fixed via the manual editing of a few music symbols. ## Key characteristics * Good recognition efficiency on real-world quality scores (as those seen on [IMSLP][imslp] site) * Effective support for large scores (with up to hundreds of pages) * Convenient user-oriented interface to detect and correct most OMR errors * Available on Windows, Linux and MacOS * Open source The core of engine music information (OMR data) is fully documented and made publicly available, either directly via XML-based `.omr` project files or via the Java API of this software. Audiveris comes with an integrated exporter to write (a subset of) this OMR data into [MusicXML][musicxml] 4.0 format. In the future, other exporters are expected to build upon OMR data to support other target formats. ## Stable releases On a rather regular basis, typically every 6 to 12 months, a new release is made available on the dedicated [Audiveris Releases][releases] page. The goal of a release is to provide significant improvements, well tested and integrated, resulting in a software as easy as possible to install and use: - for **Windows**, an installer is provided on [Github][releases]; The installer comes with pre-installed Tesseract OCR languages ``deu``, ``eng``, ``fra`` and ``ita``. But **it requires Java version 17** or higher to be available in your environment. If no suitable Java version is found at runtime, a prompt will ask you install it. - for **Linux**, a flatpak package is provided on [Flathub](https://flathub.org/apps/org.audiveris.audiveris); The package comes with pre-installed Tesseract OCR languages ``deu``, ``eng``, ``fra`` and ``ita``. The needed Java environment is included in its packaging, therefore no Java installation is needed. - for **MacOS**, unfortunately, we have nothing similar yet [^macos] -- for now, you have to build from sources as described in the following section on [Development versions](#development-versions). See details in the related [handbook section][installation]. ## Development versions The Audiveris project is developed on GitHub, the site you are reading. Any one can download, build and run this software. The needed tools are ``git``, ``gradle`` and a Java Development Kit (``jdk``), as described in this [handbook section][sources]. There are two main branches in Audiveris project: - the ``master`` branch is GitHub default branch; we use it for releases, and only for them; To build from this branch, you will need a ``jdk`` for Java version **17** or higher. - the ``development`` branch is the one where all developments continuously take place; Periodically, when a release is to be made, we merge the development branch into the master branch; As of this writing, the source code on development branch requires a ``jdk`` for Java version **21**. See details in the [Wiki article][workflow] dedicated to the chosen development workflow. ## Further Information Users and Developers are advised to read Audiveris [User Handbook][handbook], and the more general [Wiki][audiveris-wiki] set of articles. [^macos]: If you wish to give a hand, you are more than welcome! [audiveris-wiki]: https://github.com/Audiveris/audiveris/wiki [handbook]: https://audiveris.github.io/audiveris/ [imslp]: https://imslp.org/ [installation]: https://audiveris.github.io/audiveris/_pages/install/README/ [musicxml]: http://www.musicxml.com/ [releases]: https://github.com/Audiveris/audiveris/releases [sources]: https://audiveris.github.io/audiveris/_pages/install/sources/ [workflow]: https://github.com/Audiveris/audiveris/wiki/Git-Workflow
0
tvbarthel/BlurDialogFragment
Library project to display DialogFragment with a blur effect.
2014-08-09T17:15:04Z
null
BlurDialogFragment ================== This project allows to display DialogFragment with a burring effect behind. The blurring part is achieved through FastBlur algorithm thanks to the impressive work of Pavlo Dudka (cf [Special Thanks](https://github.com/tvbarthel/BlurDialogFragment/#special-thanks-to-)). [![Maven Central](http://img.shields.io/maven-central/v/fr.tvbarthel.blurdialogfragment/lib.svg)](http://search.maven.org/#search%7Cga%7C1%7Cblurdialogfragment) [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-BlurDialogFragment-brightgreen.svg?style=flat)](https://android-arsenal.com/details/1/1064) * [Sample app](#sample-app) * [Gradle dependency](#gradle-dependency) * [Example](#example) * [Use RenderScript in Your Project] (#use-renderscript-in-your-project) * [Simple usage using inheritance](#simple-usage-using-inheritance) * [Customize your blurring effect](#customize-your-blurring-effect) * [Avoiding inheritance](#avoiding-inheritance) * [Benchmark](#benchmark) * [Known bugs](#known-bugs) * [RenderScript or not RenderScript](#renderscript-or-not-renderscript) * [Change logs](#change-logs) * [Contributing](#contributing) * [Credits](#credits) * [License](#license) * [Special Thanks](#special-thanks-to-) Sample app ======= [Download the sample app on the Google Play store.](https://play.google.com/store/apps/details?id=fr.tvbarthel.lib.blurdialogfragment.sample) Gradle dependency ======= Since the library is promoted on maven central, just add a new gradle dependency : ```groovy compile 'fr.tvbarthel.blurdialogfragment:lib:2.2.0' ``` Don't forget to check the [Use RenderScript in Your Project] (#use-renderscript-in-your-project) if you're planning to use it. Example ======= Activity with action bar [blurRadius 4, downScaleFactor 5.0] : ![action bar blur](/static/action_bar_blur.png) Fullscreen activity [blurRadius 2, downScaleFactor 8.0] : ![full screen blur](/static/full_screen_blur.png) Use RenderScript in Your Project ====== Simply add this line to your build.gradle ```groovy defaultConfig { ... renderscriptTargetApi 22 renderscriptSupportModeEnabled true ... } ``` Simple usage using inheritance ======= If you are using **android.app.DialogFragment** : extends **BlurDialogFragment**. Play with the blur radius and the down scale factor to obtain the perfect blur. Don't forget to enable log if you want to keep on eye the performance. ```java /** * Simple fragment with blurring effect behind. */ public class SampleDialogFragment extends BlurDialogFragment { } ``` If you are using **android.support.v4.app.DialogFragment** : extends **SupportBlurDialogFragment**. Play with the blur radius and the down scale factor to obtain the perfect blur. Don't forget to enable log in order to keep on eye the performance. ```java /** * Simple fragment with blurring effect behind. */ public class SampleDialogFragment extends SupportBlurDialogFragment { } ``` Customize your blurring effect ====== ```java /** * Simple fragment with a customized blurring effect. */ public class SampleDialogFragment extends BlurDialogFragment { @Override public void onCreate(Bundle savedInstanceState) { ... } @Override protected float getDownScaleFactor() { // Allow to customize the down scale factor. return 5.0; } @Override protected int getBlurRadius() { // Allow to customize the blur radius factor. return 7; } @Override protected boolean isActionBarBlurred() { // Enable or disable the blur effect on the action bar. // Disabled by default. return true; } @Override protected boolean isDimmingEnable() { // Enable or disable the dimming effect. // Disabled by default. return true; } @Override protected boolean isRenderScriptEnable() { // Enable or disable the use of RenderScript for blurring effect // Disabled by default. return true; } @Override protected boolean isDebugEnable() { // Enable or disable debug mode. // False by default. return true; } ... ``` Default values are set to : ```java /** * Since image is going to be blurred, we don't care about resolution. * Down scale factor to reduce blurring time and memory allocation. */ static final float DEFAULT_BLUR_DOWN_SCALE_FACTOR = 4.0f; /** * Radius used to blur the background */ static final int DEFAULT_BLUR_RADIUS = 8; /** * Default dimming policy. */ static final boolean DEFAULT_DIMMING_POLICY = false; /** * Default debug policy. */ static final boolean DEFAULT_DEBUG_POLICY = false; /** * Default action bar blurred policy. */ static final boolean DEFAULT_ACTION_BAR_BLUR = false; /** * Default use of RenderScript. */ static final boolean DEFAULT_USE_RENDERSCRIPT = false; ``` Avoiding inheritance ======= If you want to **avoid inheritance**, use directly the **BlurEngine**. Don't forget to link the engine to the lifecycle of your DialogFragment. ```java /** * Your blur fragment directly using BlurEngine. */ public class SampleDialogFragment extends MyCustomDialogFragment { /** * Engine used to blur. */ private BlurDialogEngine mBlurEngine; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBlurEngine = new BlurDialogEngine(getActivity()); mBlurEngine.setBlurRadius(8); mBlurEngine.setDownScaleFactor(8f); mBlurEngine.debug(true); mBlurEngine.setBlurActionBar(true); mBlurEngine.setUseRenderScript(true); } @Override public void onResume() { super.onResume(); mBlurEngine.onResume(getRetainInstance()); } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); mBlurEngine.onDismiss(); } @Override public void onDestroy() { super.onDestroy(); mBlurEngine.onDetach(); } @Override public void onDestroyView() { if (getDialog() != null) { getDialog().setDismissMessage(null); } super.onDestroyView(); } ... } ``` Benchmark ======= # Benchmark outdated. Please refer to the debug option of the sample in order to compare FastBlur and RenderScript. We used a Nexus 5 running a 4.4.4 stock rom for this bench. Down scale factor 8.0 & Blur Radius 8 : [Screenshot](/static/blur_8.0_8.png) ```javascript Radius : 8 Down Scale Factor : 8.0 Blurred achieved in : 18 ms Allocation : 4320ko (screen capture) + 270ko (FastBlur) ``` Down scale factor 6.0 & Blur Radius 12 : [Screenshot](/static/blur_6.0_12.png) ```javascript Radius : 12 Down Scale Factor : 6.0 Blurred achieved in : 31 ms Allocation : 4320ko (screen capture) + 360ko (FastBlur) ``` Down scale factor 4.0 & Blur Radius 20 : [Screenshot](/static/blur_4.0_20.png) ```javascript Radius : 20 Down Scale Factor : 4.0 Blurred achieved in : 75 ms Allocation : 4320ko (screen capture) + 540ko (FastBlur) ``` Known bugs ======= * Wrong top offset when using the following line in application Theme : ```xml <item name="android:windowActionBarOverlay">true</item> ``` RenderScript or not RenderScript ======= Thanks to [amasciul](https://github.com/amasciul) blurring effect can now be achieved using ScriptIntrinsicBlur (v1.1.0). Find more information on the [memory trace](http://tvbarthel.github.io/blur-dialog-fragment.html) and on the [execution time](http://trickyandroid.com/advanced-blurring-techniques/#comment-1557039595). Change logs ======= * 2.2.0 : Fix preDrawListener registration when there was no certitude that onPreDraw will be called thanks to [Serkan Modoğlu](https://github.com/sekomod) and [Mark Mooibroek](https://github.com/markmooibroek) reports. * 2.1.6 : Fix orientation change as well as retainInstance thanks to [IskuhiSargsyan](https://github.com/IskuhiSargsyan) report and tweak FastBlur implementation to avoid the allocation of 3 additional arrays for RGB channels thanks to [sh1](https://disqus.com/by/sh1sh1sh1/) feedback. * 2.1.5 : Minor fixes thanks to [Edward S](https://github.com/edward-s) and [Tommy Chan](https://github.com/tommytcchan). * 2.1.4 : Fix NPE during the blurring process thanks to [Anth06ny](https://github.com/Anth06ny), [jacobtabak](https://github.com/jacobtabak) and [serega2593](https://github.com/serega2593) reports. * 2.1.3 : Remove unused resources thanks to [ligol](https://github.com/ligol) report. * 2.1.2 : Rework support of translucent status bar thanks to [wangsai-silence](https://github.com/wangsai-silence) report. * 2.1.1 : Fix usage without renderscript as VerifyError was fired. * 2.1.0 : Support AppCompatActivity and fix several bugs thanks to [jacobtabak](https://github.com/jacobtabak). * 2.0.1 : BlurEngine is back again (restore "avoiding inheritance" usage, thanks to [sergiopantoja](https://github.com/sergiopantoja) report). * 2.0.0 : Min SDK 9+, don't forget to check the above section "Use RenderScript in Your Project". (thanks to [ligol](https://github.com/ligol)). * 1.1.0 : Allow to use RenderScript (thank to [amasciul](https://github.com/amasciul)). * 1.0.0 : Animate blurring effect, support tablet, tweak nav bar offset and reduce memory allocation. * 0.1.2 : Fix bottom offset introduce by the navigation bar on Lollipop. * 0.1.1 : Fix top offset when using Toolbar. * 0.1.0 : Support appcompat-v7:21. * 0.0.9 : Change default blur radius (8) and default down scale factor (4). * 0.0.8 : Fix NoClassDefFound. * 0.0.7 : Avoid using inheritance through BlurDialogEngine if needed. Contributing ======= Contributions are welcome (: You can contribute through GitHub by forking the repository and sending a pull request. When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code fit these convention by running gradlew check. Credits ======== Credits go to Thomas Barthélémy [https://github.com/tbarthel-fr](https://github.com/tbarthel-fr) and Vincent Barthélémy [https://github.com/vbarthel-fr](https://github.com/vbarthel-fr). License ===================== ``` Copyright (C) 2014 tvbarthel 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. ``` Special Thanks to ... ======== Pavlo Dudka [https://github.com/paveldudka/](https://github.com/paveldudka/) , for his impressive article on [Advanced blurring techniques](http://trickyandroid.com/advanced-blurring-techniques/). Vincent Brison [https://github.com/vincentbrison](https://github.com/vincentbrison) , for his early day support. Alexandre Masciulli [https://github.com/amasciul](https://github.com/amasciul) , for the integration of RenderScript.
0
Nepxion/Discovery
☀️ Nepxion Discovery is a solution for Spring Cloud with blue green, gray, route, limitation, circuit breaker, degrade, isolation, tracing, dye, failover, active 蓝绿灰度发布、路由、限流、熔断、降级、隔离、追踪、流量染色、故障转移、多活
2018-06-21T16:16:49Z
null
![](http://nepxion.gitee.io/discovery/docs/discovery-doc/Banner.png) # Discovery【探索】云原生微服务解决方案 ![Total visits](https://visitor-badge.laobi.icu/badge?page_id=Nepxion&title=total%20visits) [![Total lines](https://tokei.rs/b1/github/Nepxion/Discovery?category=lines)](https://tokei.rs/b1/github/Nepxion/Discovery?category=lines) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?label=license)](https://github.com/Nepxion/Discovery/blob/6.x.x/LICENSE) [![Maven Central](https://img.shields.io/maven-central/v/com.nepxion/discovery.svg?label=maven)](https://search.maven.org/artifact/com.nepxion/discovery) [![Javadocs](http://www.javadoc.io/badge/com.nepxion/discovery-plugin-framework-starter.svg)](http://www.javadoc.io/doc/com.nepxion/discovery-plugin-framework-starter) [![Build Status](https://github.com/Nepxion/Discovery/workflows/build/badge.svg)](https://github.com/Nepxion/Discovery/actions) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/5c42eb719ef64def9cad773abd877e8b)](https://www.codacy.com/gh/Nepxion/Discovery/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Nepxion/Discovery&amp;utm_campaign=Badge_Grade) [![Stars](https://img.shields.io/github/stars/Nepxion/Discovery.svg?label=Stars&style=flat&logo=GitHub)](https://github.com/Nepxion/Discovery/stargazers) [![Stars](https://gitee.com/Nepxion/Discovery/badge/star.svg?theme=gvp)](https://gitee.com/Nepxion/Discovery/stargazers) <!-- [![Spring Boot](https://img.shields.io/maven-central/v/org.springframework.boot/spring-boot-dependencies.svg?label=Spring%20Boot&logo=Spring)](https://search.maven.org/artifact/org.springframework.boot/spring-boot-dependencies) [![Spring Cloud](https://img.shields.io/maven-central/v/org.springframework.cloud/spring-cloud-dependencies.svg?label=Spring%20Cloud&logo=Spring)](https://search.maven.org/artifact/org.springframework.cloud/spring-cloud-dependencies) [![Spring Cloud Alibaba](https://img.shields.io/maven-central/v/com.alibaba.cloud/spring-cloud-alibaba-dependencies.svg?label=Spring%20Cloud%20Alibaba&logo=Spring)](https://search.maven.org/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies) [![Nepxion Discovery](https://img.shields.io/maven-central/v/com.nepxion/discovery.svg?label=Nepxion%20Discovery&logo=Anaconda)](https://search.maven.org/artifact/com.nepxion/discovery) --> [![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label=GitHub)](https://github.com/Nepxion/Discovery/wiki) [![Wiki](https://badgen.net/badge/icon/wiki?icon=wiki&label=Gitee)](https://gitee.com/nepxion/Discovery/wikis/pages?sort_id=3993615&doc_id=1124387) [![Discovery PPT](https://img.shields.io/badge/Discovery%20-ppt-brightgreen?logo=Microsoft%20PowerPoint)](http://nepxion.gitee.io/discovery/docs/link-doc/discovery-ppt.html) [![Discovery Page](https://img.shields.io/badge/Discovery%20-page-brightgreen?logo=Microsoft%20Edge)](http://nepxion.gitee.io/discovery/) [![Discovery Platform Page](https://img.shields.io/badge/Discovery%20Platform%20-page-brightgreen?logo=Microsoft%20Edge)](http://nepxion.gitee.io/discoveryplatform) [![Polaris Page](https://img.shields.io/badge/Polaris%20-page-brightgreen?logo=Microsoft%20Edge)](http://polaris-paas.gitee.io/polaris-sdk) <a href="https://github.com/Nepxion" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/github.png"></a>&nbsp; <a href="https://gitee.com/Nepxion" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/gitee.png"></a>&nbsp; <a href="https://search.maven.org/search?q=g:com.nepxion" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/maven.png"></a>&nbsp; <a href="http://nepxion.gitee.io/discovery/docs/contact-doc/wechat.jpg" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/wechat.png"></a>&nbsp; <a href="http://nepxion.gitee.io/discovery/docs/contact-doc/dingding.jpg" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/dingding.png"></a>&nbsp; <a href="http://nepxion.gitee.io/discovery/docs/contact-doc/gongzhonghao.jpg" tppabs="#" target="_blank"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/gongzhonghao.png"></a>&nbsp; <a href="mailto:1394997@qq.com" tppabs="#"><img width="25" height="25" src="http://nepxion.gitee.io/discovery/docs/icon-doc/email.png"></a> 如果您觉得本框架具有一定的参考价值和借鉴意义,请帮忙在页面右上角 [**Star**] ## 简介 ### 作者简介 - Nepxion开源社区创始人 - 2020年阿里巴巴中国云原生峰会出品人 - 2020年被Nacos和Spring Cloud Alibaba纳入相关开源项目 - 2021年阿里巴巴技术峰会上海站演讲嘉宾 - 2021年荣获陆奇博士主持的奇绩资本,进行风险投资的关注和调研 - 2021年入选Gitee最有价值开源项目 - 阿里巴巴官方书籍《Nacos架构与原理》作者之一 - Spring Cloud Alibaba Steering Committer、Nacos Group Member - Spring Cloud Alibaba、Nacos、Sentinel、OpenTracing Committer & Contributor <img src="http://nepxion.gitee.io/discovery/docs/discovery-doc/CertificateGVP.jpg" width="43%"><img src="http://nepxion.gitee.io/discovery/docs/discovery-doc/AwardNacos1.jpg" width="28%"><img src="http://nepxion.gitee.io/discovery/docs/discovery-doc/AwardSCA1.jpg" width="28%"> ### 商业合作 ① Discovery系列 | 框架名称 | 框架版本 | 支持Spring Cloud版本 | 使用许可 | | --- | --- | --- | --- | | Discovery | 1.x.x ~ 6.x.x | Camden ~ Hoxton | 开源,永久免费 | | DiscoveryX | 7.x.x ~ 10.x.x | 2020 ~ 2023 | 闭源,商业许可 | ② Polaris系列 Polaris为Discovery高级定制版,特色功能 - 基于Nepxion Discovery集成定制 - 多云、多活、多机房流量调配 - 跨云动态域名、跨环境适配 - DCN、DSU、SET单元化部署 - 组件灵活装配、配置对外屏蔽 - 极简低代码PaaS平台 | 框架名称 | 框架版本 | 支持Discovery版本 | 支持Spring Cloud版本 | 使用许可 | | --- | --- | --- | --- | --- | | Polaris | 1.x.x | 6.x.x | Finchley ~ Hoxton | 闭源,商业许可 | | Polaris | 2.x.x | 7.x.x ~ 10.x.x | 2020 ~ 2023 | 闭源,商业许可 | 有商业版需求的企业和用户,请添加微信1394997,联系作者,洽谈合作事宜 ### 入门资料 ![](http://nepxion.gitee.io/discovery/docs/discovery-doc/Logo64.png) Discovery【探索】企业级云原生微服务开源解决方案 ① 快速入门 - [快速入门Github版](https://github.com/Nepxion/Discovery/wiki) - [快速入门Gitee版](https://gitee.com/Nepxion/Discovery/wikis/pages) ② 解决方案 - [解决方案WIKI版](http://nepxion.com/discovery) - [解决方案PPT版](http://nepxion.gitee.io/discovery/docs/link-doc/discovery-ppt.html) ③ 最佳实践 - [最佳实践PPT版](http://nepxion.gitee.io/discovery/docs/link-doc/discovery-ppt-1.html) ④ 平台界面 - [平台界面WIKI版](http://nepxion.com/discovery-platform) ⑤ 框架源码 - [框架源码Github版](https://github.com/Nepxion/Discovery) - [框架源码Gitee版](https://gitee.com/Nepxion/Discovery) ⑥ 指南示例源码 - [指南示例源码Github版](https://github.com/Nepxion/DiscoveryGuide) - [指南示例源码Gitee版](https://gitee.com/Nepxion/DiscoveryGuide) ⑦ 指南示例说明 - Spring Cloud Finchley ~ Hoxton版本 - [极简版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple),分支为6.x.x-simple - [极简版域网关部署指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple-domain-gateway),分支为6.x.x-simple-domain-gateway - [极简版非域网关部署指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-simple-non-domain-gateway),分支为6.x.x-simple-non-domain-gateway - [集成版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x),分支为6.x.x - [高级版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/6.x.x-complex),分支为6.x.x-complex - Spring Cloud 202x版本 - [极简版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master-simple),分支为master-simple - [极简版本地化指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master-simple-native),分支为master-simple-native - [集成版指南示例](https://github.com/Nepxion/DiscoveryGuide/tree/master),分支为master ![](http://nepxion.gitee.io/discovery/docs/polaris-doc/Logo64.png) Polaris【北极星】企业级云原生微服务商业解决方案 ① 解决方案 - [解决方案WIKI版](http://nepxion.com/polaris) ② 框架源码 - [框架源码Github版](https://github.com/polaris-paas/polaris-sdk) - [框架源码Gitee版](https://gitee.com/polaris-paas/polaris-sdk) ③ 指南示例源码 - [指南示例源码Github版](https://github.com/polaris-paas/polaris-guide) - [指南示例源码Gitee版](https://gitee.com/polaris-paas/polaris-guide) ④ 指南示例说明 - Spring Cloud Finchley ~ Hoxton版本 - [指南示例](https://github.com/polaris-paas/polaris-guide/tree/1.x.x),分支为1.x.x - Spring Cloud 202x版本 - [指南示例](https://github.com/polaris-paas/polaris-guide/tree/master),分支为master ### 功能概述 Discovery【探索】微服务框架,基于Spring Cloud & Spring Cloud Alibaba,Discovery服务注册发现、Ribbon & Spring Cloud LoadBalancer负载均衡、Feign & RestTemplate & WebClient调用、Spring Cloud Gateway & Zuul过滤等组件全方位增强的企业级微服务开源解决方案,更贴近企业级需求,更具有企业级的插件引入、开箱即用特征 ① 微服务框架支持的技术栈,如下 - 支持阿里巴巴Spring Cloud Alibaba中间件生态圈 - 支持阿里巴巴Nacos、Eureka、Consul和Zookeeper四个服务注册发现中心 - 支持阿里巴巴Nacos、携程Apollo、Redis、Zookeeper、Consul和Etcd六个远程配置中心 - 支持阿里巴巴Sentinel、Hystrix和Resilience4J三个熔断限流降级权限中间件 - 支持OpenTracing和OpenTelemetry规范下的调用链中间件,Jaeger、SkyWalking和Zipkin等 - 支持Prometheus Micrometer和Spring Boot Admin两个指标中间件 - 支持Java Agent解决异步跨线程ThreadLocal上下文传递 - 支持Spring Spel解决蓝绿灰度参数的驱动逻辑 - 支持Spring Matcher解决元数据匹配的通配逻辑 - 支持Spring Cloud Gateway、Zuul网关和微服务三大模块的蓝绿灰度发布等一系列功能 - 支持和兼容Spring Cloud Edgware版、Finchley版、Greenwich版、Hoxton版和202x版以及更高的Spring Cloud版本 - 支持和兼容Java8~Java17以及更高的SDK版本 ![](http://nepxion.gitee.io/discovery/docs/discovery-doc/Diagram.jpg) ② Discovery【探索】微服务框架支持的应用功能,如下 - 全链路蓝绿灰度发布 - 全链路版本、区域、 IP地址和端口匹配蓝绿发布 - 全链路版本、区域、 IP地址和端口权重灰度发布 - 全链路蓝 | 绿 | 兜底、蓝 | 兜底的蓝绿路由类型 - 全链路稳定、灰度的灰度路由类型 - 全链路网关、服务端到端混合蓝绿灰度发布 - 全链路单网关、域网关、非域网关部署 - 全链路条件驱动、非条件驱动 - 全链路前端触发后端蓝绿灰度发布 - 全局订阅式蓝绿灰度发布 - 全链路自定义网关、服务的过滤器、负载均衡策略类触发蓝绿灰度发布 - 全链路Header、Parameter、Cookie、域名、RPC Method等参数化规则策略驱动 - 全链路本地和远程、局部和全局无参数化规则策略驱动 - 全链路条件表达式、通配表达式支持 - 全链路内置Header,支持定时Job的服务调用蓝绿灰度发布 - 全链路手工编排、智能编排、无编排蓝绿灰度发布 - 全链路自动化测试 - 全链路自动化模拟流程测试 - 全链路自动化模拟流程本地测试 - 全链路自动化模拟流程云上测试 - 全链路自动化流量侦测测试 - 全链路自动化流量侦测本地测试 - 全链路自动化流量侦测云上测试 - 全链路流量管控对接DevOps运维平台 - 全链路多活单元化 - 全链路隔离路由 - 全链路组隔离路由 - 组负载均衡的消费端隔离 - 组Header传值的提供端隔离 - 全链路版本偏好路由 - 全链路区域调试路由 - 全链路环境隔离路由 - 全链路可用区亲和性隔离路由 - 全链路IP地址和端口隔离路由 - 全链路隔离准入 - 基于IP地址黑白名单注册准入 - 基于最大注册数限制注册准入 - 基于IP地址黑白名单发现准入 - 自定义注册发现准入 - 全链路故障转移 - 全链路版本故障转移 - 全链路区域故障转移 - 全链路环境故障转移 - 全链路可用区故障转移 - 全链路IP地址和端口故障转移 - 全链路服务无损下线,实时性的流量绝对无损 - 全局唯一ID屏蔽 - IP地址和端口屏蔽 - 异步场景下全链路蓝绿灰度发布 - 异步跨线程Agent插件 - Hystrix线程池隔离插件 - 网关动态路由 - 路由动态添加 - 路由动态修改 - 路由动态删除 - 路由动态批量更新 - 路由查询 - 路由动态变更后的事件通知 - 全链路服务限流熔断降级权限 - Sentinel基于服务名的防护 - Sentinel基于组的防护 - Sentinel基于版本的防护 - Sentinel基于区域的防护 - Sentinel基于环境的防护 - Sentinel基于可用区的防护 - Sentinel基于IP地址和端口的防护 - Sentinel自定义Header、Parameter、Cookie的防护 - Sentinel自定义业务参数的防护 - Sentinel自定义组合式的防护 - 全链路监控 - 蓝绿灰度埋点和熔断埋点的调用链监控 - 蓝绿灰度埋点和熔断埋点的日志监控 - 熔断埋点的指标监控 - 全链路蓝绿灰度发布编排建模和流量侦测 - 全链路蓝绿发布编排建模 - 全链路灰度发布编排建模 - 全链路蓝绿发布流量侦测 - 全链路灰度发布流量侦测 - 全链路蓝绿灰度发布混合流量侦测 - 全链路数据库和消息队列蓝绿发布 - 基于多DataSource的数据库蓝绿发布 - 基于多Queue的消息队列蓝绿发布 - 全链路服务侧注解 - 元数据流量染色 - 基于Git插件的元数据流量染色 - 基于服务名前缀的元数据流量染色 - 基于启动参数的元数据流量染色 - 基于配置文件的元数据流量染色 - 基于系统参数的元数据流量染色 - 基于POM版本号的元数据流量染色 - 扫描目录 - 自动扫描目录 - 手工扫描目录 - 注入扫描目录 - 规则策略推送 - 基于配置中心的规则策略订阅推送 - 基于Swagger和Rest的规则策略推送 - 基于平台端和桌面端的规则策略推送 - 统一配置订阅执行器 ![](http://nepxion.gitee.io/discovery/docs/discovery-doc/Ability.jpg) ③ Discovery【探索】微服务框架支持的功能维度,如下 微服务框架支持组(Group)、版本(Version)、区域(Region)、环境(Env)、可用区(Zone)、IP地址和端口(Address)、全局唯一ID七大经典维度实施流量管控的方式,通过“并集”方式叠加作用在流量控制上。上述七个维度在功能上各有各的侧重点,如下表格主要讲述各自的区别 | 维度 | 概念 | 场景 | 功能侧重点 | 关键头 | --- | --- | --- | --- | --- | | 组 | 服务实例的系统ID<br>系统逻辑分组 | 路由隔离 | ① 组负载均衡隔离<br>- 调用端和提供端的元数据group是否相同<br>② 组Header传值策略隔离<br>- Header(n-d-group)和提供端的元数据group是否相同<br>③ 不支持故障转移 | n-d-group | | 版本 | 服务实例的版本<br>适用于生产环境 | 蓝绿灰度发布<br>路由转移<br>故障转移 | ① 版本条件匹配蓝绿发布<br>② 版本权重灰度发布<br>③ 版本偏好<br>- 非蓝绿灰度发布场景下,路由到相应版本的实例<br>- 稳定版本策略、指定版本策略<br>④ 版本故障转移<br>- 未找到相应版本的服务实例,路由到其它版本<br>- 负载均衡策略、稳定版本策略、指定版本策略 | n-d-version<br>n-d-version-weight<br>n-d-version-prefer<br>n-d-version-failover | | 区域 | 服务实例的区域<br>适用于多活单元化<br>适用于多机房<br>适用于多环境 | 蓝绿灰度发布<br>同城双活/异地多活<br>路由转移<br>故障转移 | ① 区域条件匹配蓝绿发布<br>② 区域权重灰度发布<br>③ 区域多活单元化<br>④ 区域调试路由<br>- 多区域路由隔离下跨区服务调用的调试手段<br>⑤ 区域故障转移<br>- 未找到相应区域的服务实例,路由到其它区域<br>- 负载均衡策略、指定区域策略 | n-d-region<br>n-d-region-weight<br>n-d-region-transfer<br>n-d-region-failover | | 环境 | 服务实例的环境<br>适用于测试环境 | 路由隔离<br>故障转移 | ① 环境隔离路由<br>- Header(n-d-env)和提供端的元数据env是否相同<br>② 环境故障转移<br>- 未找到相应环境的服务实例,路由到其它环境<br>- 指定环境(未配置,默认为common)策略 | n-d-env<br>n-d-env-failover | | 可用区 | 服务实例的可用区<br>适用于多机房 | 路由隔离<br>故障转移 | ① 可用区亲和性隔离路由<br>- 调用端和提供端的元数据zone是否相同<br>② 可用区故障转移<br>- 未找到相应可用区的服务实例,路由到其它可用区<br>- 支持负载均衡策略、指定区可用区策略 | n-d-zone-failover | | IP地址和端口 |服务实例机器地址 | 蓝绿灰度发布<br>路由隔离<br>故障转移<br>无损下线 | ① IP地址和端口匹配蓝绿发布<br>② IP地址和端口权重灰度发布<br>③ IP地址和端口故障转移<br>- 未找到相应IP地址和端口的服务实例,路由到其它地址<br>- 负载均衡策略、指定区IP地址和端口策略<br>④ IP地址和端口无损下线黑名单屏蔽 | n-d-address<br>n-d-address-failover<br>n-d-address-blacklist | | 全局唯一ID | 服务实例机器ID | 无损下线 | ① 全局唯一ID无损下线黑名单屏蔽 | n-d-id-blacklist | ![](http://nepxion.gitee.io/discovery/docs/discovery-doc/Filter.jpg) ### 发展历程 - 2017年12月开始筹划 - 2018年03月开始编码 - 2018年06月在GitHub开源 - 2018年06月发布v1.0.0,支持Camden版 - 2018年06月发布v2.0.0,支持Dalston版 - 2018年07月发布v3.0.0,支持Edgware版 - 2018年07月发布v4.0.0,支持Finchley版 - 2019年04月发布v5.0.0,支持Greenwich版 - 2020年04月发布v6.0.0,支持Hoxton版 - 2021年04月完成v7.0.0,支持2020版 - 2022年04月完成v8.0.0,支持2021版 - 2023年01月完成v9.0.0,支持2022版 - 2024年03月完成v10.0.0,支持2023版 ### 版本列表 ① 微服务框架版本兼容列表,如下 ![](http://nepxion.gitee.io/discovery/docs/icon-doc/tip.png) 提醒:版本号右边, `↑` 表示>=该版本号, `↓` 表示<=该版本号 | 框架版本 | 框架分支 | 框架状态 | Spring Cloud版本 | Spring Boot版本 | Spring Cloud Alibaba版本 | | --- | --- | --- | --- | --- | --- | | 10.0.0<br>商业版 | DiscoveryX/master | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | 2023.x.x | 3.2.x | 2023.x.x.x | | 9.0.0<br>商业版 | DiscoveryX/9.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | 2022.x.x | 3.1.x<br>3.0.x | 2022.x.x.x | | 8.0.0<br>商业版 | DiscoveryX/8.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | 2021.x.x | 2.7.x<br>2.6.x | 2021.x.x.x | | 7.0.0<br>商业版 | DiscoveryX/7.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | 2020.x.x | 2.5.x<br>2.4.1 `↑` | 2021.x | | 6.21.0 | Discovery/6.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | Hoxton.SR5 `↑`<br>Hoxton<br>Greenwich<br>Finchley | 2.3.x.RELEASE<br>2.2.x.RELEASE<br>2.1.x.RELEASE<br>2.0.x.RELEASE | 2.2.7.RELEASE `↑` | | 6.12.11 `↓` | Discovery/6.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) | Hoxton.SR5 `↑`<br>Hoxton<br>Greenwich<br>Finchley | 2.3.x.RELEASE<br>2.2.x.RELEASE<br>2.1.x.RELEASE<br>2.0.x.RELEASE | 2.2.6.RELEASE `↓`<br>2.1.x.RELEASE<br>2.0.x.RELEASE | | ~~5.6.0~~ | ~~Discovery/5.x.x~~ | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/delete_24.png) | Greenwich | 2.1.x.RELEASE | 2.1.x.RELEASE | | ~~4.15.0~~ | ~~Discovery/4.x.x~~ | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/delete_24.png) | Finchley | 2.0.x.RELEASE | 2.0.x.RELEASE | | 3.38.0 | Discovery/3.x.x | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/arrow_up_24.png) | Edgware | 1.5.x.RELEASE | 1.5.x.RELEASE | | ~~2.0.x~~ | ~~Discovery/2.x.x~~ | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/delete_24.png) | Dalston | 1.x.x.RELEASE | 1.5.x.RELEASE | | ~~1.0.x~~ | ~~Discovery/1.x.x~~ | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/delete_24.png) | Camden | 1.x.x.RELEASE | 1.5.x.RELEASE | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/confirm_24.png) 表示维护中 | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/arrow_up_24.png) 表示不维护,但可用,强烈建议升级 | ![](http://nepxion.gitee.io/discovery/docs/icon-doc/delete_24.png) 表示不维护,不可用,已废弃 - 10.x.x版本(适用于2023.x.x)将继续维护 - 9.x.x版本(适用于2022.x.x)将继续维护 - 8.x.x版本(适用于2021.x.x)将继续维护 - 7.x.x版本(适用于2020.x.x)将继续维护 - 6.x.x版本(同时适用于Finchley、Greenwich和Hoxton)将继续维护 - 5.x.x版本(适用于Greenwich)已废弃 - 4.x.x版本(适用于Finchley)已废弃 - 3.x.x版本(适用于Edgware)不维护,但可用,强烈建议升级 - 2.x.x版本(适用于Dalston)已废弃 - 1.x.x版本(适用于Camden)已废弃 ② 相关中间件版本列表,如下 | 组件类型 | 组件版本 | | --- | --- | | 基础组件 | [![Guava](https://img.shields.io/maven-central/v/com.google.guava/guava.svg?label=Guava&logo=Google)](https://search.maven.org/artifact/com.google.guava/guava)<br>[![Caffeine](https://img.shields.io/maven-central/v/com.github.ben-manes.caffeine/caffeine.svg?label=Caffeine&logo=Caffeine)](https://search.maven.org/artifact/com.github.ben-manes.caffeine/caffeine)<br>[![Redisson](https://img.shields.io/maven-central/v/org.redisson/redisson-spring-boot-starter.svg?label=Redisson&logo=Redis)](https://search.maven.org/artifact/org.redisson/redisson-spring-boot-starter)<br>[![Dom4J](https://img.shields.io/maven-central/v/org.dom4j/dom4j.svg?label=Dom4J&logo=XMPP)](https://search.maven.org/artifact/org.dom4j/dom4j)<br>[![Swagger](https://img.shields.io/maven-central/v/io.swagger/swagger-models?label=Swagger&logo=Swagger)](https://search.maven.org/artifact/io.swagger/swagger-models)<br>[![Swagger](https://img.shields.io/maven-central/v/io.springfox/springfox-swagger2?label=SpringFox%20Swagger&logo=Swagger)](https://search.maven.org/artifact/io.springfox/springfox-swagger2) | | 注册配置组件 | [![Apollo](https://img.shields.io/maven-central/v/com.ctrip.framework.apollo/apollo-client.svg?label=Apollo&logo=ApolloGraphQL)](https://search.maven.org/artifact/com.ctrip.framework.apollo/apollo-client)<br>[![Zookeeper Curator](https://img.shields.io/maven-central/v/org.apache.curator/curator-framework.svg?label=Zookeeper%20Curator&logo=Apache)](https://search.maven.org/artifact/org.apache.curator/curator-framework)<br>[![Consul](https://img.shields.io/maven-central/v/com.ecwid.consul/consul-api.svg?label=Consul&logo=Consul)](https://search.maven.org/artifact/com.ecwid.consul/consul-api)<br>[![JEtcd](https://img.shields.io/maven-central/v/io.etcd/jetcd-core.svg?label=JEtcd&logo=Etcd)](https://search.maven.org/artifact/io.etcd/jetcd-core)<br>[![Nacos](https://img.shields.io/maven-central/v/com.alibaba.nacos/nacos-client.svg?label=Nacos&logo=AlibabaDotCom)](https://search.maven.org/artifact/com.alibaba.nacos/nacos-client)<br>[![Eureka](https://img.shields.io/maven-central/v/com.netflix.eureka/eureka-client.svg?label=Eureka&logo=Netflix)](https://search.maven.org/artifact/com.netflix.eureka/eureka-client)<br>[![Redis](https://img.shields.io/maven-central/v/org.springframework.data/spring-data-redis.svg?label=Redis&logo=Redis)](https://search.maven.org/artifact/org.springframework.data/spring-data-redis) | | 防护组件 | [![Sentinel](https://img.shields.io/maven-central/v/com.alibaba.csp/sentinel-core.svg?label=Sentinel&logo=AlibabaDotCom)](https://search.maven.org/artifact/com.alibaba.csp/sentinel-core)<br>[![Hystrix](https://img.shields.io/maven-central/v/com.netflix.hystrix/hystrix-core.svg?label=Hystrix&logo=Netflix)](https://search.maven.org/artifact/com.netflix.hystrix/hystrix-core) | | 监控组件 | [![SkyWalking](https://img.shields.io/maven-central/v/org.apache.skywalking/apm-toolkit-opentracing.svg?label=SkyWalking&logo=Apache)](https://search.maven.org/artifact/org.apache.skywalking/apm-toolkit-opentracing)<br>[![OpenTelemetry](https://img.shields.io/maven-central/v/io.opentelemetry/opentelemetry-api.svg?label=OpenTelemetry&logo=OpenTelemetry)](https://search.maven.org/artifact/io.opentelemetry/opentelemetry-api)<br>[![OpenTracing](https://img.shields.io/maven-central/v/io.opentracing/opentracing-api.svg?label=OpenTracing&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing/opentracing-api)<br>[![OpenTracing%20Spring%20Cloud](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-spring-cloud-starter.svg?label=OpenTracing%20Spring%20Cloud&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-spring-cloud-starter)<br>[![OpenTracing%20Jaeger](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-spring-jaeger-starter.svg?label=OpenTracing%20Jaeger&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-spring-jaeger-starter)<br>[![OpenTracing%20Concurrent](https://img.shields.io/maven-central/v/io.opentracing.contrib/opentracing-concurrent.svg?label=OpenTracing%20Concurrent&logo=Anaconda)](https://search.maven.org/artifact/io.opentracing.contrib/opentracing-concurrent)<br>[![Spring Boot](https://img.shields.io/maven-central/v/de.codecentric/spring-boot-admin-dependencies.svg?label=Spring%20Boot%20Admin&logo=SpringBoot)](https://search.maven.org/artifact/de.codecentric/spring-boot-admin-dependencies) | | Spring组件 | [![Alibaba Spring](https://img.shields.io/maven-central/v/com.alibaba.spring/spring-context-support.svg?label=Alibaba%20Spring&logo=Spring)](https://search.maven.org/artifact/com.alibaba.spring/spring-context-support)<br>[![Spring Cloud](https://img.shields.io/maven-central/v/org.springframework.cloud/spring-cloud-dependencies.svg?label=Spring%20Cloud&logo=Spring)](https://search.maven.org/artifact/org.springframework.cloud/spring-cloud-dependencies)<br>[![Spring Cloud Alibaba](https://img.shields.io/maven-central/v/com.alibaba.cloud/spring-cloud-alibaba-dependencies.svg?label=Spring%20Cloud%20Alibaba&logo=Spring)](https://search.maven.org/artifact/com.alibaba.cloud/spring-cloud-alibaba-dependencies)<br>[![Spring Boot](https://img.shields.io/maven-central/v/org.springframework.boot/spring-boot-dependencies.svg?label=Spring%20Boot&logo=Spring)](https://search.maven.org/artifact/org.springframework.boot/spring-boot-dependencies) | ### 企业用户 不完全统计,目前社区开源项目(包括本框架以及关联框架或组件)已经被如下公司使用或者调研 <table> <tbody> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/华为.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/腾讯.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/京东.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/顺丰.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中国移动.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/平安银行.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/平安科技.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/平安一账通.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/招商银行.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/民生银行.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/浦发银行信用卡.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/三峡银行.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/亿联银行.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中国人寿.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/太平洋保险.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中国太平.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/众安保险.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/珍保.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/国家电网.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/东方航空.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/恒大.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/碧桂园.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/华住会.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/城家.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/南瑞.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/蔚来汽车.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/东风汽车.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/吉利汽车.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/海纳新思.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/路特斯科技.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/宇信.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/蔷薇.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/掌门.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/跟谁学.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/瑞幸.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/海尔.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/三七互娱.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/诺亚财富.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/快盈.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/链上科技.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/喜马拉雅.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/微鲸.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/东华软件.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/捷顺.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/御家汇.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/融都.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/天阙.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/惠借.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/新云网.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/毅德零空.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/软通动力.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/冰鉴.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/轻舟.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/数梦工场.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/星艺装饰.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/青客.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/顶昂.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/卖客星球.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/思必驰.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/弘人.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/依威能源.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/伯乔.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/创软.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/颐尔信.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/炫贵.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/明略.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/必胜道.png"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中交兴路.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/太谷电力.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/小电.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/学海.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/资云同商.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/巨玩.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/吾享.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/风影.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/云帐房.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/壹站.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/蓝蜂.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/智慧校园.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/睿住.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/天音.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/药链.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/琢创.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/悟空丰运.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/思派.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/手心美业.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/神州商龙.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/润民.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/鑫安利中.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/橙单.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/万达信息.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/百世快递.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/贝壳找房.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/KK直播.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/雪球科技.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中商惠民.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/果果乐学.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/林氏木业.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/兰亮.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/吹星屯.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/诺基亚.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中科云谷.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/希捷速必达.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/趣淘鲸.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/创迹.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/联想.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/物易云通.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/翡翠东方.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/爱纷美.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/保险极客.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/遨游酒店.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/艾科智泊.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/车电网.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/菲森科技.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/筑网科技.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中科曙光.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/博智林机器人.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/欣和企业.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/阿优.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/汇元.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中国联通.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中国透云.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/天九共享.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/十二度精密技术.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/远迈.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/国家电投.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/正丁云商.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/乐摇摇.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中航讯.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/知视科技.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/浙商证券.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/遥望.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/老来网.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/万邑通.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/边锋游戏.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/上汽集团.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/滨江集团.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/海豚科技.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/ClickPaaS.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/Ping++.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/云尚找家纺.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/威诺科技.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/蜀海供应链.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中天置地.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/万顺叫车.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/中电投.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/上药云健康.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/神州信息.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/万米.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/花西子.png"></td> </tr> <tr align="center"> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/本田.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/东软睿驰.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/极氪.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/林氏家居.png"></td> <td width="20%"><img style="max-height:75%;max-width:75%;" src="http://nepxion.gitee.io/discovery/docs/logo-doc/和讯网.png"></td> </tr> </tbody> </table> 为提供更好的专业级服务,请更多已经使用本框架的公司和企业联系我,并希望在[Github Issues](https://github.com/Nepxion/Discovery/issues/56)上登记 ### 落地案例 ① 某大型银行信用卡新核心系统在生产环境接入Nepxion Discovery框架的服务实例数(包括异地双活,同城双活,多机房全部汇总)将近10000个 ② 某大型互联网教育公司在生产环境接入Nepxion Discovery框架的服务实例数截至到2021年2月已达到2600多个,基本接入完毕 <img src="http://nepxion.gitee.io/discovery/docs/discovery-doc/Result.jpg"/> - [企业级落地:阿里巴巴 Nacos 企业级落地上篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490123&idx=1&sn=10d7cd89bf43f07152513718c08dd80c&chksm=fdeb282bca9ca13d2ffb2128c2b5e1acfa5743c0cf835e266835cd5e0233bef5adbca896c8bd&mpshare=1&scene=1&srcid=0724z4xF3FAu0ky75IQ5kexf&sharer_sharetime=1595589366762&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=ef51a5b0b69d9d3093d17fcab26ddf2c201b696670a1736109d481338e2a980b0c9a82df17369c8796381093f405f0a7cb21c9e467871948960c8890753de7c3f0346a03314d993c33e16817f805c42e&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AfxA6ifl0AcuT4OYhZcXm7k%3D&pass_ticket=c2pshxbFqNmjiwpp%2FUl%2FCP77XI63HuMtvWrO9d2Egrv7y16EseCu1CRLBih3O2MM) - [企业级落地:阿里巴巴 Nacos 企业级落地中篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490179&idx=2&sn=6d14417c9770729c89e0ace90f689338&chksm=fdeb28e3ca9ca1f53495cbfeba4bcc0692ff802c034f2e4290f37735428ac0138be050638d46&mpshare=1&scene=1&srcid=0730GwwgWoI8MciSSaATpowp&sharer_sharetime=1596108490727&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=56c1a4d5743468c93969185004d8e48519dcd2f967bba6978f4e1be13ce7b50d42a51670394473104091352b0fd51e8baed4a72591c511a123166888fd1ff6cc5d54a9326947ef8ebec5f813817669ee&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=Ade%2FPtqCCcfAHZQ%2F3vyVCuI%3D&pass_ticket=JDwi8tQ2jPpAhhIOjlvLIetXOdV%2FpqfV3xJ%2B0vfu4O2n10K5qhVh8aZz8bjlwA%2B8) - [企业级落地:阿里巴巴 Nacos 企业级落地下篇](https://mp.weixin.qq.com/s?__biz=MzU4NzU0MDIzOQ==&mid=2247490231&idx=2&sn=d77c78dfaa244c8c2d95c70fdfa5638a&chksm=fdeb28d7ca9ca1c144bd38e8622af472dbbb7bbe328dcabeddac757130431d354cc75f788196&mpshare=1&scene=1&srcid=0806bN7XW61MNRzsq6IFoZbr&sharer_sharetime=1596716100660&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=9255e861c291e6d5033faa3da87c4e627d0272caaf2dbd7f01f573ad886ede89da90cff052cb800b029ebfbbe146348d65533fc11db0256cdcaa17edb0752b46d61deb6de3f883413e9fa4e8394f3544&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090529&lang=zh_CN&exportkey=AZqS6bHMqvgI%2B36YHV%2FRudU%3D&pass_ticket=0wm6xz%2FLhV%2FSxdCvwyJulMHDWW60%2BLZb6hInajgK9oW%2FE9IOemST8NPOOc4mEX7s) - [企业级落地:全链路蓝绿灰度发布智能化实践](https://mp.weixin.qq.com/s?__biz=MzU1NTgxNDM0Nw==&mid=2247484172&idx=1&sn=41ba2fed39d468f7ee4913e9c305f1b3&chksm=fbcfdfa8ccb856be2280e9484e5e5c091645f98b78dd36e4caf9e3c580a58654d3057e0b4ab0&mpshare=1&scene=1&srcid=04239tBo6ikZqGBMEJwg0h57&sharer_sharetime=1591065506571&sharer_shareid=45ec30ab664def961bd5a4f87aafb0f2&key=1712c1d3e731e2888f16059008c5350eadd5f936fdb5e86d01f61ebf46041db0dbe926e940ae2fa24731e4e0a27412840aaed72f2159f6aaddf87489b5e7a181fe77b4962c39b5a5565dd4c93773b8ad&ascene=1&uin=MjczOTY4MzIw&devicetype=Windows+10+x64&version=62090070&lang=zh_CN&exportkey=AZwuvPfR%2BRhkKms5F7xjmXY%3D&pass_ticket=MQsjBxWL55r6TkZZPKDk9MzUlNhSMI7BVZtQPMwSXWNJ8YsqsiWz41EqXEfYqTUD) ### 郑重致谢 - 感谢阿里巴巴中间件Nacos、Sentinel和Spring Cloud Alibaba团队,尤其是Nacos负责人@彦林、@于怀,Sentinel负责人@宿何、@子衿,Spring Cloud Alibaba负责人@铖朴、@良名、@小马哥、@洛夜、@亦盏的技术支持 - 感谢携程Apollo团队,尤其是@宋顺的技术支持 - 感谢所有Committers和Contributors - 感谢所有帮忙分析和定位问题的同学 - 感谢所有提出宝贵建议和意见的同学 - 感谢支持和使用本框架的公司和企业 ### 请联系我 微信、钉钉、公众号和文档 ![](http://nepxion.gitee.io/discovery/docs/contact-doc/wechat-1.jpg)![](http://nepxion.gitee.io/discovery/docs/contact-doc/dingding-1.jpg)![](http://nepxion.gitee.io/discovery/docs/contact-doc/gongzhonghao-1.jpg)![](http://nepxion.gitee.io/discovery/docs/contact-doc/document-1.jpg) ## Star走势图 [![Stargazers over time](https://starchart.cc/Nepxion/Discovery.svg)](https://starchart.cc/Nepxion/Discovery)
0
berndruecker/flowing-retail
Sample application demonstrating an order fulfillment system decomposed into multiple independant components (e.g. microservices). Showing concrete implementation alternatives using e.g. Java, Spring Boot, Apache Kafka, Camunda, Zeebe, ...
2017-09-13T11:41:51Z
null
# Flowing Retail This sample application demonstrates a simple order fulfillment system, decomposed into multiple independent components (like _microservices_). The repository contains code for multiple implementation alternatives to allow a broad audience to understand the code and to compare alternatives. The [table below](#alternatives) lists these alternatives. The example respects learnings from **Domain Driven Design (DDD)**, Event Driven Architecture (EDA) and **Microservices (µS)** and is designed to give you hands-on access to these topics. **Note:** The code was written in order to be explained. Hence, I favored simplified code or copy & paste over production-ready code with generic solutions. **Don't consider the coding style best practice! It is purpose-written to be easily explainable code**. You can find more information on the concepts in the [Practical Process Automation](https://processautomationbook.com/) book with O'Reilly. Flowing retail simulates a very easy order fulfillment system: ![Events and Commands](docs/workflow-in-service.png) <a name = "alternatives"></a> ## Architecture and implementation alternatives The most fundamental choice is to select the **communication mechanism**: * **[Apache Kafka](kafka/)** as event bus (could be easily changed to messaging, e.g. RabbitMQ): [](docs/architecture.png) * **[REST](rest/)** communication between Services. * This example also shows how to do **stateful resilience patterns** like **stateful retries** leveraging a workflow engine. * **[Zeebe](zeebe/)** broker doing work distribution. After the communication mechanism, the next choice is the **workflow engine**: * **Camunda 8 (aka Zeebe)** and the **programming language**: * **Java** ## Storyline Flowing retail simulates a very easy order fulfillment system. The business logic is separated into the services shown above (shown as a [context map](https://www.infoq.com/articles/ddd-contextmapping)). ### Long running services and orchestration Some services are **long running** in nature - for example: the payment service asks customers to update expired credit cards. A workflow engine is used to persist and control these long running interactions. ### Workflows live within service boundaries Note that the state machine (_or workflow engine in this case_) is a library used **within** one service. If different services need a workflow engine they can run whatever engine they want. This way it is an autonomous team decision if they want to use a framework, and which one: ![Events and Commands](docs/workflow-in-service.png) ## Links and background reading * [Practical Process Automation](https://processautomationbook.com/) book * Introduction blog post: https://blog.bernd-ruecker.com/flowing-retail-demonstrating-aspects-of-microservices-events-and-their-flow-with-concrete-source-7f3abdd40e53 * InfoQ-Writeup "Events, Flows and Long-Running Services: A Modern Approach to Workflow Automation": https://www.infoq.com/articles/events-workflow-automation
1
MFC-TEC/ELinkageScroll
多子view嵌套滚动通用解决方案
2019-10-10T03:28:31Z
null
# ELinkageScroll 多子view嵌套滚动通用解决方案 ### Demo运行效果 <img src='https://github.com/baiduapp-tec/ELinkageScroll/blob/master/elinkagescroll.gif' width="300px" style='border: #f1f1f1 solid 1px'/><br> # 使用方法 #### xml ```xml <?xml version="1.0" encoding="utf-8"?> <com.baidu.elinkagescroll.ELinkageScrollLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 第1个子view --> <com.baidu.elinkagescroll.view.LWebView android:id="@+id/webview" android:layout_width="match_parent" android:layout_height="match_parent"/> <!-- 第2个子view --> <com.baidu.elinkagescroll.view.LLinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="100dp" android:textSize="22dp" android:gravity="center" android:background="#22ff0000" android:text="LinearLayout"/> <Button android:layout_width="match_parent" android:layout_height="200dp" android:text="LinearLayout" android:onClick="onLLButtonClick"/> <TextView android:layout_width="match_parent" android:layout_height="150dp" android:textSize="22dp" android:gravity="center" android:background="#22ff0000" android:text="LinearLayout"/> </com.baidu.elinkagescroll.view.LLinearLayout> <!-- 第3个子view --> <com.baidu.elinkagescroll.view.LRecyclerView android:id="@+id/recycler1" android:layout_width="match_parent" android:layout_height="match_parent"/> <!-- 第4个子view --> <com.baidu.elinkagescroll.view.LTextView android:layout_width="match_parent" android:layout_height="300dp" android:background="@color/colorPrimary" android:text="TextView" android:clickable="true" android:textColor="#ffffff" android:textSize="28dp" android:gravity="center"/> <!-- 第5个子view --> <com.baidu.elinkagescroll.view.LRecyclerView android:id="@+id/recycler2" android:layout_width="match_parent" android:layout_height="wrap_content"/> <!-- 第6个子view --> <com.baidu.elinkagescroll.view.LScrollView android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="200dp" android:text="ScrollView - 1" android:textSize="22dp" android:background="#22ff0000" android:gravity="center"/> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <TextView android:layout_width="match_parent" android:layout_height="200dp" android:text="ScrollView - 2" android:textSize="22dp" android:background="#22ff0000" android:gravity="center"/> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <TextView android:layout_width="match_parent" android:layout_height="200dp" android:text="ScrollView - 3" android:textSize="22dp" android:background="#22ff0000" android:gravity="center"/> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <TextView android:layout_width="match_parent" android:layout_height="200dp" android:text="ScrollView - 4" android:textSize="22dp" android:background="#22ff0000" android:gravity="center"/> <View android:layout_width="match_parent" android:layout_height="1px" android:background="#000000"/> <TextView android:layout_width="match_parent" android:layout_height="200dp" android:text="ScrollView - 5" android:textSize="22dp" android:background="#22ff0000" android:gravity="center"/> </LinearLayout> </com.baidu.elinkagescroll.view.LScrollView> <!-- 第7个子view --> <com.baidu.elinkagescroll.sample.LFrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_in_framelayout" android:layout_width="match_parent" android:layout_height="match_parent"/> </com.baidu.elinkagescroll.sample.LFrameLayout> </com.baidu.elinkagescroll.ELinkageScrollLayout> ``` # 联系方式 如果你在使用ELinkageScrollLayout过程中发现任何问题,你可以通过如下方式联系我: * 邮箱: * 微博:https://weibo.com/u/5894400455
0
henryyan/activiti-in-action-codes
Activiti官方唯一推荐中文书籍——《Activiti实战》示例源码
2014-12-07T14:15:20Z
null
《Activiti实战》示例源码 ======================== Activiti官方唯一推荐中文书籍——《Activiti实战》示例源码 Activiti项目负责人Tijs Rademakers高度认可并推荐,根据Activiti新版本系统、深度讲解了BPMN2.0规范,以及Activiti功能、用法、技巧、实践和源代码分析。 > 如果发现代码有问题请到 http://www.kafeitu.me/activiti-in-action.html 页面给我留言或者发邮件到 yanhonglei@gmail.com,多谢支持。 <img src="http://www.kafeitu.me/images/activiti-in-action.jpg" width="510" /> # 编辑推荐 《Activiti实战》是国内Activiti领域第一人撰写,Activiti项目负责人Tijs Rademakers高度认可并推荐; 《Activiti实战》根据Activiti最新版本系统、深度讲解了BPMN2.0规范,以及Activiti功能、用法、技巧、最佳实践和源代码分析。 # 内容简介 《Activiti实战 》立足于实践,不仅让读者知其然,全面掌握Activiti架构、功能、用法、技巧和最佳实践,广度足够;而且让读者知其所以然,深入理解Activiti的源代码实现、设计模式和PVM,深度也足够。 《Activiti实战 》一共四个部分:准备篇(1至2章)介绍了Activiti的概念、特点、应用、体系结构,以及开发环境的搭建和配置;基础篇(3至4章)首先讲解了Activiti Modeler、Activiti Designer两种流程设计工具的详细使用,然后详细讲解了BPMN2.0规范;实战篇(5至14章)系统讲解了Activiti的用法、技巧和最佳实践,包含流程定义、流程实例、任务、子流程、多实例、事件以及监听器等;高级篇(15至21)通过集成WebService、规则引擎、JPA、ESB等各种服务和中间件来阐述了Activiti不仅仅是引擎,实际上是一个BPM平台,最后还通过源代码对它的设计模式及PVM进行了分析。 # 作者简介 闫洪磊(咖啡兔),资深软件开发工程师和架构师,为Activiti贡献了大量代码,为Activiti在中国的推广与普及做了大量的工作,在社群中有很高的威望和知名度,被称为中国Activiti领域的第一人。多年来一直从事OA、ERP等系统的开发与架构设计工作,持续关注并深入研究工作流引擎,目前就职于小马购车,担任架构师一职,并负责公司内部工作流平台的建设工作。 # 精彩书评 >Tijs Rademakers——Activiti 项目负责人 Henry Yan has been a longtime valued contributor to the Activiti project, both for his commits and for promoting Activiti in China through his community and blog site (http://www.kafeitu.me/activiti.html). It’s great to see his Activiti book as it brings a lot of value for Activiti users and developers in China. With Henry Yan’s background in the Activiti project I highly recommend this book for new Activiti users as well as developers already using Activiti. 长期以来,Henry Yan通过他的社区及博客一直致力于在中国广泛推广Activiti,为Activiti项目做出了巨大(或宝贵)贡献。很高兴看到他的《Activiti实战》一书将为Activiti 的中国使用者及开发者提供非常多的重要价值。在Activiti项目方面,Henry Yan具有非常专业的背景经验,在此,我向各位包括已经在使用Activiti的开发者及Activiti新手极力推荐此书。 >徐会生(临远)——jBPM国内推广者,Activiti国内推广者 咖啡兔同学的《Activiti实战》终于出炉,欣喜之情溢于言表。国内的工作流行业虽然产品繁多,但是开源一直为Activiti和jBPM垄断,相对来言Activiti延续了一贯方便灵活的特性,又不会在功能上有半分折损,在国内拥有大量的粉丝。咖啡兔同学此前一直致力于Activiti在国内的推广与传播,先后开辟了专栏博客、Activiti论坛网站、QQ群组,并积极参与Activiti的官方开发,可以说Activiti在国内能达到当前的认知程度,他是功不可没的。可惜,国内尚缺一本可以为Activiti新手答疑解惑,带初阶者更上一层楼的实体书籍。那么我觉得,这个任务由一直积极活跃于Activiti开源社区,既拥有实际流程项目设计研发经验,又为Activiti官方内核提交过代码的人是再合适不过了。 全书由浅入深的引导读者进入工作流的殿堂,不仅覆盖常见的流程功能与实现方法,还专门提供了作者实践中总结的经验方法,这本书必将成为学习流程道路上的得力助手。 >袁启勋(北京信舟科技创始人) 在开源BPM领域,你或许不知道“闫洪磊”是谁,但你必须听说过“咖啡兔”,否则,你不能说你曾经玩过开源BPM! 咖啡兔是我从事BPM工作几年来,少有的一位对BPM领域有较深认识的人,同时他对于开源界热情的、积极的、无私的贡献精神,让我感动。我们信舟科技SuperBPM平台的诞生,离不开咖啡兔提供的巨大 帮助,在此表示感谢。Activiti是一个优秀的项目,让我们能够很容易的将BPM引入我们的企业级应用中,但Activiti毕竟是国外的开源产品,她与国内很多BPM应用还是有些差异,我们还需要对其做一些必要的个性化扩展和补充,才能用于我们实际的企业应用。目前国内关于Activiti的专业资料,几乎没有,而《Activiti实战》无疑是目前最佳的入门宝典,书中介绍了很多案例,都是实际BPM应用中总结的宝贵经验,相信你们将与我一样从中受益,并快速的将Activiti集成到自己的企业应用中,让Activiti绽放光芒。 >Robinson(edoc2 CTO ) 自2010年Tom Bayen离开jBoss加入Afresco公司开发出Activit5,在短短几年时间内,国内有着大批企事业单位和大型金融机构基于Activiti5来构建各类业务流程系统,那是因为 Activiti功能稳定、性能良好、对BPMN2规范的完全支持、API应用友好性和扩展性方面都有 着卓越的表现。个人从2010年接触工作流至今已15年,认为Activti5是完全可以与Ultimus 、K2等大型商用工作流引擎相媲美的大型开源产品,加上国内有着咖啡兔等众多开源奉献者和非常活跃地社区支持,相信Activiti在国内BPM界会发挥更大地作用和价值,也希望这本汇集的各种实战经验能帮助读者深入了解Activiti。 # 立即购买 * 华章自营China-pub:http://product.china-pub.com/3770832 * 京东:http://item.jd.com/11599588.html * 当当:http://product.dangdang.com/23622065.html * 淘宝:自己搜索吧,但请支持正版 # 下载依赖失败解决办法 鉴于国内网络特殊问题,`建议`使用**开源中国**提供的Maven仓库代理中央仓库,参考 [http://maven.oschina.net/help.html](http://maven.oschina.net/help.html) 推荐`settings.xml`内容: ```xml <?xml version="1.0" encoding="UTF-8"?> <settings xmlns="http://maven.apache.org/settings/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"> <mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | --> <mirror> <id>nexus-osc</id> <mirrorOf>central</mirrorOf> <name>Nexus osc</name> <url>http://maven.oschina.net/content/groups/public/</url> </mirror> <mirror> <id>nexus-osc-thirdparty</id> <mirrorOf>thirdparty</mirrorOf> <name>Nexus osc thirdparty</name> <url>http://maven.oschina.net/content/repositories/thirdparty/</url> </mirror> </mirrors> </settings> ``` # 那啥 没有买书?觉得源码有料?买本书吧,也就少喝两杯咖啡而已~~~
0
zhegexiaohuozi/SeimiCrawler
一个简单、敏捷、分布式的支持SpringBoot的Java爬虫框架;An agile, distributed crawler framework.
2015-11-06T16:06:36Z
null
SeimiCrawler ============ [![GitHub release](https://img.shields.io/github/release/zhegexiaohuozi/SeimiCrawler.svg)](https://github.com/zhegexiaohuozi/JsoupXpath/releases) [![Maven](https://maven-badges.herokuapp.com/maven-central/cn.wanghaomiao/SeimiCrawler/badge.svg)](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22cn.wanghaomiao%22%20AND%20a%3A%22SeimiCrawler%22) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) An agile,powerful,standalone,distributed crawler framework.Support spring boot and redisson. SeimiCrawler的目标是成为Java里最实用的爬虫框架,大家一起加油。 # 简介 # SeimiCrawler是一个敏捷的,独立部署的,支持分布式的Java爬虫框架,希望能在最大程度上降低新手开发一个可用性高且性能不差的爬虫系统的门槛,以及提升开发爬虫系统的开发效率。在SeimiCrawler的世界里,绝大多数人只需关心去写抓取的业务逻辑就够了,其余的Seimi帮你搞定。设计思想上SeimiCrawler受Python的爬虫框架Scrapy启发,同时融合了Java语言本身特点与Spring的特性,并希望在国内更方便且普遍的使用更有效率的XPath解析HTML,所以SeimiCrawler默认的HTML解析器是[JsoupXpath](http://jsoupxpath.wanghaomiao.cn)(独立扩展项目,非jsoup自带),默认解析提取HTML数据工作均使用XPath来完成(当然,数据处理亦可以自行选择其他解析器)。并结合[SeimiAgent](https://github.com/zhegexiaohuozi/SeimiAgent)彻底完美解决复杂动态页面渲染抓取问题。 # 最新进展、资讯订阅 # - 微信订阅号 ![weixin](http://img.wanghaomiao.cn/seimiweixin_v2.jpeg) 里面会发布一些使用案例等文章,以及seimi体系相关项目的最新更新动态,后端技术,研发感悟等等。 # V2.0版本新特性 # - 完美支持SpringBoot,[demo参考](https://github.com/zhegexiaohuozi/SeimiCrawler/tree/master/spring-boot-example) - 回调函数支持方法引用,设置起来更自然 ``` push(Request.build(s.toString(),Basic::getTitle)); ``` - 非SpringBoot模式全局配置项通过`SeimiConfig`进行配置,包括 Redis集群信息,SeimiAgent信息等,SpringBoot模式则通过SpringBoot标准模式配置 ``` SeimiConfig config = new SeimiConfig(); config.setSeimiAgentHost("127.0.0.1"); //config.redisSingleServer().setAddress("redis://127.0.0.1:6379"); Seimi s = new Seimi(config); s.goRun("basic"); ``` SpringBoot模式,在application.properties中配置 ``` seimi.crawler.enabled=true # 指定要发起start请求的crawler的name seimi.crawler.names=basic,test seimi.crawler.seimi-agent-host=xx seimi.crawler.seimi-agent-port=xx #开启分布式队列 seimi.crawler.enable-redisson-queue=true #自定义bloomFilter预期插入次数,不设置用默认值 () #seimi.crawler.bloom-filter-expected-insertions= #自定义bloomFilter预期的错误率,0.001为1000个允许有一个判断错误的。不设置用默认值(0.001) #seimi.crawler.bloom-filter-false-probability= ``` - 分布式队列改用Redisson实现,底层依旧为redis,去重引入BloomFilter以提高空间利用率,一个线上的[BloomFilter调参模拟器地址](https://hur.st/bloomfilter/?n=4000&p=1.0E-7&m=&k=8) - JDK要求 1.8+ # 原理示例 # ## 基本原理 ## ![SeimiCrawler原理图](http://img.wanghaomiao.cn/v2_Seimi.png) ## 集群原理 ## ![SeimiCrawler集群原理图](http://img.wanghaomiao.cn/v1_distributed.png) # 社区沟通讨论 # - QQ群:`557410934` ![QQ群](http://img.wanghaomiao.cn/seimiqq.png) 这个就是给大家自由沟通啦 # 快速开始 # 添加maven依赖(以中央maven库最新版本为准,下仅供参考): ``` <dependency> <groupId>cn.wanghaomiao</groupId> <artifactId>SeimiCrawler</artifactId> <version>2.1.4</version> </dependency> ``` 在包`crawlers`下添加爬虫规则,例如: ``` @Crawler(name = "basic") public class Basic extends BaseSeimiCrawler { @Override public String[] startUrls() { return new String[]{"http://www.cnblogs.com/"}; } @Override public void start(Response response) { JXDocument doc = response.document(); try { List<Object> urls = doc.sel("//a[@class='titlelnk']/@href"); logger.info("{}", urls.size()); for (Object s:urls){ push(Request.build(s.toString(),Basic::getTitle)); } } catch (Exception e) { e.printStackTrace(); } } public void getTitle(Response response){ JXDocument doc = response.document(); try { logger.info("url:{} {}", response.getUrl(), doc.sel("//h1[@class='postTitle']/a/text()|//a[@id='cb_post_title_url']/text()")); //do something } catch (Exception e) { e.printStackTrace(); } } } ``` 然后随便某个包下添加启动Main函数,启动SeimiCrawler: ``` public class Boot { public static void main(String[] args){ Seimi s = new Seimi(); s.start("basic"); } } ``` 以上便是一个最简单的爬虫系统开发流程。 ## 工程化打包部署 ## ### Spring boot(推荐) ### 推荐使用spring boot方式来构建项目,这样能借助现有的spring boot生态扩展出很多意想不到的玩法。Spring boot项目打包参考spring boot官网的标准打包方式即可 ``` mvn package ``` ### 独立运行 ### 上面可以方便的用来开发或是调试,当然也可以成为生产环境下一种启动方式。但是,为了便于工程化部署与分发,SeimiCrawler提供了专门的打包插件用来对SeimiCrawler工程进行打包,打好的包可以直接分发部署运行了。 pom中添加添加plugin ``` <plugin> <groupId>cn.wanghaomiao</groupId> <artifactId>maven-seimicrawler-plugin</artifactId> <version>1.2.0</version> <executions> <execution> <phase>package</phase> <goals> <goal>build</goal> </goals> </execution> </executions> <!--<configuration>--> <!-- 默认target目录 --> <!--<outputDirectory>/some/path</outputDirectory>--> <!--</configuration>--> </plugin> ``` 执行`mvn clean package`即可,打好包目录结构如下: ``` . ├── bin # 相应的脚本中也有具体启动参数说明介绍,在此不再敖述 │ ├── run.bat #windows下启动脚本 │ └── run.sh #Linux下启动脚本 └── seimi ├── classes #Crawler工程业务类及相关配置文件目录 └── lib #工程依赖包目录 ``` 接下来就可以直接用来分发与部署了。 > 详细请继续参阅[maven-seimicrawler-plugin](https://github.com/zhegexiaohuozi/maven-seimicrawler-plugin) # 更多文档 # 目前可以参考demo工程中的样例,基本包含了主要的特性用法。更为细致的文档移步[SeimiCrawler主页](http://seimi.wanghaomiao.cn)中进一步查看 # Change log # 请参阅 [ChangeLog.md](https://github.com/zhegexiaohuozi/SeimiCrawler/blob/master/ChangeLog.md) # 项目源码 # [Github](https://github.com/zhegexiaohuozi/SeimiCrawler) > **BTW:** > 如果您觉着这个项目不错,到github上`star`一下,我是不介意的 ^_^
0
nguyenq/tess4j
Java JNA wrapper for Tesseract OCR API
2014-06-25T23:31:52Z
null
## Tess4J [![Join the chat at https://gitter.im/nguyenq/tess4j](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/nguyenq/tess4j?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) A Java JNA wrapper for [Tesseract OCR API](https://github.com/tesseract-ocr). Tess4J is released and distributed under the [Apache License, v2.0](http://www.apache.org/licenses/LICENSE-2.0). ## Features The library provides optical character recognition (OCR) support for: * TIFF, JPEG, GIF, PNG, and BMP image formats * Multi-page TIFF images * PDF document format ## Dependencies On Windows: Microsoft Visual C++ 2022 x86 and x64 Runtimes Since Tesseract and Leptonica Windows binaries were built using Visual Studio 2022 (v143) Platform Toolset, please ensure you have [Microsoft Visual C++ 2022 Redistributable](https://visualstudio.microsoft.com/downloads/) installed. ## Tutorial [Development with Tess4J in NetBeans, Eclipse, and Command-line](http://tess4j.sourceforge.net/tutorial/) ## Contributors A big thanks to GitHub and all of Tess4J's contributors.
0
wzgiceman/RxjavaRetrofitDemo-master
Retrofit+Rxjava+okhttp终极封装(Gson方案)
2016-07-18T01:01:44Z
null
# Retrofit+Rxjava+okhttp封装 ![Preview](https://github.com/wzgiceman/RxjavaRetrofitDemo-string-master/blob/master/gif/rxretrofit.gif) 1.Retrofit+Rxjava+okhttp基本使用方法 2.统一处理请求数据格式 3.统一的ProgressDialog和回调Subscriber处理 4.取消http请求 5.预处理http请求 6.返回数据的统一判断 7.失败后的retry处理 8.RxLifecycle管理生命周期,防止泄露 9.文件上传下载(支持多文件,断点续传) 10.Cache数据持久化和数据库(greenDao)两种缓存机制 ## 依赖工程 * 1.moudel导入工程 ```java compile project(':rxretrofitlibrary') ``` * 2.初始化设置:Application中初始化 ```java RxRetrofitApp.init(this); ``` ## 代码使用 更多用法请参考demo ```java // 完美封装简化版 private void simpleDo() { SubjectPost postEntity = new SubjectPost(simpleOnNextListener,this); postEntity.setAll(true); HttpManager manager = HttpManager.getInstance(); manager.doHttpDeal(postEntity); } // 回调一一对应 HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<List<Subject>>() { @Override public void onNext(List<Subject> subjects) { tvMsg.setText("已封装:\n" + subjects.toString()); } /*用户主动调用,默认是不需要覆写该方法*/ @Override public void onError(Throwable e) { super.onError(e); tvMsg.setText("失败:\n" + e.toString()); } } ``` * 初始化一个请求数据的对象继承BaseEntity对象,传递一个sub回调对象和context对象,设置请求需要的参数 * 通过单利获取一个httpmanger对象,触发请求 * 结果统一通过BaseEntity中的fun1方法判断,最后返回传递的sub对象中 ## 变种-推荐使用 在之前的封装1-5中我们都是通过传统的GsonConverterFactory自动解析,这样做确实很方便,用户能直接获取返回的对象,不用关心具体的转换,但是:这随之而来有很多的缺陷(虽然官网推荐这样使用); 比如:无法使用其他第三发转换框架;泛型无法中间传递,封装无法统一处理缓存结果;回调信息无法统一处理.......... 所以我们在享受它遍历的同时也被迫的要限制做很多的处理,限制我们的扩展! 介绍如何放弃GsonConverterFactory,直接返回String,扩展我们的封装!(封装的整体思想和之前的封装一样,所以不会有大的改动!) >[Rxjava+ReTrofit+okHttp深入浅出-终极封装变种](https://github.com/wzgiceman/RxjavaRetrofitDemo-string-master) >[Rxjava+ReTrofit+okHttp极简方式使用-无需任何学习成本](https://github.com/wzgiceman/Rx-Retrofit) ## 思路 详细思路可以可以参看我的博客: [Rxjava+ReTrofit+okHttp深入浅出-终极封装](http://blog.csdn.net/column/details/13297.html) ## 问题反馈列表集合 [问题反馈列表集合-汇总解决](https://github.com/wzgiceman/RxjavaRetrofitDemo-master/blob/master/README_ep.md) ## QQ交流群 ![](https://github.com/wzgiceman/Rxbus/blob/master/gif/qq.png)
0
springside/springside4
A Spring Framework based, pragmatic style JavaEE application reference architecture.
2012-02-23T08:39:03Z
null
### 最新开源: [VJTools-唯品会Java核心项目](https://github.com/vipshop/vjtools) # SpringSide [![Build Status](https://api.travis-ci.org/springside/springside4.png?branch=master)](https://travis-ci.org/springside/springside4/) SpringSide是以Spring Framework为核心的,Pragmatic风格的JavaEE应用参考示例,是JavaEE世界中的主流技术选型,最佳实践的总结与演示。 1. Utils - 性能与易用性兼顾的Java基础库,综合各门各派的大成之作(近期重点). 2. BootApi - 基于Spring Boot的Web Service应用, 可以用于SOA服务,或Ajax页面的后台. 3. BootWeb - 基于Spring Boot的Web应用, 典型的增删改查管理(未开始). 4. Showcase - 更多的示例. ## 主要用例 全部示例以一个P2P图书馆展开,P2P图书馆避免了中央式图书馆所需的场地和图书管理员,大家把图书登记在应用里互相借阅。 ## 快速开始 (JDK7.0+) 1. 运行根目录下的quick-start.sh 或 quick-start.bat * 将modules安装到本地maven仓库 * 以开发模式启动BootApi应用 2. 访问 http://localhost:8080/,按上面的提示体验。 ------------------------------- Offical Site: http://springside.io(域名过期) Document: https://github.com/springside/springside4/wiki
0
shyiko/mysql-binlog-connector-java
MySQL Binary Log connector
2013-07-11T15:05:22Z
null
# mysql-binlog-connector-java [![Build Status](https://travis-ci.org/shyiko/mysql-binlog-connector-java.svg?branch=master)](https://travis-ci.org/shyiko/mysql-binlog-connector-java) [![Coverage Status](https://coveralls.io/repos/shyiko/mysql-binlog-connector-java/badge.svg?branch=master)](https://coveralls.io/r/shyiko/mysql-binlog-connector-java?branch=master) [![Maven Central](https://img.shields.io/maven-central/v/com.github.shyiko/mysql-binlog-connector-java.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.shyiko%22%20AND%20a%3A%22mysql-binlog-connector-java%22) ## ATTENTION: This repository is no longer maintained. I recommend migrating to [osheroff/mysql-binlog-connector-java](https://github.com/osheroff/mysql-binlog-connector-java). MySQL Binary Log connector. Initially project was started as a fork of [open-replicator](https://code.google.com/p/open-replicator), but ended up as a complete rewrite. Key differences/features: - automatic binlog filename/position | GTID resolution - resumable disconnects - plugable failover strategies - binlog_checksum=CRC32 support (for MySQL 5.6.2+ users) - secure communication over the TLS - JMX-friendly - real-time stats - availability in Maven Central - no third-party dependencies - test suite over different versions of MySQL releases > If you are looking for something similar in other languages - check out [siddontang/go-mysql](https://github.com/siddontang/go-mysql) (Go), [noplay/python-mysql-replication](https://github.com/noplay/python-mysql-replication) (Python). ## Usage Get the latest JAR(s) from [here](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.github.shyiko%22%20AND%20a%3A%22mysql-binlog-connector-java%22). Alternatively you can include following Maven dependency (available through Maven Central): ```xml <dependency> <groupId>com.github.shyiko</groupId> <artifactId>mysql-binlog-connector-java</artifactId> <version>0.21.0</version> </dependency> ``` #### Reading binary log file ```java File binlogFile = ... EventDeserializer eventDeserializer = new EventDeserializer(); eventDeserializer.setCompatibilityMode( EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG, EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY ); BinaryLogFileReader reader = new BinaryLogFileReader(binlogFile, eventDeserializer); try { for (Event event; (event = reader.readEvent()) != null; ) { ... } } finally { reader.close(); } ``` #### Tapping into MySQL replication stream > PREREQUISITES: Whichever user you plan to use for the BinaryLogClient, he MUST have [REPLICATION SLAVE](http://dev.mysql.com/doc/refman/5.5/en/privileges-provided.html#priv_replication-slave) privilege. Unless you specify binlogFilename/binlogPosition yourself (in which case automatic resolution won't kick in), you'll need [REPLICATION CLIENT](http://dev.mysql.com/doc/refman/5.5/en/privileges-provided.html#priv_replication-client) granted as well. ```java BinaryLogClient client = new BinaryLogClient("hostname", 3306, "username", "password"); EventDeserializer eventDeserializer = new EventDeserializer(); eventDeserializer.setCompatibilityMode( EventDeserializer.CompatibilityMode.DATE_AND_TIME_AS_LONG, EventDeserializer.CompatibilityMode.CHAR_AND_BINARY_AS_BYTE_ARRAY ); client.setEventDeserializer(eventDeserializer); client.registerEventListener(new EventListener() { @Override public void onEvent(Event event) { ... } }); client.connect(); ``` > You can register a listener for `onConnect` / `onCommunicationFailure` / `onEventDeserializationFailure` / `onDisconnect` using `client.registerLifecycleListener(...)`. > By default, BinaryLogClient starts from the current (at the time of connect) master binlog position. If you wish to kick off from a specific filename or position, use `client.setBinlogFilename(filename)` + `client.setBinlogPosition(position)`. > `client.connect()` is blocking (meaning that client will listen for events in the current thread). `client.connect(timeout)`, on the other hand, spawns a separate thread. #### Controlling event deserialization > You might need it for several reasons: you don't want to waste time deserializing events you won't need; there is no EventDataDeserializer defined for the event type you are interested in (or there is but it contains a bug); you want certain type of events to be deserialized in a different way (perhaps *RowsEventData should contain table name and not id?); etc. ```java EventDeserializer eventDeserializer = new EventDeserializer(); // do not deserialize EXT_DELETE_ROWS event data, return it as a byte array eventDeserializer.setEventDataDeserializer(EventType.EXT_DELETE_ROWS, new ByteArrayEventDataDeserializer()); // skip EXT_WRITE_ROWS event data altogether eventDeserializer.setEventDataDeserializer(EventType.EXT_WRITE_ROWS, new NullEventDataDeserializer()); // use custom event data deserializer for EXT_DELETE_ROWS eventDeserializer.setEventDataDeserializer(EventType.EXT_DELETE_ROWS, new EventDataDeserializer() { ... }); BinaryLogClient client = ... client.setEventDeserializer(eventDeserializer); ``` #### Exposing BinaryLogClient through JMX ```java MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); BinaryLogClient binaryLogClient = ... ObjectName objectName = new ObjectName("mysql.binlog:type=BinaryLogClient"); mBeanServer.registerMBean(binaryLogClient, objectName); // following bean accumulates various BinaryLogClient stats // (e.g. number of disconnects, skipped events) BinaryLogClientStatistics stats = new BinaryLogClientStatistics(binaryLogClient); ObjectName statsObjectName = new ObjectName("mysql.binlog:type=BinaryLogClientStatistics"); mBeanServer.registerMBean(stats, statsObjectName); ``` #### Using SSL > Introduced in 0.4.0. TLSv1.1 & TLSv1.2 require [JDK 7](http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6916074)+. Prior to MySQL 5.7.10, MySQL supported only TLSv1 (see [Secure Connection Protocols and Ciphers](http://dev.mysql.com/doc/refman/5.7/en/secure-connection-protocols-ciphers.html)). > To check that MySQL server is [properly configured with SSL support](http://dev.mysql.com/doc/refman/5.7/en/using-secure-connections.html) - `mysql -h host -u root -ptypeyourpasswordmaybe -e "show global variables like 'have_%ssl';"` ("Value" should be "YES"). State of the current session can be determined using `\s` ("SSL" should not be blank). ```java System.setProperty("javax.net.ssl.trustStore", "/path/to/truststore.jks"); System.setProperty("javax.net.ssl.trustStorePassword","truststore.password"); System.setProperty("javax.net.ssl.keyStore", "/path/to/keystore.jks"); System.setProperty("javax.net.ssl.keyStorePassword", "keystore.password"); BinaryLogClient client = ... client.setSSLMode(SSLMode.VERIFY_IDENTITY); ``` ## Implementation notes - data of numeric types (tinyint, etc) always returned signed(!) regardless of whether column definition includes "unsigned" keyword or not. - data of var\*/\*text/\*blob types always returned as a byte array (for var\* this is true starting from 1.0.0). ## Frequently Asked Questions **Q**. How does a typical transaction look like? **A**. GTID event (if gtid_mode=ON) -> QUERY event with "BEGIN" as sql -> ... -> XID event | QUERY event with "COMMIT" or "ROLLBACK" as sql. **Q**. EventData for inserted/updated/deleted rows has no information about table (except for some weird id). How do I make sense out of it? **A**. Each [WriteRowsEventData](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/WriteRowsEventData.java)/[UpdateRowsEventData](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/UpdateRowsEventData.java)/[DeleteRowsEventData](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/DeleteRowsEventData.java) event is preceded by [TableMapEventData](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/TableMapEventData.java) which contains schema & table name. If for some reason you need to know column names (types, etc). - the easiest way is to ```sql select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, ORDINAL_POSITION, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, CHARACTER_OCTET_LENGTH, NUMERIC_PRECISION, NUMERIC_SCALE, CHARACTER_SET_NAME, COLLATION_NAME from INFORMATION_SCHEMA.COLUMNS; # see https://dev.mysql.com/doc/refman/5.6/en/columns-table.html for more information ``` (yes, binary log DOES NOT include that piece of information). You can find JDBC snippet [here](https://github.com/shyiko/mysql-binlog-connector-java/issues/24#issuecomment-43747417). ## Documentation #### API overview There are two entry points - [BinaryLogClient](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/BinaryLogClient.java) (which you can use to read binary logs from a MySQL server) and [BinaryLogFileReader](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/BinaryLogFileReader.java) (for offline log processing). Both of them rely on [EventDeserializer](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/EventDeserializer.java) to deserialize stream of events. Each [Event](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/Event.java) consists of [EventHeader](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/EventHeader.java) (containing among other things reference to [EventType](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/EventType.java)) and [EventData](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/EventData.java). The aforementioned EventDeserializer has one [EventHeaderDeserializer](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/EventHeaderDeserializer.java) ([EventHeaderV4Deserializer](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/EventHeaderV4Deserializer.java) by default) and [a collection of EventDataDeserializer|s](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/EventDeserializer.java#L82). If there is no EventDataDeserializer registered for some particular type of Event - default EventDataDeserializer kicks in ([NullEventDataDeserializer](https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/NullEventDataDeserializer.java)). #### MySQL Internals Manual For the insight into the internals of MySQL look [here](https://dev.mysql.com/doc/internals/en/index.html). [MySQL Client/Server Protocol](http://dev.mysql.com/doc/internals/en/client-server-protocol.html) and [The Binary Log](http://dev.mysql.com/doc/internals/en/binary-log.html) sections are particularly useful as a reference documentation for the `**.binlog.network` and `**.binlog.event` packages. ## Real-world applications Some of the OSS using / built on top of mysql-binlog-conector-java: * [apache/nifi](https://github.com/apache/nifi) An easy to use, powerful, and reliable system to process and distribute data. * [debezium](https://github.com/debezium/debezium) A low latency data streaming platform for change data capture (CDC). * [mavenlink/changestream](https://github.com/mavenlink/changestream) - A stream of changes for MySQL built on Akka. * [mardambey/mypipe](https://github.com/mardambey/mypipe) MySQL binary log consumer with the ability to act on changed rows and publish changes to different systems with emphasis on Apache Kafka. * [ngocdaothanh/mydit](https://github.com/ngocdaothanh/mydit) MySQL to MongoDB data replicator. * [sharetribe/dumpr](https://github.com/sharetribe/dumpr) A Clojure library for live replicating data from a MySQL database. * [shyiko/rook](https://github.com/shyiko/rook) Generic Change Data Capture (CDC) toolkit. * [streamsets/datacollector](https://github.com/streamsets/datacollector) Continuous big data ingestion infrastructure. * [twingly/ecco](https://github.com/twingly/ecco) MySQL replication binlog parser in JRuby. * [zendesk/maxwell](https://github.com/zendesk/maxwell) A MySQL-to-JSON Kafka producer. * [zzt93/syncer](https://github.com/zzt93/syncer) A tool sync & manipulate data from MySQL/MongoDB to ES/Kafka/MySQL, which make 'Eventual Consistency' promise. It's also used [on a large scale](https://twitter.com/atwinmutt/status/626816601078300672) in MailChimp. You can read about it [here](http://devs.mailchimp.com/blog/powering-mailchimp-pro-reporting/). ## Development ```sh git clone https://github.com/shyiko/mysql-binlog-connector-java.git cd mysql-binlog-connector-java mvn # shows how to build, test, etc. project ``` ## Contributing In lieu of a formal styleguide, please take care to maintain the existing coding style. Executing `mvn checkstyle:check` within project directory should not produce any errors. If you are willing to install [vagrant](http://www.vagrantup.com/) (required by integration tests) it's highly recommended to check (with `mvn clean verify`) that there are no test failures before sending a pull request. Additional tests for any new or changed functionality are also very welcomed. ## License [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
0
selenide/selenide
Concise UI Tests with Java!
2012-02-07T11:44:33Z
null
# Selenide = UI Testing Framework powered by Selenium WebDriver ![Build Status](https://github.com/selenide/selenide/workflows/Run%20tests/badge.svg) [![Maven Central](https://img.shields.io/maven-central/v/com.codeborne/selenide.svg)](https://central.sonatype.com/search?q=selenide&namespace=com.codeborne) [![MIT License](http://img.shields.io/badge/license-MIT-green.svg)](https://github.com/selenide/selenide/blob/main/LICENSE) ![Free](https://img.shields.io/badge/free-open--source-green.svg) [![Join the chat at https://gitter.im/codeborne/selenide](https://img.shields.io/badge/welcome%20to-chat-green.svg)](https://gitter.im/codeborne/selenide?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Присоединяйся к чату https://gitter.im/codeborne/selenide-ru](https://img.shields.io/badge/%D0%B7%D0%B0%D1%85%D0%BE%D0%B4%D0%B8%20%D0%B2-%D1%87%D0%B0%D1%82-green.svg)](https://gitter.im/codeborne/selenide-ru?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Follow](https://img.shields.io/twitter/follow/selenide.svg?style=social&label=Follow)](https://twitter.com/selenide) [![Telegram channel](https://img.shields.io/badge/Telegram-channel-blue.svg)](https://t.me/selenide) [![Telegram чат](https://img.shields.io/badge/Telegram-%D1%87%D0%B0%D1%82-blue.svg)](https://t.me/selenide_ru) ## What is Selenide? Selenide is a framework for writing easy-to-read and easy-to-maintain automated tests in Java. It defines concise fluent API, natural language assertions and does some magic for ajax-based applications to let you focus entirely on the business logic of your tests. Selenide is based on and is compatible to Selenium WebDriver 4.0+ ```java @Test public void login() { open("/login"); $(By.name("user.name")).setValue("johny"); $("#submit").click(); $("#username").shouldHave(text("Hello, Johny!")); } ``` Look for [detailed comparison of Selenide and Selenium WebDriver API](https://github.com/selenide/selenide/wiki/Selenide-vs-Selenium). #### Selenide for mobile apps You can use Selenide for testing mobile applications. See plugin [selenide-appium](https://github.com/selenide/selenide/tree/main/modules/appium). #### Selenide with Selenoid You can use Selenide for running tests in Selenoid containers. See plugin [selenide-selenoid](https://github.com/selenide/selenide/tree/main/modules/selenoid). #### Selenide with Selenium Grid You can use Selenide for running tests in Selenium Grid. See plugin [selenide-grid](https://github.com/selenide/selenide/tree/main/modules/grid). ## Changelog Here is [CHANGELOG](https://github.com/selenide/selenide/blob/main/CHANGELOG.md) ## How to start? Just put selenide.jar to your project and import the following methods: `import static com.codeborne.selenide.Selenide.*;` Look for [Quick Start](https://github.com/selenide/selenide/wiki/Quick-Start) for details. ## Resources * First of all, [selenide.org](http://selenide.org) * For bustlers: [How to start writing UI tests in 10 minutes](http://selenide.org/2014/10/01/how-to-start-writing-ui-tests/) * For developers: [Selenide presentation on Devoxx 2015](http://selenide.org/2015/11/13/selenide-on-devoxx/) * For QA engineers: [Selenide presentation on SeleniumConf 2015](http://selenide.org/2015/09/23/selenide-on-seleniumconf/) * For russians: [Selenide presentation on SeleniumCamp 2015](http://seleniumcamp.com/materials/good-short-test/) ## FAQ See [Frequently asked questions](http://selenide.org/faq.html) ## Posts - Set-up environment with gradle, junit5, allure and selenide -- read a [post](https://medium.com/@rosolko/simple-allure-2-configuration-for-gradle-8cd3810658dd) on medium, grab from [GitHub](https://github.com/rosolko/allure-gradle-configuration) - Small step do dramatically improve your tests speed -- read a [post](https://medium.com/@rosolko/boost-you-autotests-with-fast-authorization-b3eee52ecc19) on medium - Another way to improve tests speed -- read a [post](https://medium.com/@rosolko/fast-authorization-level-local-storage-6c84e9b3cef1) on medium - [Configure Selenide to work with Selenoid](https://medium.com/@rosolko/configure-selenide-to-work-with-selenoid-8835cd6dc7d2) ## Contributing Contributions to Selenide are both welcomed and appreciated. See [CONTRIBUTING.md](CONTRIBUTING.md) for specific guidelines. Feel free to fork, clone, build, run tests and contribute pull requests for Selenide! ## Authors Selenide was originally designed and developed by [Andrei Solntsev](http://asolntsev.github.io/) in 2011-2021 and is maintained by [a group of enthusiast](https://github.com/orgs/selenide/people). ## Thanks Many thanks to these incredible tools that help us create open-source software: [![Intellij IDEA](https://selenide.org/images/jetbrains.svg)](http://www.jetbrains.com/idea) [![BrowserStack](https://www.browserstack.com/images/mail/browserstack-logo-footer.png)](https://www.browserstack.com) [![LambdaTest](https://www.lambdatest.com/support/img/logo.svg)](https://www.lambdatest.com/) ## License Selenide is open-source project, and distributed under the [MIT](http://choosealicense.com/licenses/mit/) license
0
twowaits/SDE-Interview-Questions
Most comprehensive list :clipboard: of tech interview questions :blue_book: of companies scraped from Geeksforgeeks, CareerCup and Glassdoor.
2017-10-25T11:08:52Z
null
[![All Contributors](https://img.shields.io/badge/all_contributors-49-orange.svg?style=flat-square)](#contributors) ![](https://github.com/rishabh115/Interview-Questions/blob/master/thumbnail.png) # Companies<sup title="Companies whose are articles are properly ready">*</sup> | | Companies| | ------ | ------ | | **E** | [Expedia](Expedia/README.md) | | **G** | [Grab](Grab/README.md) | | **M** | [MobiKwik](MobiKwik/README.md) | | **N** | [NEC Technologies](NEC%20Technologies/README.md) | | **P** | [PayPal](PayPal/README.md) | | **S** | [Samsung Research Institute](Samsung/README.md) | | **U** | [Uber](Uber/README.md) | | **Y** | [Yatra.com](Yatra.com/README.md) | | **Z** | [Zomato](Zomato/README.md) | ## Announcements👐 <i><b>📣This repo is not participating in hacktoberfest this year. </b></i> There are many unfinished articles in this repo. Feel free to contribute or create the issue. #### Note: This repo is for educational purposes only. If you are going to contribute, don't do symbolic contribution. Strictly adhere to contributing guidelines and hacktoberfest rules. Fixing grammar, typos and formatting only is complete non-sense. And non-sense is highly discouraged. ## Top Contributors ✨ Thanks goes to these wonderful people: <table href = "#contributors"> <tr> <td align="center"><a href="https://github.com/sesubash"><img src="https://avatars0.githubusercontent.com/u/4628269?v=4" width="100px;" alt="Subash Selvaraj"/><br /><sub><b>Subash Selvaraj</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=sesubash" title="Code">💻</a></td> <td align="center"><a href="https://in.linkedin.com/in/shrutiab"><img src="https://avatars0.githubusercontent.com/u/10259707?v=4" width="100px;" alt="Shruti Bhutaiya"/><br /><sub><b>Shruti Bhutaiya</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=shrutibhutaiya" title="Code">💻</a></td> <td align="center"><a href="https://github.com/akshit04"><img src="https://avatars0.githubusercontent.com/u/20995986?v=4" width="100px;" alt="Akshit Kharbanda"/><br /><sub><b>Akshit Kharbanda</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=akshit04" title="Code">💻</a></td> <td align="center"><a href="https://github.com/dhruv-aggarwal"><img src="https://avatars2.githubusercontent.com/u/13146014?v=4" width="100px;" alt="Dhruv Aggarwal"/><br /><sub><b>Dhruv Aggarwal</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=dhruv-aggarwal" title="Code">💻</a></td> <td align="center"><a href="https://github.com/CheshtaK"><img src="https://avatars2.githubusercontent.com/u/32400008?v=4" width="100px;" alt="Cheshta Kwatra"/><br /><sub><b>Cheshta Kwatra</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=CheshtaK" title="Code">💻</a></td> <td align="center"><a href="https://github.com/kartikay101"><img src="https://avatars0.githubusercontent.com/u/21268943?v=4" width="100px;" alt="Kartikay Shandil "/><br /><sub><b>Kartikay Shandil </b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=kartikay101" title="Code">💻</a></td> <td align="center"><a href="https://tanaytoshniwal.me"><img src="https://avatars3.githubusercontent.com/u/19304171?v=4" width="100px;" alt="Tanay Toshniwal"/><br /><sub><b>Tanay Toshniwal</b></sub></a><br /><a href="https://github.com/rishabh115/Interview-Questions/commits?author=tanaytoshniwal" title="Code">💻</a></td> </tr> </table> #### For contributing see <a href="https://github.com/rishabh115/InterviewQuestions/blob/master/CONTRIBUTING.md">Contributing guidelines</a> . ## Similar projects: - [Interviewee-Questions](https://github.com/alexakasanjeev/Interviewee-Questions) by [Sanjeev](https://github.com/alexakasanjeev) ## Feel free to show your love :heart: by putting a star :star: on this project :v: . <b name="ref">References</b> - [Geeksforgeeks](http://www.geeksforgeeks.org/) - [Career Cup](https://www.careercup.com/) - [Glassdoor](https://www.glassdoor.co.in/index.htm)
0
pinterest/secor
Secor is a service implementing Kafka log persistence
2014-04-15T22:26:44Z
null
# Pinterest Secor [![Build Status](https://travis-ci.org/pinterest/secor.svg)](https://travis-ci.org/pinterest/secor) Secor is a service persisting [Kafka] logs to [Amazon S3], [Google Cloud Storage], [Microsoft Azure Blob Storage] and [Openstack Swift]. ## Key features ## - **strong consistency**: as long as [Kafka] is not dropping messages (e.g., due to aggressive cleanup policy) before Secor is able to read them, it is guaranteed that each message will be saved in exactly one [S3] file. This property is not compromised by the notorious temporal inconsistency of [S3] caused by the [eventual consistency] model, - **fault tolerance**: any component of Secor is allowed to crash at any given point without compromising data integrity, - **load distribution**: Secor may be distributed across multiple machines, - **horizontal scalability**: scaling the system out to handle more load is as easy as starting extra Secor processes. Reducing the resource footprint can be achieved by killing any of the running Secor processes. Neither ramping up nor down has any impact on data consistency, - **output partitioning**: Secor parses incoming messages and puts them under partitioned s3 paths to enable direct import into systems like [Hive]. day,hour,minute level partitions are supported by secor - **configurable upload policies**: commit points controlling when data is persisted in S3 are configured through size-based and time-based policies (e.g., upload data when local buffer reaches size of 100MB and at least once per hour), - **monitoring**: metrics tracking various performance properties are exposed through [Ostrich], [Micrometer] and optionally exported to [OpenTSDB] / [statsD], - **customizability**: external log message parser may be loaded by updating the configuration, - **event transformation**: external message level transformation can be done by using customized class. - **Qubole interface**: Secor connects to [Qubole] to add finalized output partitions to Hive tables. ## Release Notes Release Notes for past versions can be found in [RELEASE.md](RELEASE.md). ## Setup/Configuration Guide Setup/Configuration instruction is available in [README.setup.md](README.setup.md). ### Secor configuration for Kubernetes/GKE environment Extra Setup instruction for Kubernetes/GKE environment is available in [README.kubernetes.md](README.kubernetes.md). ## Detailed design Design details are available in [DESIGN.md](DESIGN.md). ## License Secor is distributed under [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). ## Maintainers * [Pawel Garbacki](https://github.com/pgarbacki) * [Henry Cai](https://github.com/HenryCaiHaiying) ## Contributors * [Andy Kramolisch](https://github.com/andykram) * [Brenden Matthews](https://github.com/brndnmtthws) * [Lucas Zago](https://github.com/zago) * [James Green](https://github.com/jfgreen) * [Praveen Murugesan](https://github.com/lefthandmagic) * [Zack Dever](https://github.com/zackdever) * [Leo Woessner](https://github.com/estezz) * [Jerome Gagnon](https://github.com/jgagnon1) * [Taichi Nakashima](https://github.com/tcnksm) * [Lovenish Goyal](https://github.com/lovenishgoyal) * [Ahsan Nabi Dar](https://github.com/ahsandar) * [Ashish Kumar](https://github.com/ashubhumca) * [Ashwin Sinha](https://github.com/tygrash) * [Avi Chad-Friedman](https://github.com/achad4) ## Companies who use Secor * [Airbnb](https://www.airbnb.com) * [Appsflyer](https://www.appsflyer.com) * [Branch](http://branch.io) * [Coupang](https://www.coupang.com) * [Credit Karma](https://www.creditkarma.com) * [GO-JEK](http://gojekengineering.com/) * [Nextperf](http://www.nextperf.com) * [PayTM](https://www.paytm.com) * [Pinterest](https://www.pinterest.com) * [Rakuten](http://techblog.rakuten.co.jp/) * [Robinhood](http://www.robinhood.com/) * [Simplaex](https://www.simplaex.com/) * [Skyscanner](http://www.skyscanner.net) * [Strava](https://www.strava.com) * [TiVo](https://www.tivo.com) * [VarageSale](http://www.varagesale.com) * [Viacom](http://www.viacom.com) * [Wego](https://www.wego.com) * [Yelp](http://www.yelp.com) * [Zalando](http://www.zalando.com) * [Zapier](https://www.zapier.com) ## Help If you have any questions or comments, you can reach us at [secor-users@googlegroups.com](https://groups.google.com/forum/#!forum/secor-users) [Kafka]:http://kafka.apache.org/ [Amazon S3]:http://aws.amazon.com/s3/ [Microsoft Azure Blob Storage]:https://azure.microsoft.com/en-us/services/storage/blobs/ [S3]:http://aws.amazon.com/s3/ [Google Cloud Storage]:https://cloud.google.com/storage/ [eventual consistency]:http://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyMode [Hive]:http://hive.apache.org/ [Ostrich]: https://github.com/twitter/ostrich [Micrometer]: https://micrometer.io [OpenTSDB]: http://opentsdb.net/ [Qubole]: http://www.qubole.com/ [statsD]: https://github.com/etsy/statsd/ [Openstack Swift]: http://swift.openstack.org [Protocol Buffers]: https://developers.google.com/protocol-buffers/ [Parquet]: https://parquet.apache.org/
0
SherlockGougou/BigImageViewPager
🔥🔥🔥 BigImage ImageView ViewPager 支持超长图、超大图的图片浏览器,优化内存,支持手势放大、下拉关闭、查看原图、加载百分比、保存图片等功能。
2018-05-21T10:11:44Z
null
<img src="https://yitaoyitao.oss-cn-qingdao.aliyuncs.com/app/img/temp/test/cover.png"/> ### BigImage + ImageView + ViewPager = BigImageViewPager BigImageViewPager是一个图片浏览器框架,支持超大图、超长图、动图,支持手势,支持查看原图、下载、加载百分比进度显示。采用区块复用加载,优化内存占用,有效避免OOM。 ### 注意:本框架支持网络图片、本地图片、支持gif动图、支持Android 13。 # 推荐扫描二维码进行安装体验: <p align="center"> <img src="https://www.pgyer.com/app/qrcode/bigimageviewpager" width="200"/> <img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/bfd23ce0042e431bb200d7e5e2fca87d~tplv-k3u1fbpfcp-zoom-1.image" width="200"/> </p> <p align="center"> <img src="https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a045eaa577834b00a345b409b81826f8~tplv-k3u1fbpfcp-watermark.image" width="200"/> <img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/a0a1125f397b46619c9beea59691eaf5~tplv-k3u1fbpfcp-watermark.image" width="200"/> <img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/414c415380f742c4918c4b705ffc2f4f~tplv-k3u1fbpfcp-watermark.image" width="200"/> <img src="https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/ffb4cfcbaecf43488d7ae671c7c02d3d~tplv-k3u1fbpfcp-watermark.image" width="200"/> </p> ## ⭐️⭐️Star数量曲线⭐️⭐️ [![Star History Chart](https://api.star-history.com/svg?repos=SherlockGougou/BigImageViewPager&type=Date)](https://star-history.com/#SherlockGougou/BigImageViewPager&Date) # 用法 ### 一、添加依赖 #### Step 1. 在你project层级的build.gradle中,添加仓库地址: ``` allprojects { repositories { ... maven { url 'https://jitpack.io' } } } ``` #### Step 2. 在你主module的build.gradle中添加依赖: ``` dependencies { // 添加本框架 BigImageViewPager https://github.com/SherlockGougou/BigImageViewPager // 此处展示的是最新版本 implementation 'com.github.SherlockGougou:BigImageViewPager:androidx-7.3.0' // 另外还需要依赖 glide implementation 'com.github.bumptech.glide:glide:4.11.0' implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0' // 下面两个根据自己的语言二选一: // 纯java用户: annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0' // 纯kotlin、或者kotlin、java混编用户: kapt 'com.github.bumptech.glide:compiler:4.11.0' } ``` #### Step 3. 在你的主module里,添加自定义AppGlideModule。你需要继承AppGlideModule并添加以下代码到对应的重载方法中,例如: ``` @GlideModule public class MyAppGlideModule extends AppGlideModule { @Override public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) { super.registerComponents(context, glide, registry); // 替换底层网络框架为okhttp3,这步很重要!如果不添加会无法正常显示原图的加载百分比,或者卡在1% // 如果你的app中已经存在了自定义的GlideModule,你只需要把这一行代码,添加到对应的重载方法中即可。 registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(ProgressManager.getOkHttpClient())); } } ``` #### Step 4. 以上操作完成后,请点击顶部按钮:Build->Rebuild Project,等待重建完成,至此,框架添加完成。如遇到任何问题,请附带截图提issues,我会及时回复,或添加底部QQ群,进行交流。 ## 二、调用方式 #### 1:生成图片源:(如果你有缩略图和原图两种路径,请使用下面的方式,进行图片List的生成;如果你是本地图片或者没有原图缩略图之分,可以跳过这一步) ``` ImageInfo imageInfo; final List<ImageInfo> imageInfoList = new ArrayList<>(); for (String image : images) { imageInfo = new ImageInfo(); imageInfo.setOriginUrl(url);// 原图url imageInfo.setThumbnailUrl(thumbUrl);// 缩略图url imageInfoList.add(imageInfo); } ``` #### 2:最简单的调用方式: ``` // 最简单的调用,即可实现大部分需求,如需定制,可参考下一步的自定义代码: ImagePreview .getInstance() // 上下文,必须是activity,不需要担心内存泄漏,本框架已经处理好; .setContext(MainActivity.this) // 设置从第几张开始看(索引从0开始) .setIndex(0) //================================================================================================= // 有三种设置数据集合的方式,根据自己的需求进行三选一: // 1:第一步生成的imageInfo List .setImageInfoList(imageInfoList) // 2:直接传url List //.setImageList(List<String> imageList) // 3:只有一张图片的情况,可以直接传入这张图片的url //.setImage(String image) //================================================================================================= // 开启预览 .start(); // 默认配置为: // 显示顶部进度指示器、 // 显示右侧下载按钮、 // 隐藏关闭按钮、 // 开启点击图片关闭、 // 开启下拉图片关闭、 // 加载策略为全自动 ``` ##### 接口说明: 方法名 | 功能 | 说明 -|-|- |setBigImageClickListener|设置图片点击事件|默认null| |setBigImageLongClickListener|设置图片长按事件|默认null| |setBigImagePageChangeListener|设置页面切换监听|默认null| |setDownloadClickListener|设置点击下载监听|默认null,可选是否拦截下载行为| |setDownloadListener|设置下载过程toast|不设置时使用默认toast| |setCloseIconResId|设置关闭按钮的Drawable资源id|默认内置R.drawable.ic_action_close| |setContext|设置上下文|不允许为空| |setDownIconResId|设置下载按钮的Drawable资源id|R.drawable.icon_download_new| |setEnableClickClose|设置是否开启点击图片退出|默认true| |setEnableDragClose|设置是否开启下拉图片退出|默认true| |setEnableUpDragClose|设置是否开启上拉图片退出|默认false| |setEnableDragCloseIgnoreScale|是否忽略缩放启用拉动关闭|默认true| |setErrorPlaceHolder|设置加载失败的占位图资源id|默认内置R.drawable.load_failed| |setFolderName|设置下载到的文件夹名称|默认保存Picture文件夹中| |setImage|设置单张图片地址|三选一| |setImageInfoList|设置图片Bean集合|三选一| |setImageList|设置图片地址集合|三选一| |setIndex|设置开始的索引|从0开始| |setLoadStrategy|设置加载策略|详见加载策略说明| |setLongPicDisplayMode|设置长图的展示模式|默认缩小展示,可选宽度撑满| |setOnOriginProgressListener|设置原图加载进度回调|加载原图的百分比进度| |setProgressLayoutId|自定义百分比布局|详细见demo| |setShowCloseButton|设置是否显示关闭按钮|默认false,不显示| |setShowDownButton|设置是否显示下载按钮|默认true,显示| |setShowIndicator|设置是否显示顶部的进度指示器|默认true,显示| |setIndicatorShapeResId|设置顶部指示器背景shape|默认自带灰色圆角shape,设置为0时不显示背景| |setShowErrorToast|设置是否显示加载失败的Toast|默认false,不显示| |setZoomTransitionDuration|设置图片缩放动画时长|默认200ms| |setPreviewLayoutResId|设置自定义的预览页面布局id|默认R.layout.sh_layout_preview| |setOnPageFinishListener|页面关闭回调|默认null| |finish|关闭页面|自主控制关闭页面| |start|开启看图|最后调用| ##### 3:自定义多种配置: 请参考Demo:https://github.com/SherlockGougou/BigImageViewPager/blob/master/sample/src/main/java/cc/shinichi/bigimageviewpager/MainActivity.java#L299 ##### 4:加载策略介绍 ``` public enum LoadStrategy { /** * 仅加载原图;会强制隐藏查看原图按钮 */ AlwaysOrigin, /** * 仅加载普清;会强制隐藏查看原图按钮 */ AlwaysThumb, /** * 根据网络自适应加载,WiFi原图,流量普清;会强制隐藏查看原图按钮 */ NetworkAuto, /** * 手动模式:默认普清,点击按钮再加载原图;会根据原图、缩略图url是否一样来判断是否显示查看原图按钮 */ Default /** * 全自动模式:WiFi原图,流量下默认普清,可点击按钮查看原图 */ Auto } 注:以上所有方式,如果原图缓存存在的情况,会默认加载原图缓存保证清晰度;且原图缓存只要存在,就不会显示查看原图按钮。 ``` ##### 5:完全自定义预览界面布局: 详细操作请参考Demo:https://github.com/SherlockGougou/BigImageViewPager/blob/master/sample/src/main/java/cc/shinichi/bigimageviewpager/MainActivity.java#L470 ##### 6:Q&A 1.查看原图卡在1%? 答:请仔细查看以上第三步的操作。 # GitHub源码 https://github.com/SherlockGougou/BigImageViewPager # 致谢 - 本框架核心是开源作者 [davemorrissey](https://github.com/davemorrissey) 的 [subsampling-scale-image-view](https://github.com/davemorrissey/subsampling-scale-image-view),在此感谢他的付出! 对原作感兴趣的,可以去研究学习 ---> [传送门点我](https://github.com/davemorrissey/subsampling-scale-image-view) - okhttp 进度监听部分代码,借鉴使用了[GlideImageView](https://github.com/sunfusheng/GlideImageView),在此对其表示感谢,喜欢其作品的可以移步去查看学习 # Bug反馈、增加需求,加 QQ 交流群 <p align="center"> <img src="https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/17de72a7d15445f3b9a9591647af3c9b~tplv-k3u1fbpfcp-watermark.image" width="200"/> </p> # 如果有帮助到你,欢迎请我喝杯☕️: <p align="center"> <img src="https://github.com/SherlockGougou/BigImageViewPager/assets/17920617/ad358723-6c5c-4878-81b9-ec77b17cda09" width="400"/> <img src="https://github.com/SherlockGougou/BigImageViewPager/assets/17920617/507f28d2-c5d0-449c-bbe6-a5e022484130" width="400"/> </p> # LICENSE ``` Copyright (C) 2018 SherlockGougou qinglingou@gmail.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. ```
0
torakiki/pdfsam
PDFsam, a desktop application to split, merge, mix, rotate PDF files and extract pages
2013-09-24T11:06:13Z
null
PDFsam (PDF Split And Merge) ============================== Official SCM repository for PDFsam Basic, a free and open source, multi-platform software designed to extract pages, split, merge, mix and rotate PDF files. ![Build Status](https://github.com/torakiki/pdfsam/actions/workflows/build.yml/badge.svg) [![License](http://img.shields.io/badge/license-AGPLv3-blue.svg)](http://www.gnu.org/licenses/agpl-3.0.html) ![](pdfsam-docs/graphics/pdfsam-merge.gif) Where ------------------- Official website [pdfsam.org](https://pdfsam.org/ "PDFsam") License ------------------- Since version 3 PDFsam Basic is open source under the [GNU Affero General Public License], previous versions are released under GPLv2. Requirements ------------------- PDFsam Basic is written using JavaFX. Since version 4 it is released as a self-contained application and bundles a jlinked JDK while version 3 requires a Java Runtime Environment 8 with JavaFx installed in order to run. Documentation ------------------- Some [documentation](https://pdfsam.org/documentation/) and [FAQ](https://pdfsam.org/faq/) Build ------------------- This is a [simple guide](https://github.com/torakiki/pdfsam/wiki/Build-and-run) that can help you to build PDFsam Basic Contribute ------------------ Contributes are more then welcome, just please make sure you first read the [contributing guidelines](CONTRIBUTING.md) Translations ------------------ If you want to contribute translating PDFsam to your language you can do it [here](https://translations.launchpad.net/pdfsam/pdfsam-v3) Tips and tweaks ------------------ A list of properties and arguments that can tweak PDFsam behavior can be found [here](https://github.com/torakiki/pdfsam/wiki/Properties-and-arguments) [GNU Affero General Public License]: http://www.gnu.org/licenses/agpl-3.0.html
0
dcm4che/dcm4che
DICOM Implementation in JAVA
2010-09-15T11:13:55Z
null
dcm4che DICOM Toolkit & Library =============================== Sources: https://github.com/dcm4che/dcm4che Binaries: https://sourceforge.net/projects/dcm4che/files/dcm4che3 Issue Tracker: https://github.com/dcm4che/dcm4che/issues Build Status: [![Build](https://github.com/dcm4che/dcm4che/actions/workflows/build.yml/badge.svg)](https://github.com/dcm4che/dcm4che/actions/workflows/build.yml) This is a complete rewrite of [dcm4che-2.x](http://www.dcm4che.org/confluence/display/d2/). One main focus was to minimize the memory footprint of the DICOM data sets. It already provides modules to store/fetch configuration data to/from LDAP, compliant to the DICOM Application Configuration Management Profile, specified in [DICOM PS 3.15](http://dicom.nema.org/medical/dicom/current/output/html/part15.html#chapter_H), Annex H. dcm4che uses a native library for the compression and decompression of images. Here is the list of supported systems and architectures: | System | Architecture | Package | Requirement | |:--------|:-------------|:---------------|:-----------------------| | Linux | x86 64-bit | linux-x86-64 | GLIBC_2.17 | | Linux | ARM 64-bit | linux-aarch64 | GLIBC_2.27 | | Linux | ARM 32-bit | linux-armv7a | GLIBC_2.28 | | Windows | x86 64-bit | windows-x86-64 | Windows 7 or higher | | Windows | x86 32-bit | windows-x86 | Windows 7 or higher | | Mac OS | x86 64-bit | macosx-x86-64 | Mac OS 10.13 or higher | | Mac OS | ARM 64-bit | macosx-aarch64 | Mac OS 11 or higher | Build ----- Make sure you have Java 17 (JDK) or newer installed. Run the [Maven Wrapper](https://maven.apache.org/wrapper/) script for building: ./mvnw install or on Windows: .\mvnw install Modules ------- - dcm4che-audit - dcm4che-audit-keycloak - dcm4che-conf - dcm4che-conf-api - dcm4che-conf-api-hl7 - dcm4che-conf-json - dcm4che-conf-json-schema - dcm4che-conf-ldap - dcm4che-conf-ldap-audit - dcm4che-conf-ldap-hl7 - dcm4che-conf-ldap-imageio - dcm4che-conf-ldap-schema - dcm4che-core - dcm4che-dcmr - dcm4che-deident - dcm4che-dict - dcm4che-dict-priv - dcm4che-emf - dcm4che-hl7 - dcm4che-image - dcm4che-imageio - dcm4che-imageio-opencv - dcm4che-imageio-rle - dcm4che-js-dict - dcm4che-json - dcm4che-mime - dcm4che-net - dcm4che-net-audit - dcm4che-net-hl7 - dcm4che-net-imageio - dcm4che-soundex - dcm4che-ws-rs - dcm4che-xdsi - dcm4che-jboss-modules Utilities --------- - [agfa2dcm][]: Extract DICOM files from Agfa BLOB file - [agfa2sr][]: Extract concatenated XML Agfa Reports and convert them to DICOM SR Documents - [dcm2dcm][]: Transcode DICOM file according the specified Transfer Syntax - [dcm2jpg][]: Convert DICOM image to JPEG or other image formats - [dcm2json][]: Convert DICOM file in JSON presentation - [dcm2pdf][]: Extract encapsulated PDF, CDA or STL from DICOM file - [dcm2str][]: Apply Attributes Format Pattern to dicom file or command line parameters. - [dcm2xml][]: Convert DICOM file in XML presentation - [dcmbenchmark][]: Parse a DICOM file repetitively, measuring time and used memory - [dcmdir][]: Dump, create or update DICOMDIR file - [dcmdump][]: Dump DICOM file in textual form - [dcmldap][]: Insert/remove configuration entries for Network AEs into/from LDAP server - [dcmqrscp][]: Simple DICOM archive - [dcmvalidate][]: Validate DICOM object according a specified Information Object Definition - [deidentify][]: De-identify one or several DICOM files - [emf2sf][]: Convert DICOM Enhanced Multi-frame image to legacy DICOM Single-frame images - [findscu][]: Invoke DICOM C-FIND Query Request - [fixlo2un][]: Fixes length of private tags truncated to 2 bytes on conversion from implicit VR to explicit VR Transfer Syntax - [getscu][]: Invoke DICOM C-GET Retrieve Request - [hl72xml][]: Convert HL7 v2.x message in XML presentation - [hl7pdq][]: Query HL7 v2.x Patient Demographics Supplier - [hl7pix][]: Query HL7 v2.x PIX Manager - [hl7rcv][]: HL7 v2.x Receiver - [hl7snd][]: Send HL7 v2.x message - [ianscp][]: DICOM Instance Availability Notification receiver - [ianscu][]: Send DICOM Instance Availability Notification - [jpg2dcm][]: Convert JPEG images or MPEG videos in DICOM files - [json2dcm][]: Converts JSON file to DICOM file - [json2index][]: Creates search index for UI configuration from JSON schema files - [json2props][]: Convert Archive configuration schema JSON files to key/value properties files and vice versa - [json2rst][]: Generate ReStructuredText files from Archive configuration schema JSON files - [maskpxdata][]: Mask information burned into the Pixel Data - [mkkos][]: Make DICOM Key Object Selection Document - [modality][]: Simulates DICOM Modality - [movescu][]: Invoke DICOM C-MOVE Retrieve request - [mppsscp][]: DICOM Modality Performed Procedure Step Receiver - [mppsscu][]: Send DICOM Modality Performed Procedure Step - [pdf2dcm][]: Convert PDF file into DICOM file - [planarconfig][]: Detects the actual planar configuration of uncompressed pixel data of color images with Photometric Interpretation RGB or YBR_FULL and optionally correct non matching values of attribute Planar Configuration of the image - [qstar][]: QStar SOAP Client to prefetch/retrieve or fetch file information of specified files - [stgcmtscu][]: Invoke DICOM Storage Commitment Request - [storescp][]: DICOM Composite Object Receiver - [storescu][]: Send DICOM Composite Objects - [stowrs][]: Send DICOM Composite Objects or Bulkdata file over Web - [stowrsd][]: STOW-RS Server - [swappxdata][]: Swaps bytes of uncompressed pixel data in DICOM files - [syslog][]: Send Syslog messages via TCP/TLS or UDP to a Syslog Receiver - [syslogd][]: Receives RFC 5424 Syslog messages via TCP/TLS or UDP - [tpl2xml][]: Converts private dictionaries present in template file(s) to xml file(s). - [upsscu][]: Invokes services of Unified Procedure Step Service Class - [wadors][]: Wado RS Client Simulator - [wadows][]: Wado WS Client Simulator - [xml2dcm][]: Create/Update DICOM file from/with XML presentation - [xml2hl7][]: Create HL7 v2.x message from XML presentation - [xroad][]: XRoad SOAP Client to query Estonia National Patient Registry for Patient Demographics [agfa2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-agfa2dcm/README.md [agfa2sr]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-agfa2sr/README.md [dcm2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2dcm/README.md [dcm2jpg]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2jpg/README.md [dcm2json]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2json/README.md [dcm2pdf]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2pdf/README.md [dcm2str]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2str/README.md [dcm2xml]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcm2xml/README.md [dcmbenchmark]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmbenchmark/README.md [dcmdir]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmdir/README.md [dcmdump]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmdump/README.md [dcmldap]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmldap/README.md [dcmqrscp]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmqrscp/README.md [dcmvalidate]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-dcmvalidate/README.md [deidentify]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-deidentify/README.md [emf2sf]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-emf2sf/README.md [findscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-findscu/README.md [fixlo2un]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-fixlo2un/README.md [getscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-getscu/README.md [hl72xml]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-hl72xml/README.md [hl7pdq]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-hl7pdq/README.md [hl7pix]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-hl7pix/README.md [hl7rcv]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-hl7rcv/README.md [hl7snd]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-hl7snd/README.md [ianscp]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-ianscp/README.md [ianscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-ianscu/README.md [jpg2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-jpg2dcm/README.md [json2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-json2dcm/README.md [json2index]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-json2index/README.md [json2props]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-json2props/README.md [json2rst]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-json2rst/README.md [maskpxdata]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-maskpxdata/README.md [mkkos]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-mkkos/README.md [modality]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-ihe/dcm4che-tool-ihe-modality/README.md [movescu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-movescu/README.md [mppsscp]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-mppsscp/README.md [mppsscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-mppsscu/README.md [pdf2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-pdf2dcm/README.md [planarconfig]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-planarconfig/README.md [qstar]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-qstar/README.md [stgcmtscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-stgcmtscu/README.md [storescp]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-storescp/README.md [storescu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-storescu/README.md [stowrs]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-stowrs/README.md [stowrsd]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-stowrsd/README.md [swappxdata]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-swappxdata/README.md [syslog]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-syslog/README.md [syslogd]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-syslogd/README.md [tpl2xml]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-tpl2xml/README.md [upsscu]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-upsscu/README.md [wadors]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-wadors/README.md [wadows]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-wadows/README.md [xml2dcm]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-xml2dcm/README.md [xml2hl7]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-xml2hl7/README.md [xroad]: https://github.com/dcm4che/dcm4che/blob/master/dcm4che-tool/dcm4che-tool-xroad/README.md License ------- * [Mozilla Public License Version 1.1](http://www.mozilla.org/MPL/1.1/)
0
itfsw/mybatis-generator-plugin
Mybatis Generator 代码生成插件拓展,增加:查询单条数据插件(SelectOneByExamplePlugin)、MySQL分页插件(LimitPlugin)、数据Model链式构建插件(ModelBuilderPlugin)、Example Criteria 增强插件(ExampleEnhancedPlugin)、Example 目标包修改插件(ExampleTargetPlugin)、批量插入插件(BatchInsertPlugin)、逻辑删除插件(LogicalDeletePlugin)、数据Model属性对应Column获取插件(ModelColumnPlugin)、存在即更新(UpsertPlugin)、Selective选择插入更新增强插件(SelectiveEnhancedPlugin)、Table增加前缀插件(TableSuffixPlugin)、自定义注释插件(CommentPlugin)、增量插件(IncrementsPlugin)、查询结果选择性返回插件(SelectSelectivePlugin)、乐观锁插件(OptimisticLockerPlugin)、LombokPlugin等拓展。
2017-01-06T07:35:23Z
null
# 这是 MyBatis Generator 插件的拓展插件包 应该说使用Mybatis就一定离不开[MyBatis Generator](https://github.com/mybatis/generator)这款代码生成插件,而这款插件自身还提供了插件拓展功能用于强化插件本身,官方已经提供了一些[拓展插件](http://www.mybatis.org/generator/reference/plugins.html),本项目的目的也是通过该插件机制来强化Mybatis Generator本身,方便和减少我们平时的代码开发量。 >因为插件是本人兴之所至所临时发布的项目(本人已近三年未做JAVA开发,代码水平请大家见谅),但基本插件都是在实际项目中经过检验的请大家放心使用,但因为项目目前主要数据库为MySQL,Mybatis实现使用Mapper.xml方式,所以代码生成时对于其他数据库和注解方式的支持未予考虑,请大家见谅。 >V1.3.x版本的测试基准基于mybatis-3.5.0,同时向下兼容V3.4.0(某些插件需要context节点配置mybatis版本信息[[issues#70](https://github.com/itfsw/mybatis-generator-plugin/issues/70)])。老版本参见分支[V1.2.x](https://github.com/itfsw/mybatis-generator-plugin/tree/V1.2); ```xml <context> <!-- 解决 批量插入插件(BatchInsertPlugin)在mybatis3.5.0以下版本无法返回自增主键的问题 指定mybatis版本,让插件指定您所使用的mybatis版本生成对应代码 --> <property name="mybatisVersion" value="3.4.0"/> </context> ``` --------------------------------------- 插件列表: * [查询单条数据插件(SelectOneByExamplePlugin)](#1-查询单条数据插件) * [MySQL分页插件(LimitPlugin)](#2-mysql分页插件) * [数据Model链式构建插件(ModelBuilderPlugin)](#3-数据model链式构建插件) * [Example Criteria 增强插件(ExampleEnhancedPlugin)](#4-example-增强插件exampleandiforderby) * [Example 目标包修改插件(ExampleTargetPlugin)](#5-example-目标包修改插件) * [批量插入插件(BatchInsertPlugin)](#6-批量插入插件) * [逻辑删除插件(LogicalDeletePlugin)](#7-逻辑删除插件) * [数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件) * [存在即更新插件(UpsertPlugin)](#9-存在即更新插件) * [Selective选择插入更新增强插件(SelectiveEnhancedPlugin)](#10-selective选择插入更新增强插件) * [~~Table增加前缀插件(TablePrefixPlugin)~~](#11-table增加前缀插件) * [~~Table重命名插件(TableRenamePlugin)~~](#12-table重命名插件) * [自定义注释插件(CommentPlugin)](#13-自定义注释插件) * [~~增量插件(IncrementsPlugin)~~](#14-增量插件) * [查询结果选择性返回插件(SelectSelectivePlugin)](#15-查询结果选择性返回插件) * [~~官方ConstructorBased配置BUG临时修正插件(ConstructorBasedBugFixPlugin)~~](#16-官方constructorbased配置bug临时修正插件) * [乐观锁插件(OptimisticLockerPlugin)](#17-乐观锁插件) * [表重命名配置插件(TableRenameConfigurationPlugin)](#18-表重命名配置插件) * [Lombok插件(LombokPlugin)](#19-Lombok插件) * [数据ModelCloneable插件(ModelCloneablePlugin)](#20-数据ModelCloneable插件) * [状态枚举生成插件(EnumTypeStatusPlugin)](#21-状态枚举生成插件) * [增量插件(IncrementPlugin)](#22-增量插件) * [Mapper注解插件(MapperAnnotationPlugin)](#23-Mapper注解插件) --------------------------------------- Maven引用: ```xml <dependency> <groupId>com.itfsw</groupId> <artifactId>mybatis-generator-plugin</artifactId> <version>1.3.10</version> </dependency> ``` --------------------------------------- MyBatis Generator 参考配置(插件依赖应该配置在mybatis-generator-maven-plugin插件依赖中[[issues#6]](https://github.com/itfsw/mybatis-generator-plugin/issues/6)) ```xml <!-- mybatis-generator 自动代码插件 --> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <!-- 配置文件 --> <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile> <!-- 允许移动和修改 --> <verbose>true</verbose> <overwrite>true</overwrite> </configuration> <dependencies> <!-- jdbc 依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <dependency> <groupId>com.itfsw</groupId> <artifactId>mybatis-generator-plugin</artifactId> <version>${mybatis.generator.plugin.version}</version> </dependency> </dependencies> </plugin> ``` --------------------------------------- gradle集成[[issues#41]](https://github.com/itfsw/mybatis-generator-plugin/issues/41)),感谢[masa-kunikata](https://github.com/masa-kunikata)提供的脚本。 ```gradle // https://gist.github.com/masa-kunikata/daaf0f51a8ab9b808f61805407e1654c buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "gradle.plugin.com.arenagod.gradle:mybatis-generator-plugin:1.4" } } apply plugin: 'java-library' apply plugin: "com.arenagod.gradle.MybatisGenerator" apply plugin: 'eclipse' sourceCompatibility = 1.8 targetCompatibility = 1.8 def mybatisGeneratorCore = 'org.mybatis.generator:mybatis-generator-core:1.3.7' def itfswMybatisGeneratorPlugin = 'com.itfsw:mybatis-generator-plugin:1.3.9' mybatisGenerator { verbose = false configFile = "config/mybatisGenerator/generatorConfig.xml" dependencies { mybatisGenerator project(':') mybatisGenerator itfswMybatisGeneratorPlugin mybatisGenerator mybatisGeneratorCore } } repositories { mavenCentral() } dependencies { compile mybatisGeneratorCore compile itfswMybatisGeneratorPlugin testCompile 'junit:junit:4.12' } def defaultEncoding = 'UTF-8' compileJava { options.encoding = defaultEncoding } compileTestJava { options.encoding = defaultEncoding } ``` --------------------------------------- ### 1. 查询单条数据插件 对应表Mapper接口增加了方法 插件: ```xml <!-- 查询单条数据插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/> ``` 使用: ```java public interface TbMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ Tb selectOneByExample(TbExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ // Model WithBLOBs 时才有 TbWithBLOBs selectOneByExampleWithBLOBs(TbExample example); } ``` ### 2. MySQL分页插件 对应表Example类增加了Mysql分页方法,limit(Integer rows)、limit(Integer offset, Integer rows)和page(Integer page, Integer pageSize) >warning: 分页默认从0开始,目前网上流行的大多数前端框架分页都是从0开始,插件保持这种方式(可通过配置startPage参数修改); 插件: ```xml <!-- MySQL分页插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin"> <!-- 通过配置startPage影响Example中的page方法开始分页的页码,默认分页从0开始 --> <property name="startPage" value="0"/> </plugin> ``` 使用: ```java public class TbExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ protected Integer offset; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ protected Integer rows; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public TbExample limit(Integer rows) { this.rows = rows; return this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public TbExample limit(Integer offset, Integer rows) { this.offset = offset; this.rows = rows; return this; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated * @project https://github.com/itfsw/mybatis-generator-plugin */ public TbExample page(Integer page, Integer pageSize) { this.offset = page * pageSize; // !!! 如果配置了startPage且不为0 // this.offset = (page - startPage) * pageSize; this.rows = pageSize; return this; } // offset 和 rows 的getter&setter // 修正了clear方法 /** * This method was generated by MyBatis Generator. * This method corresponds to the database table tb * * @mbg.generated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; rows = null; offset = null; } } public class Test { public static void main(String[] args) { this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1GreaterThan(1) .example() .limit(10) // 查询前10条 .limit(10, 10) // 查询10~20条 .page(1, 10) // 查询第2页数据(每页10条) ); } } ``` ### 3. 数据Model链式构建插件 这个是仿jquery的链式调用强化了表的Model的赋值操作 插件: ```xml <!-- 数据Model链式构建插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin"/> ``` 使用: ```java public class Test { public static void main(String[] args) { // 直接new表Model的内部Builder类,赋值后调用build()方法返回对象 Tb table = new Tb.Builder() .field1("xx") .field2("xx") .field3("xx") .field4("xx") .build(); // 或者使用builder静态方法创建Builder Tb table = Tb.builder() .field1("xx") .field2("xx") .field3("xx") .field4("xx") .build(); } } ``` ### 4. Example 增强插件(example,andIf,orderBy) * Criteria的快速返回example()方法。 * ~~Criteria链式调用增强,以前如果有按条件增加的查询语句会打乱链式查询构建,现在有了andIf(boolean ifAdd, CriteriaAdd add)方法可一直使用链式调用下去。~~ * Example增强了setOrderByClause方法,新增orderBy(String orderByClause)、orderBy(String ... orderByClauses)方法直接返回example,增强链式调用,配合数据Model属性对应Column获取插件(ModelColumnPlugin)使用效果更佳。 * 增加基于column的操作,当配置了[数据Model属性对应Column获取插件(ModelColumnPlugin)](#8-数据model属性对应column获取插件)插件时,提供column之间的比对操作。 * 增加createCriteria静态方法newAndCreateCriteria简写example的创建。 * 增加when方法(Example和Criteria都有),方便根据不同条件附加对应操作。 插件: ```xml <!-- Example Criteria 增强插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin"> <!-- 是否支持已经过时的andIf方法(推荐使用when代替),默认支持 --> <property name="enableAndIf" value="true"/> </plugin> ``` 使用: ```java public class Test { public static void main(String[] args) { // -----------------------------------example----------------------------------- // 表Example.Criteria增加了工厂方法example()支持,使用后可链式构建查询条件使用example()返回Example对象 this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1EqualTo(1) .andField2EqualTo("xxx") .example() ); // ----------------- andIf (@Deprecated 尽量使用when代替) --------------------- // Criteria增强了链式调用,现在一些按条件增加的查询条件不会打乱链式调用了 // old TbExample oldEx = new TbExample(); TbExample.Criteria criteria = oldEx .createCriteria() .andField1EqualTo(1) .andField2EqualTo("xxx"); // 如果随机数大于0.5,附加Field3查询条件 if (Math.random() > 0.5){ criteria.andField3EqualTo(2) .andField4EqualTo(new Date()); } this.tbMapper.selectByExample(oldEx); // new this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1EqualTo(1) .andField2EqualTo("xxx") // 如果随机数大于0.5,附加Field3查询条件 .andIf(Math.random() > 0.5, new TbExample.Criteria.ICriteriaAdd() { @Override public TbExample.Criteria add(TbExample.Criteria add) { return add.andField3EqualTo(2) .andField4EqualTo(new Date()); } }) // 当然最简洁的写法是采用java8的Lambda表达式,当然你的项目是Java8+ .andIf(Math.random() > 0.5, add -> add .andField3EqualTo(2) .andField4EqualTo(new Date()) ) .example() ); // -----------------------------------when----------------------------------- this.tbMapper.selectByExample( TbExample.newAndCreateCriteria() // 如果随机数大于1,附加Field3查询条件 .when(Math.random() > 1, new TbExample.ICriteriaWhen() { @Override public void criteria(TbExample.Criteria criteria) { criteria.andField3EqualTo(2); } }) // 当然最简洁的写法是采用java8的Lambda表达式,当然你的项目是Java8+ .when(Math.random() > 1, criteria -> criteria.andField3EqualTo(2)) // 也支持 if else 这种写法 .when(Math.random() > 1, criteria -> criteria.andField3EqualTo(2), criteria -> criteria.andField3EqualTo(3)) .example() // example上也支持 when 方法 .when(true, example -> example.orderBy("field1 DESC")) ); // -----------------------------------orderBy----------------------------------- // old TbExample ex = new TbExample(); ex.createCriteria().andField1GreaterThan(1); ex.setOrderByClause("field1 DESC"); this.tbMapper.selectByExample(ex); // new this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1GreaterThan(1) .example() .orderBy("field1 DESC") // 这个配合数据Model属性对应Column获取插件(ModelColumnPlugin)使用 .orderBy(Tb.Column.field1.asc(), Tb.Column.field3.desc()) ); // -----------------------------------column----------------------------------- this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1EqualToColumn(Tb.Column.field2) // where field1 = field2 .andField1NotEqualToColumn(Tb.Column.field2) // where field1 <> field2 .andField1GreaterThanColumn(Tb.Column.field2) // where field1 > field2 .andField1GreaterThanOrEqualToColumn(Tb.Column.field2) // where field1 >= field2 .andField1LessThanColumn(Tb.Column.field2) // where field1 < field2 .andField1LessThanOrEqualToColumn(Tb.Column.field2) // where field1 <= field2 .example() ); // ---------------------------- static createCriteria ----------------------- // simple this.tbMapper.selectByExample( new TbExample() .createCriteria() .example() ); // new this.tbMapper.selectByExample( TbExample.newAndCreateCriteria() .example() ); } } ``` ### 5. Example 目标包修改插件 Mybatis Generator 插件默认把Model类和Example类都生成到一个包下,这样该包下类就会很多不方便区分,该插件目的就是把Example类独立到一个新包下,方便查看。 插件: ```xml <!-- Example 目标包修改插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin"> <!-- 修改Example类生成到目标包下 --> <property name="targetPackage" value="com.itfsw.mybatis.generator.dao.example"/> </plugin> ``` ### 6. 批量插入插件 提供了批量插入batchInsert和batchInsertSelective方法,需配合数据Model属性对应Column获取插件(ModelColumnPlugin)插件使用,实现类似于insertSelective插入列! >warning: 插件生成的batchInsertSelective方法在使用时必须指定selective列,因为插件本身是预编译生成sql,对于批量数据是无法提供类似insertSelective非空插入的方式的; 插件: ```xml <!-- 批量插入插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"> <!-- 开启后可以实现官方插件根据属性是否为空决定是否插入该字段功能 !需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!插件默认不开启 --> <property name="allowMultiQueries" value="false"/> </plugin> ``` 使用: ```java public class Test { public static void main(String[] args) { // 构建插入数据 List<Tb> list = new ArrayList<>(); list.add( Tb.builder() .field1(0) .field2("xx0") .field3(0) .createTime(new Date()) .build() ); list.add( Tb.builder() .field1(1) .field2("xx1") .field3(1) .createTime(new Date()) .build() ); // 普通插入,插入所有列 this.tbMapper.batchInsert(list); // !!!下面按需插入指定列(类似于insertSelective),需要数据Model属性对应Column获取插件(ModelColumnPlugin)插件 this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime); // 或者排除某些列 this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)); } } ``` ### 7. 逻辑删除插件 因为很多实际项目数据都不允许物理删除,多采用逻辑删除,所以单独为逻辑删除做了一个插件,方便使用。 - 增加logicalDeleteByExample和logicalDeleteByPrimaryKey方法; - 增加selectByPrimaryKeyWithLogicalDelete方法([[pull#12]](https://github.com/itfsw/mybatis-generator-plugin/pull/12)); - 查询构造工具中增加逻辑删除条件andLogicalDeleted(boolean); - 数据Model增加逻辑删除条件andLogicalDeleted(boolean); - 增加逻辑删除常量IS_DELETED(已删除 默认值)、NOT_DELETED(未删除 默认值)([[issues#11]](https://github.com/itfsw/mybatis-generator-plugin/issues/11)); - 增加逻辑删除枚举; >warning: 注意在配合[状态枚举生成插件(EnumTypeStatusPlugin)](#21-状态枚举生成插件)使用时的注释格式,枚举数量必须大于等于2,且逻辑删除和未删除的值能在枚举中找到。 插件: ```xml <xml> <!-- 逻辑删除插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin"> <!-- 这里配置的是全局逻辑删除列和逻辑删除值,当然在table中配置的值会覆盖该全局配置 --> <!-- 逻辑删除列类型只能为数字、字符串或者布尔类型 --> <property name="logicalDeleteColumn" value="del_flag"/> <!-- 逻辑删除-已删除值 --> <property name="logicalDeleteValue" value="9"/> <!-- 逻辑删除-未删除值 --> <property name="logicalUnDeleteValue" value="0"/> <!-- 是否生成逻辑删除常量(只有开启时 logicalDeleteConstName、logicalUnDeleteConstName 才生效) --> <property name="enableLogicalDeleteConst" value="true"/> <!-- 逻辑删除常量名称,不配置默认为 IS_DELETED --> <property name="logicalDeleteConstName" value="IS_DELETED"/> <!-- 逻辑删除常量(未删除)名称,不配置默认为 NOT_DELETED --> <property name="logicalUnDeleteConstName" value="NOT_DELETED"/> </plugin> <table tableName="tb"> <!-- 这里可以单独表配置逻辑删除列和删除值,覆盖全局配置 --> <property name="logicalDeleteColumn" value="del_flag"/> <property name="logicalDeleteValue" value="1"/> <property name="logicalUnDeleteValue" value="-1"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // 1. 逻辑删除ByExample this.tbMapper.logicalDeleteByExample( new TbExample() .createCriteria() .andField1EqualTo(1) .example() ); // 2. 逻辑删除ByPrimaryKey this.tbMapper.logicalDeleteByPrimaryKey(1L); // 3. 同时Example中提供了一个快捷方法来过滤逻辑删除数据 this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1EqualTo(1) // 新增了一个andDeleted方法过滤逻辑删除数据 .andLogicalDeleted(true) // 当然也可直接使用逻辑删除列的查询方法,我们数据Model中定义了一个逻辑删除常量DEL_FLAG .andDelFlagEqualTo(Tb.IS_DELETED) .example() ); // 4. 逻辑删除和未删除常量 Tb tb = Tb.builder() .delFlag(Tb.IS_DELETED) // 删除 .delFlag(Tb.NOT_DELETED) // 未删除 .build() .andLogicalDeleted(true); // 也可以在这里使用true|false设置逻辑删除 // 5. selectByPrimaryKeyWithLogicalDelete V1.0.18 版本增加 // 因为之前觉得既然拿到了主键这种查询没有必要,但是实际使用中可能存在根据主键判断是否逻辑删除的情况,这种场景还是有用的 this.tbMapper.selectByPrimaryKeyWithLogicalDelete(1, true); // 6. 使用逻辑删除枚举 Tb tb = Tb.builder() .delFlag(Tb.DelFlag.IS_DELETED) // 删除 .delFlag(Tb.DelFlag.NOT_DELETED) // 未删除 .build() .andLogicalDeleted(true); // 也可以在这里使用true|false设置逻辑删除 } } ``` 通过注解覆盖逻辑删除配置 ```sql CREATE TABLE `tb` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1', `del_flag` smallint(3) COMMENT '注释[enable(1):第一项必须是代表未删除, disable(0):第二项必须是代表已删除, other(2):当然还可以附加其他状态]', PRIMARY KEY (`id`) ); ``` ```java /** * 生成的Tb会根据注释覆盖逻辑删除配置 */ public class Tb { public static final Short ENABLE = DelFlag.ENABLE.value(); public static final Short DISABLE = DelFlag.DISABLE.value(); public enum DelFlag { ENABLE(new Short("1"), "第一项必须是代表未删除"), DISABLE(new Short("0"), "第二项必须是代表已删除"), OTHER(new Short("2"), "当然还可以附加其他状态"); private final Short value; private final String name; DelFlag(Short value, String name) { this.value = value; this.name = name; } public Short getValue() { return this.value; } public Short value() { return this.value; } public String getName() { return this.name; } } } ``` ### 8. 数据Model属性对应Column获取插件 项目中我们有时需要获取数据Model对应数据库字段的名称,一般直接根据数据Model的属性就可以猜出数据库对应column的名字,可是有的时候当column使用了columnOverride或者columnRenamingRule时就需要去看数据库设计了,所以提供了这个插件获取model对应的数据库Column。 * 配合Example Criteria 增强插件(ExampleEnhancedPlugin)使用,这个插件还提供了asc()和desc()方法配合Example的orderBy方法效果更佳。 * 配合批量插入插件(BatchInsertPlugin)使用,batchInsertSelective(@Param("list") List<XXX> list, @Param("selective") XXX.Column ... insertColumns)。 * 提供静态excludes方法来进行快速反选。 插件: ```xml <!-- 数据Model属性对应Column获取插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/> ``` 使用: ```java public class Test { public static void main(String[] args) { // 1. 获取Model对应column String column = Tb.Column.createTime.value(); // 2. 配合Example Criteria 增强插件(ExampleEnhancedPlugin)使用orderBy方法 // old this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1GreaterThan(1) .example() .orderBy("field1 DESC, field3 ASC") ); // better this.tbMapper.selectByExample( new TbExample() .createCriteria() .andField1GreaterThan(1) .example() .orderBy(Tb.Column.field1.desc(), Tb.Column.field3.asc()) ); // 3. 配合批量插入插件(BatchInsertPlugin)使用实现按需插入指定列 List<Tb> list = new ArrayList<>(); list.add( Tb.builder() .field1(0) .field2("xx0") .field3(0) .field4(new Date()) .build() ); list.add( Tb.builder() .field1(1) .field2("xx1") .field3(1) .field4(new Date()) .build() ); // 这个会插入表所有列 this.tbMapper.batchInsert(list); // 下面按需插入指定列(类似于insertSelective) this.tbMapper.batchInsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime); // 4. excludes 方法 this.tbMapper.batchInsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)); // 5. all 方法 this.tbMapper.batchInsertSelective(list, Tb.Column.all()); } } ``` ### 9. 存在即更新插件 1. 使用MySQL的[“insert ... on duplicate key update”](https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html)实现存在即更新操作,简化数据入库操作([[issues#2]](https://github.com/itfsw/mybatis-generator-plugin/issues/2))。 2. 在开启allowMultiQueries=true(默认不会开启)情况下支持upsertByExample,upsertByExampleSelective操作,但强力建议不要使用(需保证团队没有使用statement提交sql,否则会存在sql注入风险)([[issues#2]](https://github.com/itfsw/mybatis-generator-plugin/issues/2))。 插件: ```xml <!-- 存在即更新插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin"> <!-- 支持upsertByExample,upsertByExampleSelective操作 !需开启allowMultiQueries=true多条sql提交操作,所以不建议使用!插件默认不开启 --> <property name="allowMultiQueries" value="false"/> <!-- 开启批量功能,支持batchUpsert,batchUpsertWithBLOBs,batchUpserSelective !这几个方法中无法支持IncrementsPlugin的方法!插件默认不开启 --> <property name="allowBatchUpsert" value="fasle"/> </plugin> ``` 使用: ```java public class Test { public static void main(String[] args) { // 1. 未入库数据入库,执行insert Tb tb = Tb.builder() .field1(1) .field2("xx0") .delFlag(Tb.DEL_FLAG_ON) .build(); int k0 = this.tbMapper.upsert(tb); // 2. 已入库数据再次入库,执行update(!!需要注意如触发update其返回的受影响行数为2) tb.setField2("xx1"); int k1 = this.tbMapper.upsert(tb); // 3. 类似insertSelective实现选择入库 Tb tb1 = Tb.builder() .field1(1) .field2("xx0") .build(); int k2 = this.tbMapper.upsertSelective(tb1); tb1.setField2("xx1"); int k3 = this.tbMapper.upsertSelective(tb1); // --------------------------------- allowMultiQueries=true ------------------------------ // 4. 开启allowMultiQueries后增加upsertByExample,upsertByExampleSelective但强力建议不要使用(需保证团队没有使用statement提交sql,否则会存在sql注入风险) Tb tb2 = Tb.builder() .field1(1) .field2("xx0") .field3(1003) .delFlag(Tb.DEL_FLAG_ON) .build(); int k4 = this.tbMapper.upsertByExample(tb2, new TbExample() .createCriteria() .andField3EqualTo(1003) .example() ); tb2.setField2("xx1"); // !!! upsertByExample,upsertByExampleSelective触发更新时,更新条数返回是有问题的,这里只会返回0 // 这是mybatis自身问题,也是不怎么建议开启allowMultiQueries功能原因之一 int k5 = this.tbMapper.upsertByExample(tb2, new TbExample() .createCriteria() .andField3EqualTo(1003) .example() ); // upsertByExampleSelective 用法类似 // 当Model WithBLOBs 存在时上述方法增加对应的 WithBLOBs 方法,举例如下: TbWithBLOBs tb3 = Tb.builder() .field1(1) .field2("xx0") .delFlag(Tb.DEL_FLAG_ON) .build(); int k6 = this.tbMapper.upsertWithBLOBs(tb); // --------------------------------- allowBatchUpsert=true ------------------------------ List<Tb> list = new ArrayList<>(); list.add( Tb.builder() .field1(0) .field2("xx0") .field3(0) .field4(new Date()) .build() ); list.add( Tb.builder() .field1(1) .field2("xx1") .field3(1) .field4(new Date()) .build() ); this.tbMapper.batchUpsert(list); // 对于BLOBs 有batchUpsertWithBLOBs方法 this.tbMapper.batchUpsertSelective(list, Tb.Column.field1, Tb.Column.field2, Tb.Column.field3, Tb.Column.createTime); this.tbMapper.batchUpsertSelective(list, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)); // 排除某些列 } } ``` ### 10. Selective选择插入更新增强插件 项目中往往需要指定某些字段进行插入或者更新,或者把某些字段进行设置null处理,这种情况下原生xxxSelective方法往往不能达到需求,因为它的判断条件是对象字段是否为null,这种情况下可使用该插件对xxxSelective方法进行增强。 >warning: 以前老版本(1.1.x)插件处理需要指定的列时是放入Model中指定的,但在实际使用过程中有同事反馈这个处理有点反直觉,导致某些新同事不能及时找到对应方法,而且和增强的SelectSelectivePlugin以及UpsertSelective使用方式都不一致,所以统一修改之。 插件: ```xml <!-- Selective选择插入更新增强插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin"/> ``` 使用: ```java public class Test { public static void main(String[] args) { // ------------------------------ 新版本(SelectiveEnhancedPlugin)-------------------------------- // 1. 指定插入或更新字段 Tb tb = Tb.builder() .field1(1) .field2("xx2") .field3(1) .createTime(new Date()) .build(); // 只插入或者更新field1,field2字段 this.tbMapper.insertSelective(tb, Tb.Column.field1, Tb.Column.field2); this.tbMapper.updateByExampleSelective( tb, new TbExample() .createCriteria() .andIdEqualTo(1l) .example(), Tb.Column.field1, Tb.Column.field2 ); this.tbMapper.updateByPrimaryKeySelective(tb, Tb.Column.field1, Tb.Column.field2); this.tbMapper.upsertSelective(tb, Tb.Column.field1, Tb.Column.field2); this.tbMapper.upsertByExampleSelective( tb, new TbExample() .createCriteria() .andField3EqualTo(1) .example(), Tb.Column.field1, Tb.Column.field2 ); // 2. 更新某些字段为null this.tbMapper.updateByPrimaryKeySelective( Tb.builder() .id(1l) .field1(null) // 方便展示,不用设也可以 .build(), Tb.Column.field1 ); // 3. 排除某些列 this.tbMapper.insertSelective(tb, Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag)); } } ``` ### 11. Table增加前缀插件 项目中有时会遇到配置多数据源对应多业务的情况,这种情况下可能会出现不同数据源出现重复表名,造成异常冲突。 该插件允许为表增加前缀,改变最终生成的Model、Mapper、Example类名以及xml名。 >warning: 使用[Table重命名插件](12-table重命名插件)可以实现相同功能! >warning: 官方最新版本中已提供domainObjectRenamingRule支持(可以配合[表重命名配置插件](#18-表重命名配置插件)进行全局配置)! ```xml <table tableName="tb"> <domainObjectRenamingRule searchString="^" replaceString="DB1" /> </table> ``` 插件: ```xml <xml> <!-- Table增加前缀插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.TablePrefixPlugin"> <!-- 这里配置的是全局表前缀,当然在table中配置的值会覆盖该全局配置 --> <property name="prefix" value="Cm"/> </plugin> <table tableName="tb"> <!-- 这里可以单独表配置前缀,覆盖全局配置 --> <property name="suffix" value="Db1"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // Tb 表对应的Model、Mapper、Example类都增加了Db1的前缀 // Model类名: Tb -> Db1Tb // Mapper类名: TbMapper -> Db1TbMapper // Example类名: TbExample -> Db1TbExample // xml文件名: TbMapper.xml -> Db1TbMapper.xml } } ``` ### 12. Table重命名插件 插件由来: 记得才开始工作时某个隔壁项目组的坑爹项目,由于某些特定的原因数据库设计表名为t1~tn,字段名为f1~fn。 这种情况下如何利用Mybatis Generator生成可读的代码呢,字段可以用columnOverride来替换,Model、Mapper等则需要使用domainObjectName+mapperName来实现方便辨识的代码。 >该插件解决:domainObjectName+mapperName?好吧我想简化一下,所以直接使用tableOverride(仿照columnOverride)来实现便于配置的理解。 某些DBA喜欢在数据库设计时使用t_、f_这种类似的设计([[issues#4]](https://github.com/itfsw/mybatis-generator-plugin/issues/4)), 这种情况下我们就希望能有类似[columnRenamingRule](http://www.mybatis.org/generator/configreference/columnRenamingRule.html)这种重命名插件来修正最终生成的Model、Mapper等命名。 >该插件解决:使用正则替换table生成的Model、Example、Mapper等命名。 项目中有时会遇到配置多数据源对应多业务的情况,这种情况下可能会出现不同数据源出现重复表名,造成异常冲突。 该插件可以实现和[Table增加前缀插件](11-table增加前缀插件)相同的功能,仿照如下配置。 ```xml <property name="searchString" value="^"/> <property name="replaceString" value="DB1"/> ``` >warning: 官方最新版本中已提供domainObjectRenamingRule支持(可以配合[表重命名配置插件](#18-表重命名配置插件)进行全局配置)! ```xml <table tableName="tb"> <domainObjectRenamingRule searchString="^T" replaceString="" /> </table> ``` 插件: ```xml <xml> <!-- Table重命名插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.TableRenamePlugin"> <!-- 可根据具体需求确定是否配置 --> <property name="searchString" value="^T"/> <property name="replaceString" value=""/> </plugin> <table tableName="tb"> <!-- 这个优先级最高,会忽略searchString、replaceString的配置 --> <property name="tableOverride" value="TestDb"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // 1. 使用searchString和replaceString时,和Mybatis Generator一样使用的是java.util.regex.Matcher.replaceAll去进行正则替换 // 表: T_USER // Model类名: TUser -> User // Mapper类名: TUserMapper -> UserMapper // Example类名: TUserExample -> UserExample // xml文件名: TUserMapper.xml -> UserMapper.xml // 2. 使用表tableOverride时,该配置优先级最高 // 表: T_BOOK // Model类名: TBook -> TestDb // Mapper类名: TBookMapper -> TestDbMapper // Example类名: TBookExample -> TestDbExample // xml文件名: TBookMapper.xml -> TestDbMapper.xml } } ``` ### 13. 自定义注释插件 Mybatis Generator是原生支持自定义注释的(commentGenerator配置type属性),但使用比较麻烦需要自己实现CommentGenerator接口并打包配置赖等等。 该插件借助freemarker极佳的灵活性实现了自定义注释的快速配置。 >warning: 下方提供了一个参考模板,需要注意${mgb}的输出,因为Mybatis Generator就是通过该字符串判断是否为自身生成代码进行覆盖重写。 >warning: 请注意拷贝参考模板注释前方空格,idea等工具拷贝进去后自动格式化会造成格式错乱。 >warning: 模板引擎采用的是freemarker所以一些freemarker指令参数(如:<#if xx></#if>、${.now?string("yyyy-MM-dd HH:mm:ss")})都是可以使用的,请自己尝试。 >warning: [默认模板](https://github.com/itfsw/mybatis-generator-plugin/blob/master/src/main/resources/default-comment.ftl) | 注释ID | 传入参数 | 备注 | | ----- | ----- | ---- | | addJavaFileComment | mgb<br>[compilationUnit](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/CompilationUnit.java) | Java文件注释 | | addComment | mgb<br>[xmlElement](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/xml/XmlElement.java) | Xml节点注释 | | addRootComment | mgb<br>[rootElement](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/xml/XmlElement.java) | Xml根节点注释 | | addFieldComment | mgb<br>[field](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/Field.java)<br>[introspectedTable](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/IntrospectedTable.java)<br>[introspectedColumn](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/IntrospectedColumn.java) | Java 字段注释(非生成Model对应表字段时,introspectedColumn可能不存在) | | addModelClassComment | mgb<br>[topLevelClass](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/TopLevelClass.java)<br>introspectedTable | 表Model类注释 | | addClassComment | mgb<br>[innerClass](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/InnerClass.java)<br>introspectedTable | 类注释 | | addEnumComment | mgb<br>[innerEnum](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/InnerEnum.java)<br>introspectedTable | 枚举注释 | | addInterfaceComment | mgb<br>[innerInterface](https://github.com/itfsw/mybatis-generator-plugin/blob/master/src/main/java/com/itfsw/mybatis/generator/plugins/utils/enhanced/InnerInterface.java)<br>introspectedTable | 接口注释(itfsw插件新增类型) | | addGetterComment | mgb<br>[method](https://github.com/mybatis/generator/blob/master/core/mybatis-generator-core/src/main/java/org/mybatis/generator/api/dom/java/Method.java)<br>introspectedTable<br>introspectedColumn | getter方法注释(introspectedColumn可能不存在) | | addSetterComment | mgb<br>method<br>introspectedTable<br>introspectedColumn | setter方法注释(introspectedColumn可能不存在) | | addGeneralMethodComment | mgb<br>method<br>introspectedTable | 方法注释 | 插件: ```xml <xml> <!-- 自定义注释插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin"> <!-- 自定义模板路径 --> <property name="template" value="src/main/resources/mybatis-generator-comment.ftl" /> </plugin> </xml> ``` 使用([参考模板](https://github.com/itfsw/mybatis-generator-plugin/blob/master/src/main/resources/default-comment.ftl)): ```xml <?xml version="1.0" encoding="UTF-8"?> <template> <!-- ############################################################################################################# /** * This method is called to add a file level comment to a generated java file. This method could be used to add a * general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse * does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the * initial run. * <p> * * The default implementation does nothing. * * @param compilationUnit * the compilation unit */ --> <comment ID="addJavaFileComment"></comment> <!-- ############################################################################################################# /** * This method should add a suitable comment as a child element of the specified xmlElement to warn users that the * element was generated and is subject to regeneration. * * @param xmlElement * the xml element */ --> <comment ID="addComment"><![CDATA[ <!-- WARNING - ${mgb} This element is automatically generated by MyBatis Generator, do not modify. @project https://github.com/itfsw/mybatis-generator-plugin --> ]]></comment> <!-- ############################################################################################################# /** * This method is called to add a comment as the first child of the root element. This method could be used to add a * general file comment (such as a copyright notice). However, note that the XML file merge function does not deal * with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run. * <p> * * The default implementation does nothing. * * @param rootElement * the root element */ --> <comment ID="addRootComment"></comment> <!-- ############################################################################################################# /** * This method should add a Javadoc comment to the specified field. The field is related to the specified table and * is used to hold the value of the specified column. * <p> * * <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without * this tag, the Eclipse based Java merge feature will fail. * * @param field * the field * @param introspectedTable * the introspected table * @param introspectedColumn * the introspected column */ --> <comment ID="addFieldComment"><![CDATA[ <#if introspectedColumn??> /** <#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''> * Database Column Remarks: <#list introspectedColumn.remarks?split("\n") as remark> * ${remark} </#list> </#if> * * This field was generated by MyBatis Generator. * This field corresponds to the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ <#else> /** * This field was generated by MyBatis Generator. * This field corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ </#if> ]]></comment> <!-- ############################################################################################################# /** * Adds a comment for a model class. The Java code merger should * be notified not to delete the entire class in case any manual * changes have been made. So this method will always use the * "do not delete" annotation. * * Because of difficulties with the Java file merger, the default implementation * of this method should NOT add comments. Comments should only be added if * specifically requested by the user (for example, by enabling table remark comments). * * @param topLevelClass * the top level class * @param introspectedTable * the introspected table */ --> <comment ID="addModelClassComment"><![CDATA[ /** <#if introspectedTable.remarks?? && introspectedTable.remarks != ''> * Database Table Remarks: <#list introspectedTable.remarks?split("\n") as remark> * ${remark} </#list> </#if> * * This class was generated by MyBatis Generator. * This class corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb} do_not_delete_during_merge * @project https://github.com/itfsw/mybatis-generator-plugin */ ]]></comment> <!-- ############################################################################################################# /** * Adds the inner class comment. * * @param innerClass * the inner class * @param introspectedTable * the introspected table * @param markAsDoNotDelete * the mark as do not delete */ --> <comment ID="addClassComment"><![CDATA[ /** * This class was generated by MyBatis Generator. * This class corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb}<#if markAsDoNotDelete?? && markAsDoNotDelete> do_not_delete_during_merge</#if> * @project https://github.com/itfsw/mybatis-generator-plugin */ ]]></comment> <!-- ############################################################################################################# /** * Adds the enum comment. * * @param innerEnum * the inner enum * @param introspectedTable * the introspected table */ --> <comment ID="addEnumComment"><![CDATA[ /** * This enum was generated by MyBatis Generator. * This enum corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ ]]></comment> <!-- ############################################################################################################# /** * Adds the interface comment. * * @param innerInterface * the inner interface * @param introspectedTable * the introspected table */ --> <comment ID="addInterfaceComment"><![CDATA[ /** * This interface was generated by MyBatis Generator. * This interface corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ ]]></comment> <!-- ############################################################################################################# /** * Adds the getter comment. * * @param method * the method * @param introspectedTable * the introspected table * @param introspectedColumn * the introspected column */ --> <comment ID="addGetterComment"><![CDATA[ <#if introspectedColumn??> /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName} * * @return the value of ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ <#else> /** * This method was generated by MyBatis Generator. * This method returns the value of the field ${method.name?replace("get","")?replace("is", "")?uncap_first} * * @return the value of field ${method.name?replace("get","")?replace("is", "")?uncap_first} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ </#if> ]]></comment> <!-- ############################################################################################################# /** * Adds the setter comment. * * @param method * the method * @param introspectedTable * the introspected table * @param introspectedColumn * the introspected column */ --> <comment ID="addSetterComment"><![CDATA[ <#if introspectedColumn??> /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName} * * @param ${method.parameters[0].name} the value for ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ <#else> /** * This method was generated by MyBatis Generator. * This method sets the value of the field ${method.name?replace("set","")?uncap_first} * * @param ${method.parameters[0].name} the value for field ${method.name?replace("set","")?uncap_first} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ </#if> ]]></comment> <!-- ############################################################################################################# /** * Adds the general method comment. * * @param method * the method * @param introspectedTable * the introspected table */ --> <comment ID="addGeneralMethodComment"><![CDATA[ /** * This method was generated by MyBatis Generator. * This method corresponds to the database table ${introspectedTable.fullyQualifiedTable} * * ${mgb} * @project https://github.com/itfsw/mybatis-generator-plugin */ ]]></comment> </template> ``` ### 14. 增量插件 为更新操作生成set filedxxx = filedxxx +/- inc 操作,方便某些统计字段的更新操作,常用于某些需要计数的场景; >warning:该插件在整合LombokPlugin使用时会生成大量附加代码影响代码美观,强力建议切换到新版插件[IncrementPlugin](#22-增量插件); 插件: ```xml <xml> <!-- 增量插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.IncrementsPlugin" /> <table tableName="tb"> <!-- 配置需要进行增量操作的列名称(英文半角逗号分隔) --> <property name="incrementsColumns" value="field1,field2"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // 在构建更新对象时,配置了增量支持的字段会增加传入增量枚举的方法 Tb tb = Tb.builder() .id(102) .field1(1, Tb.Builder.Inc.INC) // 字段1 统计增加1 .field2(2, Tb.Builder.Inc.DEC) // 字段2 统计减去2 .field4(new Date()) .build(); // 更新操作,可以是 updateByExample, updateByExampleSelective, updateByPrimaryKey // , updateByPrimaryKeySelective, upsert, upsertSelective等所有涉及更新的操作 this.tbMapper.updateByPrimaryKey(tb); } } ``` ### 15. 查询结果选择性返回插件 一般我们在做查询优化的时候会要求查询返回时不要返回自己不需要的字段数据,因为Sending data所花费的时间和加大内存的占用 ,所以我们看到官方对于大数据的字段会拆分成xxxWithBLOBs的操作,但是这种拆分还是不能精确到具体列返回。 所以该插件的作用就是精确指定查询操作所需要返回的字段信息,实现查询的精确返回。 >warning: 因为采用的是resultMap进行的属性绑定(即时设置了constructorBased=true也无效,因为参数个数不一致会导致异常,该插件也会另外生成一个基于属性绑定的resultMap), 所以可能会出现list中存在null元素的问题,这个是mybatis自身机制造成的当查询出来的某行所有列都为null时不会生成对象(PS:其实这个不能算是错误,mybatis这样处理也说的通,但是在使用时还是要注意null的判断,当然如果有什么配置或者其他处理方式欢迎反馈哦)。 插件: ```xml <xml> <!-- 查询结果选择性返回插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.SelectSelectivePlugin" /> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // 查询操作精确返回需要的列 this.tbMapper.selectByExampleSelective( new TbExample() .createCriteria() .andField1GreaterThan(1) .example(), Tb.Column.field1, Tb.Column.field2 ); // 同理还有 selectByPrimaryKeySelective,selectOneByExampleSelective(SelectOneByExamplePlugin插件配合使用)方法 // 当然可以使用excludes this.tbMapper.selectByExampleSelective( new TbExample() .createCriteria() .andField1GreaterThan(1) .example(), Tb.Column.excludes(Tb.Column.id, Tb.Column.delFlag) ); } } ``` ### 16. 官方ConstructorBased配置BUG临时修正插件 当javaModelGenerator配置constructorBased=true时,如果表中只有一个column类型为“blob”时java model没有生成BaseResultMap对应的构造函数, 这个bug已经反馈给官方[issues#267](https://github.com/mybatis/generator/issues/267)。 > 官方V1.3.6版本将解决这个bug,老版本的可以使用这个插件临时修正问题。 插件: ```xml <xml> <!-- 官方ConstructorBased配置BUG临时修正插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ConstructorBasedBugFixPlugin" /> </xml> ``` ### 17. 乐观锁插件 为并发操作引入乐观锁,当发生删除或者更新操作时调用相应的WithVersion方法传入版本号,插件会在相应的查询条件上附加上版本号的检查,防止非法操作的发生。 同时在更新操作中支持自定义nextVersion或者利用sql 的“set column = column + 1”去维护版本号。 插件: ```xml <xml> <!-- 乐观锁插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.OptimisticLockerPlugin"> <!-- 是否启用自定义nextVersion,默认不启用(插件会默认使用sql的 set column = column + 1) --> <property name="customizedNextVersion" value="false"/> </plugin> <table tableName="tb"> <!-- 这里可以单独表配置,覆盖全局配置 --> <property name="customizedNextVersion" value="true"/> <!-- 指定版本列 --> <property name="versionColumn" value="version"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // ============================ 带版本号的删除更新等操作 =============================== int result = this.tbMapper.deleteWithVersionByExample( 100, // 版本号 new TbExample() .createCriteria() .andField1GreaterThan(1) .example() ); if (result == 0){ throw new Exception("没有找到数据或者数据版本号错误!"); } // 对应生成的Sql: delete from tb WHERE version = 100 and ( ( field1 > 1 ) ) // 带版本号的方法有: // deleteWithVersionByExample、deleteWithVersionByPrimaryKey、 // updateWithVersionByExampleSelective、updateWithVersionByExampleWithBLOBs、updateWithVersionByExample // updateWithVersionByPrimaryKeySelective、updateWithVersionByPrimaryKeyWithBLOBs、updateWithVersionByPrimaryKey // ============================= 使用默认版本号生成策略 =========================== this.tbMapper.updateWithVersionByPrimaryKey( 100, // 版本号 Tb.builder() .id(102) .field1("ts1") .build() ); // 对应生成的Sql: update tb set version = version + 1, field1 = 'ts1' where version = 100 and id = 102 // ============================= 使用自定义版本号生成策略 =========================== this.tbMapper.updateWithVersionByPrimaryKey( 100, // 版本号 Tb.builder() .id(102) .field1("ts1") .build() .nextVersion(System.currentTimeMillis()) // 传入nextVersion ); // 对应生成的Sql: update tb set version = 1525773888559, field1 = 'ts1' where version = 100 and id = 102 } } ``` ### 18. 表重命名配置插件 官方提供了domainObjectRenamingRule(官方最新版本已提供)、columnRenamingRule分别进行生成的表名称和对应表字段的重命名支持,但是它需要每个表单独进行配置,对于常用的如表附带前缀“t_”、字段前缀“f_”这种全局性替换会比较麻烦。 该插件提供了一种全局替换机制,当表没有单独指定domainObjectRenamingRule、columnRenamingRule时采用全局性配置。 同时插件提供clientSuffix、exampleSuffix、modelSuffix来修改对应生成的类和文件的结尾(之前issue中有用户希望能把Mapper替换成Dao)。 - 全局domainObjectRenamingRule ```xml <xml> <!-- 表重命名配置插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin"> <property name="domainObjectRenamingRule.searchString" value="^T"/> <property name="domainObjectRenamingRule.replaceString" value=""/> </plugin> <table tableName="tb"> <!-- 这里可以禁用全局domainObjectRenamingRule配置 --> <property name="domainObjectRenamingRule.disable" value="true"/> </table> <table tableName="tb_ts1"> <!-- 当然你也可以使用官方domainObjectRenamingRule的配置来覆盖全局配置 --> <domainObjectRenamingRule searchString="^Tb" replaceString="B"/> </table> </xml> ``` - 全局columnRenamingRule ```xml <xml> <!-- 表重命名配置插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin"> <!-- 需要注意,这里的正则和官方一样是比对替换都是原始表的column名称 --> <property name="columnRenamingRule.searchString" value="^f_"/> <property name="columnRenamingRule.replaceString" value="_"/> </plugin> <table tableName="tb"> <!-- 这里可以禁用全局columnRenamingRule配置 --> <property name="columnRenamingRule.disable" value="true"/> </table> <table tableName="tb_ts1"> <!-- 当然你也可以使用官方domainObjectRenamingRule的配置来覆盖全局配置 --> <columnRenamingRule searchString="^f_" replaceString="_"/> </table> </xml> ``` - clientSuffix、exampleSuffix、modelSuffix ```xml <xml> <!-- 表重命名配置插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.TableRenameConfigurationPlugin"> <!-- TbMapper -> TbDao, TbMapper.xml -> TbDao.xml --> <property name="clientSuffix" value="Dao"/> <!-- TbExmaple -> TbQuery --> <property name="exampleSuffix" value="Query"/> <!-- Tb -> TbEntity --> <property name="modelSuffix" value="Entity"/> </plugin> </xml> ``` ### 19. Lombok插件 使用Lombok的使用可以减少很多重复代码的书写,目前项目中已大量使用。 但Lombok的@Builder对于类的继承支持很不好,最近发现新版(>=1.18.2)已经提供了对@SuperBuilder的支持,所以新增该插件方便简写代码。 >warning1: @Builder注解在Lombok 版本 >= 1.18.2 的情况下才能开启,对于存在继承关系的model会自动替换成@SuperBuilder注解(目前IDEA的插件对于SuperBuilder的还不支持(作者已经安排上更新日程), 可以开启配置supportSuperBuilderForIdea使插件在遇到@SuperBuilder注解时使用ModelBuilderPlugin替代该注解)。 >warning2: 配合插件IncrementsPlugin(已不推荐使用,请使用新版[IncrementPlugin](#22-增量插件)解决该问题) 并且 @Builder开启的情况下,因为@SuperBuilder的一些限制, 插件模拟Lombok插件生成了一些附加代码可能在某些编译器上会提示错误,请忽略(Lombok = 1.18.2 已测试)。 ```xml <xml> <!-- Lombok插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.LombokPlugin"> <!-- @Data 默认开启,同时插件会对子类自动附加@EqualsAndHashCode(callSuper = true),@ToString(callSuper = true) --> <property name="@Data" value="true"/> <!-- @Builder 必须在 Lombok 版本 >= 1.18.2 的情况下开启,对存在继承关系的类自动替换成@SuperBuilder --> <property name="@Builder" value="false"/> <!-- @NoArgsConstructor 和 @AllArgsConstructor 使用规则和Lombok一致 --> <property name="@AllArgsConstructor" value="false"/> <property name="@NoArgsConstructor" value="false"/> <!-- @Getter、@Setter、@Accessors 等使用规则参见官方文档 --> <property name="@Accessors(chain = true)" value="false"/> <!-- 临时解决IDEA工具对@SuperBuilder的不支持问题,开启后(默认未开启)插件在遇到@SuperBuilder注解时会调用ModelBuilderPlugin来生成相应的builder代码 --> <property name="supportSuperBuilderForIdea" value="false"/> </plugin> </xml> ``` ### 20. 数据ModelCloneable插件 数据Model实现Cloneable接口。 ```xml <xml> <!-- 数据ModelCloneable插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.ModelCloneablePlugin"/> </xml> ``` ### 21. 状态枚举生成插件 数据库中经常会定义一些状态字段,该工具可根据约定的注释格式生成对应的枚举类,方便使用。 >warning:插件1.2.18版本以后默认开启自动扫描,根据约定注释格式自动生成对应枚举类 ```xml <xml> <!-- 状态枚举生成插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.EnumTypeStatusPlugin"> <!-- 是否开启自动扫描根据约定注释格式生成枚举,默认true --> <property name="autoScan" value="true"/> <!-- autoScan为false,这里可以定义全局需要检查生成枚举类的列名 --> <property name="enumColumns" value="type, status"/> </plugin> <table tableName="tb"> <!-- autoScan为false,也可以为单独某个table增加配置 --> <property name="enumColumns" value="user_type"/> </table> </xml> ``` >warning: 约定的注释检查规则的正则表达式如下 ```java public class EnumTypeStatusPlugin { public final static String REMARKS_PATTERN = ".*\\s*\\[\\s*(\\w+\\s*\\(\\s*[\\u4e00-\\u9fa5_\\-a-zA-Z0-9]+\\s*\\)\\s*:\\s*[\\u4e00-\\u9fa5_\\-a-zA-Z0-9]+\\s*\\,?\\s*)+\\s*\\]\\s*.*"; } ``` 使用 ```sql CREATE TABLE `tb` ( `type` smallint(3) COMMENT '注释[success(0):成功, fail(1):失败]', `status` bigint(3) COMMENT '换行的注释 [ login_success(0):登录成功, login_fail(1):登录失败 ]', `user_type` varchar(20) COMMENT '具体注释的写法是比较宽泛的,只要匹配上面正则就行 [ success ( 我是具体值 ) : 我是值的描述_我可以是中英文数字和下划线_xxx_123, fail_xx_3 (1 ) : 失败] 后面也可以跟注释' ); ``` ```java public class Tb { public enum Type { SUCCESS((short)0, "成功"), FAIL((short)1, "失败"); private final Short value; private final String name; Type(Short value, String name) { this.value = value; this.name = name; } public Short getValue() { return this.value; } public Short value() { return this.value; } public String getName() { return this.name; } public Field2 parseValue(Short value) { if (value != null) { for (Field2 item : values()) { if (item.value.equals(value)) { return item; } } } return null; } public Field2 parseName(String name) { if (name != null) { for (Field2 item : values()) { if (item.name.equals(name)) { return item; } } } return null; } } public enum Status { LOGIN_SUCCESS(0L, "登录成功"), LOGIN_FAIL(1L, "登录失败"); private final Long value; private final String name; Status(Long value, String name) { this.value = value; this.name = name; } public Long getValue() { return this.value; } public Long value() { return this.value; } public String getName() { return this.name; } public Status parseValue(Short value) { if (value != null) { for (Status item : values()) { if (item.value.equals(value)) { return item; } } } return null; } public Status parseName(String name) { if (name != null) { for (Status item : values()) { if (item.name.equals(name)) { return item; } } } return null; } } public enum UserType { SUCCESS("我是具体值", "我是值的描述_我可以是中英文数字和下划线_xxx_123"), FAIL_XX_3("1", "失败"); private final String value; private final String name; UserType(String value, String name) { this.value = value; this.name = name; } public String getValue() { return this.value; } public String value() { return this.value; } public String getName() { return this.name; } public UserType parseValue(Short value) { if (value != null) { for (UserType item : values()) { if (item.value.equals(value)) { return item; } } } return null; } public UserType parseName(String name) { if (name != null) { for (UserType item : values()) { if (item.name.equals(name)) { return item; } } } return null; } } } ``` ### 22. 增量插件 为更新操作生成set filedxxx = filedxxx +/- inc 操作,方便某些统计字段的更新操作,常用于某些需要计数的场景,需配合([ModelColumnPlugin](#8-数据model属性对应column获取插件))插件使用; 插件: ```xml <xml> <!-- 增量插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.IncrementPlugin" /> <table tableName="tb"> <!-- 配置需要进行增量操作的列名称(英文半角逗号分隔) --> <property name="incrementColumns" value="field1,field2"/> </table> </xml> ``` 使用: ```java public class Test { public static void main(String[] args) { // 在构建更新对象时,配置了增量支持的字段会增加传入增量枚举的方法 Tb tb = Tb.builder() .id(102) .field4(new Date()) .build() .increment(Tb.Increment.field1.inc(1)) // 字段1 统计增加1 .increment(Tb.Increment.field2.dec(2)); // 字段2 统计减去2 // 更新操作,可以是 updateByExample, updateByExampleSelective, updateByPrimaryKey // , updateByPrimaryKeySelective, upsert, upsertSelective等所有涉及更新的操作 this.tbMapper.updateByPrimaryKey(tb); } } ``` ### 23. Mapper注解插件 对官方的([MapperAnnotationPlugin](http://www.mybatis.org/generator/reference/plugins.html))增强,可自定义附加@Repository注解(IDEA工具对@Mapper注解支持有问题,使用@Autowired会报无法找到对应bean,附加@Repository后解决); 插件: ```xml <xml> <!-- Mapper注解插件 --> <plugin type="com.itfsw.mybatis.generator.plugins.MapperAnnotationPlugin"> <!-- @Mapper 默认开启 --> <property name="@Mapper" value="true"/> <!-- @Repository 开启后解决IDEA工具@Autowired报错 --> <property name="@Repository" value="org.springframework.stereotype.Repository"/> <!-- 其他自定义注解 --> <property name="@DS(&quot;master&quot;)" value="com.baomidou.dynamic.datasource.annotation.DS"/> </plugin> </xml> ```
0
testng-team/testng
TestNG testing framework
2010-06-28T23:10:17Z
null
[![Maven Central](https://img.shields.io/maven-central/v/org.testng/testng.svg)](https://maven-badges.herokuapp.com/maven-central/org.testng/testng) [![License](https://img.shields.io/github/license/cbeust/testng.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) [![Sonarqube tech debt](https://img.shields.io/sonar/https/sonarqube.com/org.testng:testng/tech_debt.svg?label=Sonarqube%20tech%20debt)](https://sonarqube.com/dashboard/index?id=org.testng:testng) [![Sonarqube Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=org.testng%3Atestng&metric=alert_status)](https://sonarcloud.io/dashboard?id=org.testng%3Atestng) Documentation available at [TestNG's main web site](https://testng.org). Visit [TestNG Documentation's GitHub Repo](https://github.com/testng-team/testng-team.github.io) to contribute to it. ### Release Notes * [7.10.0](https://groups.google.com/g/testng-users/c/6DmFaKUjIxY) * [7.9.0](https://groups.google.com/g/testng-users/c/nN7LkuZWO48) * [7.8.0](https://groups.google.com/g/testng-users/c/xdldK3VyU_s) * [7.7.0](https://groups.google.com/g/testng-users/c/V6jie-9uUIA) * [7.6.0](https://groups.google.com/g/testng-users/c/BAFB1vk-kok) * [7.5](https://groups.google.com/g/testng-users/c/ESLiK8xSomc) * [7.4.0](https://groups.google.com/g/testng-users/c/dwSJ04qeu8k) * [7.3.0](https://groups.google.com/forum/#!topic/testng-users/a81uaZvtEZI) * [7.1.0](https://groups.google.com/forum/#!topic/testng-users/84bYPJ1rjno) * [7.0.0](https://groups.google.com/forum/#!topic/testng-users/HKujuefBhXA) ### Need help? Before opening a new issue, did you ask your question on * [Google group](https://groups.google.com/group/testng-users) * [StackOverflow](https://stackoverflow.com/questions/tagged/testng) If you posted on both sites, please provide the link to the other question to avoid duplicating the answer. ### Are you sure it is a TestNG bug? Before posting the issue, try to reproduce the issue in [a shell window](https://testng.org/doc/documentation-main.html#running-testng). If the problem does not exist with the shell, first check if the issue exists on the bugtracker of the runner, and open an issue there first: * Eclipse :[Issues Page](https://github.com/cbeust/testng-eclipse/issues) * IntelliJ:[Issues Page](https://youtrack.jetbrains.com/issues?q=Subsystem:%20%7BJava.%20Tests.%20TestNG%7D) * Maven :[Issues Page](https://issues.apache.org/jira/browse/SUREFIRE) * Gradle :[Issues Page](https://issues.gradle.org/projects/GRADLE) ### Which version are you using? Always make sure your issue is happening on the latest TestNG version. Bug reports occurring on older versions will not be looked at quickly. ### Have you considered sending a pull request instead of filing an issue? The best way to report a bug is to provide the TestNG team with a full test case reproducing the issue. Maybe you can write a runnable test case (check the `src/test/` folder for examples) and propose it in a pull request Don't worry if the CI fails because it is the expected behavior. This pull request will be a perfect start to find the fix :) ### How to create a pull request? Refer our [Contributing](.github/CONTRIBUTING.md) section for detailed set of steps. ### We encourage pull requests that: * Add new features to TestNG (or) * Fix bugs in TestNG If your pull request involves fixing SonarQube issues then we would suggest that you please discuss this with the [TestNG-dev](https://groups.google.com/forum/#!forum/testng-dev) before you spend time working on it. ### GPG Keys #### Getting the keys Download the keys as shown below: ```bash gpg --keyserver keyserver.ubuntu.com --recv-keys 0F13D5631D6AF36D gpg: key 0F13D5631D6AF36D: "Krishnan Mahadevan (krmahadevan-key) <krishnan.mahadevan1978@gmail.com>" not changed gpg: Total number processed: 1 gpg: unchanged: 1 ``` #### Trusting the keys Trust the keys as shown below: ```bash gpg --edit-key 0F13D5631D6AF36D gpg (GnuPG) 2.4.4; Copyright (C) 2024 g10 Code GmbH This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Secret key is available. sec rsa2048/0F13D5631D6AF36D created: 2016-12-01 expires: never usage: SC trust: full validity: unknown ssb rsa2048/7295B61CC8DD9AE8 created: 2016-12-01 expires: never usage: E [ unknown] (1). Krishnan Mahadevan (krmahadevan-key) <krishnan.mahadevan1978@gmail.com> gpg> trust sec rsa2048/0F13D5631D6AF36D created: 2016-12-01 expires: never usage: SC trust: full validity: unknown ssb rsa2048/7295B61CC8DD9AE8 created: 2016-12-01 expires: never usage: E [ unknown] (1). Krishnan Mahadevan (krmahadevan-key) <krishnan.mahadevan1978@gmail.com> Please decide how far you trust this user to correctly verify other users' keys (by looking at passports, checking fingerprints from different sources, etc.) 1 = I don't know or won't say 2 = I do NOT trust 3 = I trust marginally 4 = I trust fully 5 = I trust ultimately m = back to the main menu Your decision? 5 Do you really want to set this key to ultimate trust? (y/N) y sec rsa2048/0F13D5631D6AF36D created: 2016-12-01 expires: never usage: SC trust: ultimate validity: unknown ssb rsa2048/7295B61CC8DD9AE8 created: 2016-12-01 expires: never usage: E [ unknown] (1). Krishnan Mahadevan (krmahadevan-key) <krishnan.mahadevan1978@gmail.com> Please note that the shown key validity is not necessarily correct unless you restart the program. gpg> exit Invalid command (try "help") gpg> quit ``` #### Verifying the signature 1. Download the `.asc` file from `https://repo1.maven.org/maven2/org/testng/testng/<versionGoesHere>` 2. Run the command `gpg --verify testng-<versionGoesHere>.jar.asc testng-<versionGoesHere>.jar` 3. You should see an output as below: ```bash gpg: Signature made Tue Dec 26 15:06:16 2023 IST gpg: using RSA key 0F13D5631D6AF36D gpg: checking the trustdb gpg: marginals needed: 3 completes needed: 1 trust model: pgp gpg: depth: 0 valid: 1 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 1u gpg: Good signature from "Krishnan Mahadevan (krmahadevan-key) <krishnan.mahadevan1978@gmail.com>" [ultimate] ``` For more details regarding keys please refer: * [Verifying Signature](https://infra.apache.org/release-signing.html#verifying-signature) * [How to Trust Imported GPG Keys](https://classroom.anir0y.in/post/blog-how-to-trust-imported-gpg-keys/)
0
npgall/cqengine
Ultra-fast SQL-like queries on Java collections
2015-08-23T19:27:00Z
null
[![Build Status](https://travis-ci.org/npgall/cqengine.svg?branch=master)](https://travis-ci.org/npgall/cqengine) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.googlecode.cqengine/cqengine/badge.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.googlecode.cqengine%22%20AND%20a%3Acqengine) # CQEngine - Collection Query Engine # CQEngine – Collection Query Engine – is a high-performance Java collection which can be searched with SQL-like queries, with _extremely_ low latency. * Achieve millions of queries per second, with query latencies measured in microseconds * Offload query traffic from databases - scale your application tier * Outperform databases by a factor of thousands, even on low-end hardware Supports on-heap persistence, off-heap persistence, disk persistence, and supports MVCC transaction isolation. Interesting reviews of CQEngine: * [dzone.com: Comparing the search performance of CQEngine with standard Java collections](https://dzone.com/articles/comparing-search-performance) * [dzone.com: Getting started with CQEngine: LINQ for Java, only faster](https://dzone.com/articles/getting-started-cqengine-linq) * CQEngine in the wild: [excelian.com](http://www.excelian.com/exposure-and-counterparty-limit-checking) | [gravity4.com](http://gravity4.com/welcome-gravity4-engineering-blog/) | [snapdeal.com](http://engineering.snapdeal.com/how-were-building-a-system-to-scale-for-billions-of-requests-per-day-201601/) (3-5 billion requests/day) ## The Limits of Iteration ## The classic way to retrieve objects matching some criteria from a collection, is to iterate through the collection and apply some tests to each object. If the object matches the criteria, then it is added to a result set. This is repeated for every object in the collection. Conventional iteration is hugely inefficient, with time complexity O(_n_ _t_). It can be optimized, but requires **statistical knowledge** of the makeup of the collection. [Read more: The Limits of Iteration](documentation/TheLimitsOfIteration.md) **Benchmark Sneak Peek** Even with optimizations applied to convention iteration, CQEngine can outperform conventional iteration by wide margins. Here is a graph for a test comparing CQEngine latency with iteration for a range-type query: ![quantized-navigable-index-carid-between.png](documentation/images/quantized-navigable-index-carid-between.png) * **1,116,071 queries per second** (on a single 1.8GHz CPU core) * **0.896 microseconds per query** * CQEngine is **330187.50% faster** than naive iteration * CQEngine is **325727.79% faster** than optimized iteration See the [Benchmark](documentation/Benchmark.md) wiki page for details of this test, and other tests with various types of query. --- ## CQEngine Overview ## CQEngine solves the scalability and latency problems of iteration by making it possible to build _indexes_ on the fields of the objects stored in a collection, and applying algorithms based on the rules of set theory to _reduce the time complexity_ of accessing them. **Indexing and Query Plan Optimization** * **Simple Indexes** can be added to any number of individual fields in a collection of objects, allowing queries on just those fields to be answered in O(_1_) time complexity * **Multiple indexes on the same field** can be added, each optimized for different types of query - for example equality, numerical range, string starts with etc. * **Compound Indexes** can be added which span multiple fields, allowing queries referencing several fields to also be answered in O(_1_) time complexity * **Nested Queries** are fully supported, such as the SQL equivalent of "`WHERE color = 'blue' AND(NOT(doors = 2 OR price > 53.00))`" * **Standing Query Indexes** can be added; these allow _arbitrarily complex queries_, or _nested query fragments_, to be answered in O(_1_) time complexity, regardless of the number of fields referenced. Large queries containing branches or query fragments for which standing query indexes exist, will automatically benefit from O(_1_) time complexity evaluation of their branches; in total several indexes might be used to accelerate complex queries * **Statistical Query Plan Optimization** - when several fields have suitable indexes, CQEngine will use statistical information from the indexes, to internally make a query plan which selects the indexes which can perform the query with minimum time complexity. When some referenced fields have suitable indexes and some do not, CQEngine will use the available indexes first, and will then iterate the smallest possible set of results from those indexes to filter objects for the rest of the query. In those cases time complexity will be greater than O(_1_), but usually significantly less than O(_n_) * **Iteration fallback** - if no suitable indexes are available, CQEngine will evaluate the query via iteration, using lazy evaluation. CQEngine can always evaluate every query, even if no suitable indexes are available. Queries are not coupled with indexes, so indexes can be added after the fact, to speed up existing queries * **CQEngine supports full concurrency** and expects that objects will be added to and removed from the collection at runtime; CQEngine will take care of updating all registered indexes in realtime * **Type-safe** - nearly all errors in queries result in _compile-time_ errors instead of exceptions at runtime: all indexes, and all queries, are strongly typed using generics at both object-level and field-level * **On-heap/off-heap/disk** - objects can be stored on-heap (like a conventional Java collection), or off-heap (in native memory, within the JVM process but outside the Java heap), or persisted to disk Several implementations of CQEngine's `IndexedCollection` are provided, supporting various concurrency and transaction isolation levels: * [ConcurrentIndexedCollection](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/ConcurrentIndexedCollection.html) - lock-free concurrent reads and writes with no transaction isolation * [ObjectLockingIndexedCollection](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/ObjectLockingIndexedCollection.html) - lock-free concurrent reads, and some locking of writes for object-level transaction isolation and consistency guarantees * [TransactionalIndexedCollection](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/TransactionalIndexedCollection.html) - lock-free concurrent reads, and sequential writes for full [transaction isolation](documentation/TransactionIsolation.md) using Multi-Version Concurrency Control For more details see [TransactionIsolation](documentation/TransactionIsolation.md). --- ## Complete Example ## In CQEngine applications mostly interact with [IndexedCollection](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/IndexedCollection.html), which is an implementation of [java.util.Set](http://docs.oracle.com/javase/6/docs/api/java/util/Set.html), and it provides two additional methods: * [addIndex(SomeIndex)](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/engine/QueryEngine.html#addIndex(com.googlecode.cqengine.index.Index)) allows indexes to be added to the collection * [retrieve(Query)](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/engine/QueryEngine.html#retrieve(com.googlecode.cqengine.query.Query)) accepts a [Query](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/query/Query.html) and returns a [ResultSet](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html) providing objects matching that query. `ResultSet` implements [java.lang.Iterable](http://docs.oracle.com/javase/6/docs/api/java/lang/Iterable.html), so accessing results is achieved by iterating the result set, or accessing it as a Java 8+ Stream Here is a **complete example** of how to build a collection, add indexes and perform queries. It does not discuss _attributes_, which are discussed below. **STEP 1: Create a new indexed collection** ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(); ``` **STEP 2: Add some indexes to the collection** ```java cars.addIndex(NavigableIndex.onAttribute(Car.CAR_ID)); cars.addIndex(ReversedRadixTreeIndex.onAttribute(Car.NAME)); cars.addIndex(SuffixTreeIndex.onAttribute(Car.DESCRIPTION)); cars.addIndex(HashIndex.onAttribute(Car.FEATURES)); ``` **STEP 3: Add some objects to the collection** ```java cars.add(new Car(1, "ford focus", "great condition, low mileage", Arrays.asList("spare tyre", "sunroof"))); cars.add(new Car(2, "ford taurus", "dirty and unreliable, flat tyre", Arrays.asList("spare tyre", "radio"))); cars.add(new Car(3, "honda civic", "has a flat tyre and high mileage", Arrays.asList("radio"))); ``` **STEP 4: Run some queries** Note: add import statement to your class: _`import static com.googlecode.cqengine.query.QueryFactory.*`_ * *Example 1: Find cars whose name ends with 'vic' or whose id is less than 2* Query: ```java Query<Car> query1 = or(endsWith(Car.NAME, "vic"), lessThan(Car.CAR_ID, 2)); cars.retrieve(query1).forEach(System.out::println); ``` Prints: ``` Car{carId=3, name='honda civic', description='has a flat tyre and high mileage', features=[radio]} Car{carId=1, name='ford focus', description='great condition, low mileage', features=[spare tyre, sunroof]} ``` * *Example 2: Find cars whose flat tyre can be replaced* Query: ```java Query<Car> query2 = and(contains(Car.DESCRIPTION, "flat tyre"), equal(Car.FEATURES, "spare tyre")); cars.retrieve(query2).forEach(System.out::println); ``` Prints: ``` Car{carId=2, name='ford taurus', description='dirty and unreliable, flat tyre', features=[spare tyre, radio]} ``` * *Example 3: Find cars which have a sunroof or a radio but are not dirty* Query: ```java Query<Car> query3 = and(in(Car.FEATURES, "sunroof", "radio"), not(contains(Car.DESCRIPTION, "dirty"))); cars.retrieve(query3).forEach(System.out::println); ``` Prints: ``` Car{carId=1, name='ford focus', description='great condition, low mileage', features=[spare tyre, sunroof]} Car{carId=3, name='honda civic', description='has a flat tyre and high mileage', features=[radio]} ``` Complete source code for these examples can be found [here](http://github.com/npgall/cqengine/blob/master/code/src/test/java/com/googlecode/cqengine/examples/introduction/). --- ## String-based queries: SQL and CQN dialects ## As an alternative to programmatic queries, CQEngine also has support for running string-based queries on the collection, in either SQL or CQN (CQEngine Native) format. Example of running an SQL query on a collection (full source [here](https://github.com/npgall/cqengine/blob/master/code/src/test/java/com/googlecode/cqengine/examples/parser/SQLQueryDemo.java)): ```java public static void main(String[] args) { SQLParser<Car> parser = SQLParser.forPojoWithAttributes(Car.class, createAttributes(Car.class)); IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(); cars.addAll(CarFactory.createCollectionOfCars(10)); ResultSet<Car> results = parser.retrieve(cars, "SELECT * FROM cars WHERE (" + "(manufacturer = 'Ford' OR manufacturer = 'Honda') " + "AND price <= 5000.0 " + "AND color NOT IN ('GREEN', 'WHITE')) " + "ORDER BY manufacturer DESC, price ASC"); results.forEach(System.out::println); // Prints: Honda Accord, Ford Fusion, Ford Focus } ``` Example of running a CQN query on a collection (full source [here](https://github.com/npgall/cqengine/blob/master/code/src/test/java/com/googlecode/cqengine/examples/parser/CQNQueryDemo.java)): ```java public static void main(String[] args) { CQNParser<Car> parser = CQNParser.forPojoWithAttributes(Car.class, createAttributes(Car.class)); IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(); cars.addAll(CarFactory.createCollectionOfCars(10)); ResultSet<Car> results = parser.retrieve(cars, "and(" + "or(equal(\"manufacturer\", \"Ford\"), equal(\"manufacturer\", \"Honda\")), " + "lessThanOrEqualTo(\"price\", 5000.0), " + "not(in(\"color\", GREEN, WHITE))" + ")"); results.forEach(System.out::println); // Prints: Ford Focus, Ford Fusion, Honda Accord } ``` --- ## Feature Matrix for Included Indexes ## **Legend for the feature matrix** | **Abbreviation** | **Meaning** | **Example** | |:-----------------|:------------|:------------| | **EQ** | _Equality_ | `equal(Car.DOORS, 4)` | | **IN** | _Equality, multiple values_ | `in(Car.DOORS, 3, 4, 5)` | | **LT** | _Less Than (numerical range / `Comparable`)_ | `lessThan(Car.PRICE, 5000.0)` | | **GT** | _Greater Than (numerical range / `Comparable`)_ | `greaterThan(Car.PRICE, 2000.0)` | | **BT** | _Between (numerical range / `Comparable`)_ | `between(Car.PRICE, 2000.0, 5000.0)` | | **SW** | _String Starts With_ | `startsWith(Car.NAME, "For")` | | **EW** | _String Ends With_ | `endsWith(Car.NAME, "ord")` | | **SC** | _String Contains_ | `contains(Car.NAME, "or")` | | **CI** | _String Is Contained In_ | `isContainedIn(Car.NAME, "I am shopping for a Ford Focus car")` | | **RX** | _String Matches Regular Expression_ | `matchesRegex(Car.MODEL, "Ford.*")` | | **HS** | _Has (aka `IS NOT NULL`)_ | `has(Car.DESCRIPTION)` / `not(has(Car.DESCRIPTION))` | | **SQ** | _Standing Query_ | _Can the index accelerate a query (as opposed to an attribute) to provide constant time complexity for any simple query, complex query, or fragment_ | | **QZ** | _Quantization_ | _Does the index accept a quantizer to control granularity_ | | **LP** | _LongestPrefix_ | `longestPrefix(Car.NAME, "Ford")` | Note: CQEngine also supports complex queries via **`and`**, **`or`**, **`not`**, and combinations thereof, across all indexes. **Index Feature Matrix** | <sub>**Index Type**</sub> | <sub>**EQ**</sub> | <sub>**IN**</sub> | <sub>**LT**</sub> | <sub>**GT**</sub> | <sub>**BT**</sub> | <sub>**SW**</sub> | <sub>**EW**</sub> | <sub>**SC**</sub> | <sub>**CI**</sub> | <sub>**HS**</sub> | <sub>**RX**</sub> | <sub>**SQ**</sub> | <sub>**QZ**</sub> | <sub>**LP**</sub> | |:---------------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------|:-------| | [<sub>Hash</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/hash/HashIndex.html) | ✓ | ✓ | | | | | | | | | | | ✓ | | | [<sub>Unique</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/unique/UniqueIndex.html) | ✓ | ✓ | | | | | | | | | | | | | | [<sub>Compound</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/compound/CompoundIndex.html) | ✓ | ✓ | | | | | | | | | | | ✓ | | | [<sub>Navigable</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/navigable/NavigableIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | | | ✓ | | | [<sub>PartialNavigable</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/navigable/PartialNavigableIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | | ✓ | | | | [<sub>RadixTree</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/radix/RadixTreeIndex.html) | ✓ | ✓ | | | | ✓ | | | | | | | | | | [<sub>ReversedRadixTree</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/radixreversed/ReversedRadixTreeIndex.html) | ✓ | ✓ | | | | | ✓ | | | | | | | | | [<sub>InvertedRadixTree</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/radixinverted/InvertedRadixTreeIndex.html) | ✓ | ✓ | | | | | | | ✓ | | | | | ✓ | | [<sub>SuffixTree</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/suffix/SuffixTreeIndex.html) | ✓ | ✓ | | | | | ✓ | ✓ | | | | | | | | [<sub>StandingQuery</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/standingquery/StandingQueryIndex.html) | | | | | | | | | | | | ✓ | | | | [<sub>Fallback</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/fallback/FallbackIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | | ✓ | | [<sub>OffHeap</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/offheap/OffHeapIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | ✓<sup>[1]</sup> | | | | [<sub>PartialOffHeap</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/offheap/PartialOffHeapIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | ✓ | | | | [<sub>Disk</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/disk/DiskIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | ✓<sup>[1]</sup> | | | | [<sub>PartialDisk</sub>](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/index/disk/PartialDiskIndex.html) | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | | | | | ✓ | | | <sup>[1]</sup> See: [forStandingQuery()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/query/QueryFactory.html#forStandingQuery-com.googlecode.cqengine.query.Query-) The [Benchmark](documentation/Benchmark.md) page contains examples of how to add these indexes to a collection, and measures their impact on latency. --- ## Attributes ## ### Read Fields ### CQEngine needs to access fields inside objects, so that it can build indexes on fields, and retrieve the value of a certain field from any given object. CQEngine does not use reflection to do this; instead it uses **attributes**, which is a more powerful concept. An attribute is an accessor object which can read the value of a certain field in a POJO. Here's how to define an attribute for a Car object (a POJO), which reads the `Car.carId` field: ```java public static final Attribute<Car, Integer> CAR_ID = new SimpleAttribute<Car, Integer>("carId") { public Integer getValue(Car car, QueryOptions queryOptions) { return car.carId; } }; ``` ...or alternatively, from a lambda expression or method reference: ```java public static final Attribute<Car, Integer> Car_ID = attribute("carId", Car::getCarId); ``` (For some caveats on using lambdas, please read [LambdaAttributes](documentation/LambdaAttributes.md)) Usually attributes are defined as anonymous `static` `final` objects like this. Supplying the `"carId"` string parameter to the constructor is actually optional, but it is recommended as it will appear in query `toString`s. Since this attribute reads a field from a `Car` object, the usual place to put the attribute is inside the `Car` class - and this makes queries more readable. However it could really be defined in any class, such as in a `CarAttributes` class or similar. The example above is for a **[SimpleAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/SimpleAttribute.html)**, which is designed for fields containing only one value. CQEngine also supports **[MultiValueAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/MultiValueAttribute.html)** which can read the values of fields which themselves are collections. And so it supports building indexes on objects based on things like keywords associated with those objects. Here's how to define a `MultiValueAttribute` for a `Car` object which reads the values from `Car.features` where that field is a `List<String>`: ```java public static final Attribute<Car, String> FEATURES = new MultiValueAttribute<Car, String>("features") { public Iterable<String> getValues(Car car, QueryOptions queryOptions) { return car.features; } }; ``` ...or alternatively, from a lambda expression or method reference: ```java public static final Attribute<Car, String> FEATURES = attribute(String.class, "features", Car::getFeatures); ``` #### Null values #### Note **if your data contains `null` values**, you should use **[SimpleNullableAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/SimpleNullableAttribute.html)** or **[MultiValueNullableAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/MultiValueNullableAttribute.html)** instead. In particular, note that `SimpleAttribute` and `MultiValueAttribute` do not perform any null checking on your data, and so if your data inadvertently contains null values, you may get obscure `NullPointerException`s. This is because null checking does not come for free. Attributes are accessed heavily, and the non-nullable versions of these attributes are designed to minimize latency by skipping explicit null checks. They defer to the JVM to do the null checking implicitly. As a rule of thumb, if you get a `NullPointerException`, it's probably because you used the wrong type of attribute. The problem will usually go away if you switch your code to use a nullable attribute instead. If you don't know if your data may contain null values, just use the nullable attributes. They contain the logic to check for and handle null values automatically. The nullable attributes also allow CQEngine to work with [object inheritance](https://github.com/npgall/cqengine/tree/master/code/src/test/java/com/googlecode/cqengine/examples/inheritance), where some objects in the collection have certain optional fields (e.g. in subclasses) while others might not. #### Creating queries dynamically #### Dynamic queries can be composed at runtime by instantiating and combining Query objects directly; see [this package](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/query/simple/package-summary.html) and [this package](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/query/logical/package-summary.html). For advanced cases, it is also possible to define attributes at runtime, using [ReflectiveAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/ReflectiveAttribute.html) or [AttributeBytecodeGenerator](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/codegen/AttributeBytecodeGenerator.html). #### Generate attributes automatically #### CQEngine also provides several ways to generate attributes automatically. Note these are an alternative to using [ReflectiveAttribute](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/attribute/ReflectiveAttribute.html), which was discussed above. Whereas `ReflectiveAttribute` is a special type of attribute which reads values at runtime using reflection, `AttributeSourceGenerator` and `AttributeBytecodeGenerator` generate code for attributes which is compiled and so does not use reflection at runtime, which can be more efficient. * [AttributeSourceGenerator](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/codegen/AttributeSourceGenerator.html) can automatically generate the source code for the simple and multi-value attributes discussed above. * [AttributeBytecodeGenerator](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/codegen/AttributeBytecodeGenerator.html) can automatically generate the class bytecode for the simple and multi-value attributes discussed above, and load them into the application at runtime as if they had been compiled from source code. See [AutoGenerateAttributes](documentation/AutoGenerateAttributes.md) for more details. ### Attributes as Functions ### It can be noted that attributes are only required to return a value given an object. Although most will do so, there is no requirement that an attribute must provide a value by reading a field in the object. As such attributes can be _virtual_, implemented as _functions_. **Calculated Attributes** An attribute can **_calculate_** an appropriate value for an object, based on a function applied to data contained in other fields or from external data sources. Here's how to define a calculated (or virtual) attribute by applying a function over the Car's other fields: ```java public static final Attribute<Car, Boolean> IS_DIRTY = new SimpleAttribute<Car, Boolean>("is_dirty") { public Boolean getValue(Car car, QueryOptions queryOptions) { return car.description.contains("dirty"); } }; ``` ...or, the same thing using a lambda: ```java public static final Attribute<Car, Boolean> IS_DIRTY = attribute("is_dirty", car -> car.description.contains("dirty")); ``` A `HashIndex` could be built on the virtual attribute above, enabling fast retrievals of cars which are either dirty or not dirty, without needing to scan the collection. **Associations with other `IndexedCollections` or External Data Sources** Here is an example for a virtual attribute which **associates** with each `Car` a list of locations which can service it, from an external data source: ```java public static final Attribute<Car, String> SERVICE_LOCATIONS = new MultiValueAttribute<Car, String>() { public List<String> getValues(Car car, QueryOptions queryOptions) { return CarServiceManager.getServiceLocationsForCar(car); } }; ``` The attribute above would allow the `IndexedCollection` of cars to be searched for cars which have _servicing options in a particular location_. The locations which service a car, could alternatively be retrieved from another `IndexedCollection`, of `Garage`s, for example. **Care should be taken if building indexes on virtual attributes** however, if referenced data might change leaving obsolete information in indexes. A **strategy to accommodate this** is: if no index exists for a virtual attribute referenced in a query, and other attributes are also referenced in the query for which indexes exist, CQEngine will automatically reduce the candidate set of objects to the minimum using other indexes before querying the virtual attribute. In turn if virtual attributes perform retrievals from _other_ `IndexedCollection`s, then those collections could be indexed appropriately without a risk of stale data. --- ### Joins ### The examples above define attributes on a primary `IndexedCollection` which read data from secondary collections or external data sources. It is also possible to perform SQL EXISTS-type queries and JOINs between `IndexedCollection`s on the query side (as opposed to on the attribute side). See [Joins](documentation/Joins.md) for examples. --- ## Persistence on-heap, off-heap, disk ## CQEngine's `IndexedCollection`s can be configured to store objects added to them on-heap (the default), or off-heap, or on disk. **On-heap** Store the collection on the Java heap: ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(); ``` **Off-heap** Store the collection in native memory, within the JVM process but outside the Java heap: ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(OffHeapPersistence.onPrimaryKey(Car.CAR_ID)); ``` Note that the off-heap persistence will automatically create an index on the specified primary key attribute, so there is no need to add an index on that attribute later. **Disk** Store the collection in a temp file on disk (then see `DiskPersistence.getFile()`): ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(DiskPersistence.onPrimaryKey(Car.CAR_ID)); ``` Or, store the collection in a particular file on disk: ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, new File("cars.dat"))); ``` Note that the disk persistence will automatically create an index on the specified primary key attribute, so there is no need to add an index on that attribute later. **Wrapping** Wrap any Java collection, in a CQEngine IndexedCollection without any copying of objects. * This can be a convenient way to run queries or build indexes on existing collections. * However some caveats relating to concurrency support and the performance of the underlying collection apply, see [WrappingPersistence](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/persistence/wrapping/WrappingPersistence.html) for details. ```java Collection<Car> collection = // obtain any Java collection IndexedCollection<Car> indexedCollection = new ConcurrentIndexedCollection<Car>( WrappingPersistence.aroundCollection(collection) ); ``` **Composite** `CompositePersistence` configures a combination of persistence types for use within the same collection. The collection itself will be persisted in the first persistence provided (the _primary persistence_), and the additional persistences provided will be used by off-heap or disk indexes added to the collection subsequently. Store the collection on-heap, and also configure DiskPersistence for use by DiskIndexes added to the collection subsequently: ```java IndexedCollection<Car> cars = new ConcurrentIndexedCollection<Car>(CompositePersistence.of( OnHeapPersistence.onPrimaryKey(Car.CAR_ID), DiskPersistence.onPrimaryKeyInFile(Car.CAR_ID, new File("cars.dat")) )); ``` ### Index persistence ### Indexes can similarly be stored on-heap, off-heap, or on disk. Each index requires a certain type of persistence. It is necessary to configure the collection in advance with an appropriate combination of persistences for use by whichever indexes are added. It is possible to store the collection on-heap, but to store some indexes off-heap. Similarly it is possible to have a variety of index types on the same collection, each using a different type of persistence. On-heap persistence is by far the fastest, followed by off-heap persistence, and then by disk persistence. If both the collection and all of its indexes are stored off-heap or on disk, then it is possible to have extremely large collections which don't use any heap memory or RAM at all. CQEngine has been tested using off-heap persistence with collections of 10 million objects, and using disk persistence with collections of 100 million objects. **On-heap** Add an on-heap index on "manufacturer": ```java cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER)); ``` **Off-heap** Add an off-heap index on "manufacturer": ```java cars.addIndex(OffHeapIndex.onAttribute(Car.MANUFACTURER)); ``` **Disk** Add a disk index on "manufacturer": ```java cars.addIndex(DiskIndex.onAttribute(Car.MANUFACTURER)); ``` ### Querying with persistence ### When either the `IndexedCollection`, or one or more indexes are located off-heap or on disk, take care to close the ResultSet when finished reading. You can use a _try-with-resources_ block to achieve this: ```java try (ResultSet<Car> results = cars.retrieve(equal(Car.MANUFACTURER, "Ford"))) { results.forEach(System.out::println); } ``` --- ## Result Sets ## CQEngine [ResultSet](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html)s provide the following methods: * [iterator()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#iterator()) - Allows the `ResultSet` to be iterated, returning the next object matching the query in each iteration as determined via _lazy evaluation_ * Result sets support **concurrent iteration** while the collection is being modified; the set of objects returned simply may or may not reflect changes made during iteration (depending on whether changes are made to areas of the collection or indexes already iterated or not) * [uniqueResult()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#uniqueResult()) - Useful if the query is expected to only match one object, this method returns the first object which would be returned by the iterator, and it throws an exception if zero or more than one object is found * [size()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#size()) - Returns the number of objects which _would be returned by the `ResultSet` if it was iterated_; CQEngine can often **accelerate** this calculation of size, based on the sizes of individual sets in indexes; see JavaDoc for details * [contains()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#contains(O)) - Tests if a _given object_ would be contained in results matching a query; this is also an **accelerated** operation; when suitable indexes are available, CQEngine can avoid iterating results to test for containment; see JavaDoc for details * [getRetrievalCost()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#getRetrievalCost()) - This is a metric used internally by CQEngine to allow it to _choose between multiple indexes_ which support the query. This could occasionally be used by applications to ascertain if suitable indexes are available for any particular query, this will be `Integer.MAX_VALUE` for queries for which no suitable indexes are available * [getMergeCost()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#getMergeCost()) - This is a metric used internally by CQEngine to allow it to _re-order_ elements of the query to minimize time complexity; for example CQEngine will order intersections such that the smallest set drives the _merge_; this metric is _roughly_ based on the theoretical cost to iterate underlying result sets * For query fragments requiring _set union_ (`or`-based queries), this will be the _sum_ of merge costs from underlying result sets * For query fragments requiring _set intersection_ (`and`-based queries), this will be the _Math.min()_ of merge costs from underlying result sets, because intersections will be re-ordered to perform lowest-merge-cost intersections first * For query fragments requiring _set difference_ (`not`-based queries), this will be the merge cost from the first underlying result set * [stream()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#stream()) - Returns a Java 8+ `Stream` allowing CQEngine results to be grouped, aggregated, and transformed in flexible ways using lambda expressions. * [close()](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/resultset/ResultSet.html#close()) - Releases any resources or closes the transaction which was opened for the query. Whether or not it is necessary to close the ResultSet depends on which implementation of IndexedCollection is in use and the types of indexes added to it. --- ## Deduplicating Results ## It is possible that a query would result in the same object being returned more than once. For example if an object matches several attribute values specified in an `or`-type query, then the object will be returned multiple times, one time for each attribute matched. Intersections (`and`-type queries) and negations (`not`-type queries) do not produce duplicates. By default, CQEngine does _not_ perform de-duplication of results; however it can be _instructed_ to do so, using various strategies such as Logical Elimination and Materialize. Read more: [DeduplicationStrategies](documentation/DeduplicationStrategies.md) --- ## Ordering Results ## By default, CQEngine does not order results; it simply returns objects in the order it finds them in the collection or in indexes. CQEngine can be instructed to order results via query options as follows. **Order by price descending** ```java ResultSet<Car> results = cars.retrieve(query, queryOptions(orderBy(descending(Car.PRICE)))); ``` **Order by price descending, then number of doors ascending** ```java ResultSet<Car> results = cars.retrieve(query, queryOptions(orderBy(descending(Car.PRICE), ascending(Car.DOORS)))); ``` Note that ordering results as above uses the default _materialize_ ordering strategy. This is relatively expensive, dependent on the number of objects matching the query, and can cause latency in accessing the first object. It requires all results to be materialized into a sorted set up-front _before iteration can begin_. ### Index-accelerated ordering ### CQEngine also has support to use an index to accelerate, or eliminate, the overhead of ordering results. This strategy reduces the latency to access the first object in the sorted results, at the expense of adding more total overhead if the entire ResultSet was iterated. Read more: [OrderingStrategies](documentation/OrderingStrategies.md) --- ## Merge Strategies ## Merge strategies are the algorithms CQEngine uses to evaluate queries which have multiple branches. By default CQEngine will use strategies which should suit most applications, however these strategies can be overridden to tune performance. Read more: [MergeStrategies](documentation/MergeStrategies.md) --- ## Index Quantization, Granularity, and tuning index size ## [Quantization](http://en.wikipedia.org/wiki/Quantization_(signal_processing)) involves converting fine-grained or continuous values, to discrete or coarse-grained values. A Quantizer is a _function_ which takes fine-grained values as input, and maps those values to coarse-grained counterparts as its output, by discarding some precision. Quantization can be a useful tool to tune the size of indexes, trading a reduction in index size, for increases in CPU overhead and vice-versa. Read more: [Quantization and included Quantizers](documentation/IndexQuantization.md) --- ## Grouping and Aggregation (GROUP BY, SUM...) ## CQEngine has been designed with support for grouping and aggregation in mind, but note that this is not built into the CQEngine library itself, because CQEngine is designed to integrate with Java 8+ `Stream`s. This allows CQEngine results to be grouped, aggregated, and transformed in flexible ways using lambda expressions. CQEngine `ResultSet` can be converted into a Java 8 `Stream` by calling `ResultSet.stream()`. Note that Streams are **evaluated via filtering** and they do not avail of CQEngine indexes. So **for best performance, as much of the overall query as possible should be encapsulated in the CQEngine query**, as opposed to in lambda expressions in the stream. This combination would dramatically outperform a stream and lambda expression alone, which simply filtered the collection. Here's how to transform a `ResultSet` into a `Stream`, to compute the distinct set of Colors of cars which match a CQEngine query. ```java public static void main(String[] args) { IndexedCollection<Car> cars = new ConcurrentIndexedCollection<>(); cars.addAll(CarFactory.createCollectionOfCars(10)); cars.addIndex(NavigableIndex.onAttribute(Car.MANUFACTURER)); Set<Car.Color> distinctColorsOfFordCars = cars.retrieve(equal(Car.MANUFACTURER, "Ford")) .stream() .map(Car::getColor) .collect(Collectors.toSet()); System.out.println(distinctColorsOfFordCars); // prints: [GREEN, RED] } ``` --- ## Accessing Index Metadata and Statistics from MetadataEngine ## The [MetadataEngine](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/metadata/MetadataEngine.html), is a high-level API which can retrieve metatadata and statistics from indexes which have been added to the collection. It provides access to the following: * Frequency distributions (the counts of each attribute value stored in an index) * Distinct keys (the distinct attribute values in an index, optionally within a range between x and y) * Streams of attribute values and associated objects stored in an index (ascending/descending order, optionally within a range between x and y) * Count of distinct keys (how many distinct attribute values are in an index) * Count for a specific key (how many objects match a specific attribute value) For more information, see JavaDocs for: [MetadataEngine](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/metadata/MetadataEngine.html), [AttributeMetadata](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/metadata/AttributeMetadata.html), [SortedAttributeMetadata](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/com/googlecode/cqengine/metadata/SortedAttributeMetadata.html) --- ## Using CQEngine with Hibernate / JPA / ORM Frameworks ## CQEngine has seamless integration with JPA/ORM frameworks such as Hibernate or EclipseLink. Simply put, CQEngine can build indexes on, and query, any type of Java collection or arbitrary data source. ORM frameworks return entity objects loaded from database tables in Java collections, therefore CQEngine can act as a very fast in-memory query engine on top of such data. --- ## Usage in Maven and Non-Maven Projects ## CQEngine is in Maven Central, and can be added to a Maven project as follows: ``` <dependency> <groupId>com.googlecode.cqengine</groupId> <artifactId>cqengine</artifactId> <version>x.x.x</version> </dependency> ``` See [ReleaseNotes](documentation/ReleaseNotes.md) for the latest version number. For non-Maven projects, a version built with [maven-shade-plugin](http://maven.apache.org/plugins/maven-shade-plugin/) is also provided, which contains CQEngine and all of its own dependencies packaged in a single jar file (ending "-all"). It can be downloaded from Maven central as "-all.jar" [here](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.googlecode.cqengine%22%20AND%20a%3A%22cqengine%22). --- ## Using CQEngine in Scala, Kotlin, or other JVM languages ## CQEngine should generally be compatible with other JVM languages besides Java too, however it can be necessary to apply a few tricks to make it work. See [OtherJVMLanguages.md](documentation/OtherJVMLanguages.md) for some tips. --- ## Related Projects ## * CQEngine is somewhat similar to [Microsoft LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query), but a difference is LINQ queries on collections are evaluated via iteration/filtering whereas CQEngine uses set theory, thus CQEngine would outperform LINQ * [Concurrent Trees](http://github.com/npgall/concurrent-trees/) provides Concurrent Radix Trees and Concurrent Suffix Trees, used by some indexes in CQEngine --- ## Project Status ## * CQEngine 3.6.0 is the current release as of writing (January 2021), and is in Maven central * A [ReleaseNotes](documentation/ReleaseNotes.md) page has been added to document changes between releases * API / JavaDocs are available [here](http://htmlpreview.github.io/?http://raw.githubusercontent.com/npgall/cqengine/master/documentation/javadoc/apidocs/index.html) Report any bugs/feature requests in the [Issues](http://github.com/npgall/cqengine/issues) tab. For support please use the [Discussion Forum](http://groups.google.com/forum/#!forum/cqengine-discuss), not direct email to the developers. Many thanks to JetBrains for supporting CQEngine with free IntelliJ licenses! [![](documentation/images/logo_jetbrains.png)](http://www.jetbrains.com)[![](documentation/images/logo_intellij_idea.png)](http://www.jetbrains.com/idea/)
0
java-diff-utils/java-diff-utils
Diff Utils library is an OpenSource library for performing the comparison / diff operations between texts or some kind of data: computing diffs, applying patches, generating unified diffs or parsing them, generating diff output for easy future displaying (like side-by-side view) and so on.
2017-03-30T05:47:23Z
null
# java-diff-utils ## Status [![Build Status](https://travis-ci.org/java-diff-utils/java-diff-utils.svg?branch=master)](https://travis-ci.org/java-diff-utils/java-diff-utils) [![Build Status using Github Actions](https://github.com/java-diff-utils/java-diff-utils/workflows/Java%20CI%20with%20Maven/badge.svg)](https://github.com/java-diff-utils/java-diff-utils/actions?query=workflow%3A%22Java+CI+with+Maven%22) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/002c53aa0c924f71ac80a2f65446dfdd)](https://www.codacy.com/gh/java-diff-utils/java-diff-utils/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=java-diff-utils/java-diff-utils&amp;utm_campaign=Badge_Grade) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.github.java-diff-utils/java-diff-utils/badge.svg)](http://maven-badges.herokuapp.com/maven-central/io.github.java-diff-utils/java-diff-utils) ## Intro Diff Utils library is an OpenSource library for performing the comparison operations between texts: computing diffs, applying patches, generating unified diffs or parsing them, generating diff output for easy future displaying (like side-by-side view) and so on. Main reason to build this library was the lack of easy-to-use libraries with all the usual stuff you need while working with diff files. Originally it was inspired by JRCS library and it's nice design of diff module. **This is originally a fork of java-diff-utils from Google Code Archive.** ## API Javadocs of the actual release version: [JavaDocs java-diff-utils](https://java-diff-utils.github.io/java-diff-utils/4.10/docs/apidocs/) ## Examples Look [here](https://github.com/java-diff-utils/java-diff-utils/wiki) to find more helpful informations and examples. These two outputs are generated using this java-diff-utils. The source code can also be found at the *Examples* page: **Producing a one liner including all difference information.** ```Java //create a configured DiffRowGenerator DiffRowGenerator generator = DiffRowGenerator.create() .showInlineDiffs(true) .mergeOriginalRevised(true) .inlineDiffByWord(true) .oldTag(f -> "~") //introduce markdown style for strikethrough .newTag(f -> "**") //introduce markdown style for bold .build(); //compute the differences for two test texts. List<DiffRow> rows = generator.generateDiffRows( Arrays.asList("This is a test senctence."), Arrays.asList("This is a test for diffutils.")); System.out.println(rows.get(0).getOldLine()); ``` This is a test ~senctence~**for diffutils**. **Producing a side by side view of computed differences.** ```Java DiffRowGenerator generator = DiffRowGenerator.create() .showInlineDiffs(true) .inlineDiffByWord(true) .oldTag(f -> "~") .newTag(f -> "**") .build(); List<DiffRow> rows = generator.generateDiffRows( Arrays.asList("This is a test senctence.", "This is the second line.", "And here is the finish."), Arrays.asList("This is a test for diffutils.", "This is the second line.")); System.out.println("|original|new|"); System.out.println("|--------|---|"); for (DiffRow row : rows) { System.out.println("|" + row.getOldLine() + "|" + row.getNewLine() + "|"); } ``` |original|new| |--------|---| |This is a test ~senctence~.|This is a test **for diffutils**.| |This is the second line.|This is the second line.| |~And here is the finish.~|| ## Main Features * computing the difference between two texts. * capable to hand more than plain ascii. Arrays or List of any type that implements hashCode() and equals() correctly can be subject to differencing using this library * patch and unpatch the text with the given patch * parsing the unified diff format * producing human-readable differences * inline difference construction * Algorithms: * Myers Standard Algorithm * Myers with linear space improvement * HistogramDiff using JGit Library ### Algorithms * Myer's diff * HistogramDiff But it can easily replaced by any other which is better for handing your texts. I have plan to add implementation of some in future. ## Source Code conventions Recently a checkstyle process was integrated into the build process. java-diff-utils follows the sun java format convention. There are no TABs allowed. Use spaces. ```java public static <T> Patch<T> diff(List<T> original, List<T> revised, BiPredicate<T, T> equalizer) throws DiffException { if (equalizer != null) { return DiffUtils.diff(original, revised, new MyersDiff<>(equalizer)); } return DiffUtils.diff(original, revised, new MyersDiff<>()); } ``` This is a valid piece of source code: * blocks without braces are not allowed * after control statements (if, while, for) a whitespace is expected * the opening brace should be in the same line as the control statement ### To Install Just add the code below to your maven dependencies: ```xml <dependency> <groupId>io.github.java-diff-utils</groupId> <artifactId>java-diff-utils</artifactId> <version>4.12</version> </dependency> ``` or using gradle: ```groovy // https://mvnrepository.com/artifact/io.github.java-diff-utils/java-diff-utils implementation "io.github.java-diff-utils:java-diff-utils:4.12" ```
0
summitt/Nope-Proxy
TCP/UDP Non-HTTP Proxy Extension (NoPE) for Burp Suite.
2016-05-23T20:30:34Z
null
# NoPE Proxy ![GitHub last commit](https://img.shields.io/github/last-commit/factionsecurity/faction) ![GitHub Release Date - Published_At](https://img.shields.io/github/release-date/factionsecurity/faction) [![](https://img.shields.io/badge/null0perat0r-it?style=flat-square&logo=mastodon&labelColor=white&color=white&link=https%3A%2F%2Finfosec.exchange%2F%40null0perat0r)](https://infosec.exchange/@null0perat0r) [![](https://img.shields.io/twitter/follow/null0perar0r)](https://twitter.com/intent/follow?screen_name=null0perar0r) <img align="right" style="width:400px; margin-top: 70px" src="Nope.png"/> __A TCP/UDP Non-HTTP Proxy Extension for Burp Suite__ ## [Download Latest Release Here](https://github.com/summitt/Burp-Non-HTTP-Extension/releases) ## [Manual and Guides Here](https://github.com/summitt/Burp-Non-HTTP-Extension/wiki) ## [Community Nope Scripts](https://github.com/summitt/Nope-Proxy-Scripts) ## [Support](https://www.patreon.com/null0perat0r) ## [Follow](https://defcon.social/@Null0perat0r) ## Introduction This burp extension adds three main features to BurpSuite. 1. Interceptors for TCP and UDP traffic. 2. A configurable DNS server. This will route all DNS requests to Burp or preconfigured hosts. It makes it easier to send mobile or thick client traffic to Burp. You need to create invisible proxy listeners in BurpSuite for the Burp to intercept HTTP traffic or you can use the second feature of this extension to intercept binary/non-http protocols. 3. A Non-HTTP MiTM Intercepting proxy. This extension allows you to create multiple listening ports that can MiTM server side services. It also uses Burp's CA cert so that if the browser or mobile device is already configured to access SSL/TLS requests using this cert then the encrypted binary protocols will be able to connect without generating errors too. It also provides the ability to automatically match and replace hex or strings as they pass through the proxy or you can use custom python code to manipulate the traffic. ![](http://imgur.com/X6xYsq8.png) ## DNS Server Configuration ![](http://imgur.com/0ezoO7f.png) The DNS server configuration allows granular control over your DNS settings. You can configure it to send all traffic to the same IP address as Burp or you can use a Custom Hosts File to configure only some hosts to be forward to Burp while others can be forwarded to other hosts. It can also be confgured to send all requests to the real IP unless specified in the custom hosts file. The DNS server automatically starts with the IP address of the last interface you set in the Interface input box. Changing the interface number will automatically change the IP address. The server will need to be restarted for this change to take effect. The Custom Hosts File is not related at all to your normal hosts file and will over ride it. If the ‘Use DNS Response IP’ checkbos is checked (default) then the extension will resolve all hosts not in the Custom hosts file to which ever IP address is set in the ‘DNS Response IP’ input box. If this box is not checked then the extension will resolve the Real IP address unless it has been overridden in the ‘Custom Hosts File’ ## Port Monitoring Nope Proxy has a port monitor that will only display tcp and udp ports that a remote client is attempting to connect on. This combined with the DNS history can help you find which hosts and ports a mobile app or thin client is attempting to contact so that you can create interceptors for this traffic and proxy it to the real servers. ## Non-HTTP MiTM proxy ![](http://imgur.com/oCHMjuH.png) This non-HTTP proxy has several features built in. - All requests and responses are saved to a sqlite database and can be exported or imported into the tool. - Automatic Match and Replace Rules that are customizable based on the direction of traffic. (Client to Server, Server to Client, or Both. - Match and replace rules support both hex and string replacement. - Manual Interception binary protocols and change them before sending them back to the server or client. Just like the normal Burp proxy but with binary streams. - Python Code can be used instead of the normal Match and Replace Rules for more advancing mangling of requests and responses. - Use python code to reformat requests in history without changing outgoing or incomming requests. (e.g. Convert protobuf to JSON or human readable formats without modifying the incomming or outgoing traffic) ## TCP/UDP Repeater ![](http://imgur.com/aNpzAdz.png) - TCP/UDP repeater can be used to replay requests to the client or server on the currently connected socket streams. - Code Playground allows you to create a custom python payload based on the request currently displayed in the repeater. - Search TCP/UDP proxy history ## Configure the proxies ![](http://imgur.com/WdsB32L.png) To perform normal intercepting of binary traffic of applications you can set the DNS IP address to the extension’s IP address and then create a Listener Under ‘Server Config’. This requires that you know the hostname and Port the application is trying to connect. You can switch to the ‘DNS History’ Tab to view the DNS queries and ports that are trying to connect to you. You could also run wireshark but Nope will filter this information for you. Once you know the right host name and port you can configure these settings as shown above. If the service is using SSL then you need to export burp’s CA cert to the same folder that Burp is running out of for the extension to find it and generate certs that will pass certificate verification. Then you can check the SSL check box before adding the proxy. The proxy does not start until ‘enable’ is checked in the table. Once the proxy is started you can intercept it in real time. All your traffic will be logged into the TCP History Tab and stored locally in a sqlite database. The database can be exported or imported from the Server Configuration Tab. In addition, if Burp crashes or you close burp without saving the TCP History it will still be automatically loaded when you start Burp. ## Manual Intercept Traffic ![](http://imgur.com/X6xYsq8.png) Clicking on the TCP Intercept Tab will allow to enable and disable Manual Intercepting. This will be very similar to intercepting HTTP traffic with burp. If the data sent is just strings then it’s very simple to just replace text or attempt modification to the request. If the application is sending serialized objects or protobuffs then you will need to switch between Raw and Hex mode to ensure the data is encoded correctly and length checks are correct. ## Automated Manipulation of Traffic Once you have your ideal payload you can automatically match and replace in the Automation Tab. ![](http://imgur.com/CBRQVIo.png) If the ‘Enable Python Manger’ is left uncheck (default) then the Match and Replace Rules are used. It supports both hex, string, and directional replacement. The ‘#’ can be used to comment out a line and rules are updated as soon as you press a single key. If you want to replace the string ‘test’ with ‘hacked’ then you could use the following rule: ``` test||hacked ``` This will affect traffic in both directions. You could make it serve to client only by using the following rule: ``` test||hacked||c2sOnly ``` You could also perform the same replacement as hex using the following rule: ``` 0x74657374||6861636B6565||c2sOnly ``` ## Python Mangler The previous example is great for quickly fuzzing the request but more complicated examples may require actual coding. The Python Mangler was built to provide far more control of the requests and responses. You can import a library to extract the data into a more easily editable form and covert it back before sending to the server. The PyManger must have at the minimum the following structure. You can download community [Nope Scripts here](https://github.com/summitt/Nope-Proxy-Scripts) ``` def mangle(input, isC2S): return input ``` The ‘input’ variable is a byte array, the ‘isC2S’ variable is a Boolean value, and the output must also be a byte array (though python seems somewhat forgiving here). This will allow directional specifying changes the traffic. Using PyMangler you can perform the same rule change above by writing the following code. ``` def mangle(input, isC2S): if isC2S: input = input.replace(‘test’,’hacked’) return input ``` You can import external libraries, create classes, and do anything you can do in normal python as long as there is a ‘mangle’ function with the same inputs to process the traffic. If you import custom classes they will need to be placed in the same folder that is running BurpSuite unless they are in your path. ## Python Pre and Post Interceptor Functions You can use the pre and post interceptors do all kinds of things with the stream. I was originally created to allow converting streams to a more human readable format before sending the data to the interceptor. Once modified in the interceptor the postInterceptor can convert it back to the binary stream. ``` def preIntercept(input,isC2S): return input def postIntercept(input,isC2S): return input ``` Below is an example of a server that is sending protobuf messages. Notice the stream would be difficult to modify by hand. ![](NonHTTPProxy/screenshots/PreFormat.PNG) Now we use the pre and post interceptor functions to make it easier to modify in transit. Notice the python console on the Right will display in 'print' statements as well as errors in your python code when it runs. *Note that if the functions fail the NoPE proxy will send the original paylaods and ignore any changes to the stream you made.* ![](NonHTTPProxy/screenshots/PythonConsole.PNG) Below is an example of the now Human Readable and Editable Protobufs. ![](NonHTTPProxy/screenshots/Post%20Format.PNG)A ## Highlighting Traffic You can select mutliple requests and responses and highlight them with custom colors. You can even search only highlighted items. This makes is easy to find interesting requests later that you might want to dig into further. ![image](https://github.com/summitt/Nope-Proxy/assets/2343831/ee6d6f98-6f9b-4644-8fa3-5573c058ee7c) ### Upcomming features - UDP repeater - Switches in the python manger for TCP or UDP request only modification - Ability to decrypted encrypted UDP traffic like QUIC and other protocols - Ability to auto sense encrypted traffic so it can better decode XMPP, SSH, SFTP, etc.
0
tuguangquan/mybatis
mybatis源码中文注释
2014-11-03T04:51:06Z
null
null
0
spring-guides/gs-rest-service
Building a RESTful Web Service :: Learn how to create a RESTful web service with Spring.
2013-04-12T14:54:36Z
null
null
1
apache/linkis
Apache Linkis builds a computation middleware layer to facilitate connection, governance and orchestration between the upper applications and the underlying data engines.
2019-07-23T06:41:51Z
null
<h2 align="center"> Apache Linkis </h2> <p align="center"> <strong> Linkis builds a computation middleware layer to facilitate connection, governance and orchestration between the upper applications and the underlying data engines. </strong> </p> <p align="center"> <a href="https://linkis.apache.org/">https://linkis.apache.org/</a> </p> <p align="center"> <a href="https://linkis.apache.org/docs/latest/introduction/" > <img src="https://img.shields.io/badge/document-English-blue.svg" alt="EN docs" /> </a> <a href="https://linkis.apache.org/zh-CN/docs/latest/introduction/"> <img src="https://img.shields.io/badge/文档-简体中文-blue.svg" alt="简体中文文档" /> </a> </p> <p align="center"> <a target="_blank" href="https://search.maven.org/search?q=g:org.apache.linkis%20AND%20a:linkis"> <img src="https://img.shields.io/maven-central/v/org.apache.linkis/linkis.svg?label=maven%20central" /> </a> <a target="_blank" href="https://github.com/apache/linkis/blob/master/LICENSE"> <img src="https://img.shields.io/badge/License-Apache%202.0-blue.svg?label=license" /> </a> <a target="_blank" href="https://www.oracle.com/technetwork/java/javase/downloads/index.html"> <img src="https://img.shields.io/badge/JDK-8-green.svg" /> </a> <a target="_blank" href="https://github.com/apache/linkis/actions"> <img src="https://github.com/apache/linkis/actions/workflows//build-backend.yml/badge.svg" /> </a> <a target="_blank" href='https://github.com/apache/linkis'> <img src="https://img.shields.io/github/forks/apache/linkis.svg" alt="github forks"/> </a> <a target="_blank" href='https://github.com/apache/linkis'> <img src="https://img.shields.io/github/stars/apache/linkis.svg" alt="github stars"/> </a> <a target="_blank" href='https://github.com/apache/linkis'> <img src="https://img.shields.io/github/contributors/apache/linkis.svg" alt="github contributors"/> </a> <a target="_blank" href="https://badges.toozhao.com/stats/01G7TRNN1PH9PMSCYWDF3EK4QT"> <img src="https://badges.toozhao.com/badges/01G7TRNN1PH9PMSCYWDF3EK4QT/green.svg" /> </a> </p> <br/> --- [English](README.md) | [中文](README_CN.md) # Introduction Linkis builds a layer of computation middleware between upper applications and underlying engines. By using standard interfaces such as REST/WS/JDBC provided by Linkis, the upper applications can easily access the underlying engines such as MySQL/Spark/Hive/Presto/Flink, etc., and achieve the intercommunication of user resources like unified variables, scripts, UDFs, functions and resource files at the same time. As a computation middleware, Linkis provides powerful connectivity, reuse, orchestration, expansion, and governance capabilities. By decoupling the application layer and the engine layer, it simplifies the complex network call relationship, and thus reduces the overall complexity and saves the development and maintenance costs as well. Since the first release of Linkis in 2019, it has accumulated more than **700** trial companies and **1000+** sandbox trial users, which involving diverse industries, from finance, banking, tele-communication, to manufactory, internet companies and so on. Lots of companies have already used Linkis as a unified entrance for the underlying computation and storage engines of the big data platform. ![linkis-intro-01](https://user-images.githubusercontent.com/7869972/148767375-aeb11b93-16ca-46d7-a30e-92fbefe2bd5e.png) ![linkis-intro-03](https://user-images.githubusercontent.com/7869972/148767380-c34f44b2-9320-4633-9ec8-662701f41d15.png) # Features - **Support for diverse underlying computation storage engines** : Spark, Hive, Python, Shell, Flink, JDBC, Pipeline, Sqoop, OpenLooKeng, Presto, ElasticSearch, Trino, SeaTunnel, etc.; - **Support for diverse language** : SparkSQL, HiveSQL, Python, Shell, Pyspark, Scala, JSON and Java; - **Powerful computing governance capability** : It can provide task routing, load balancing, multi-tenant, traffic control, resource control and other capabilities based on multi-level labels; - **Support full stack computation/storage engine** : The ability to receive, execute and manage tasks and requests for various compute and storage engines, including offline batch tasks, interactive query tasks, real-time streaming tasks and data lake tasks; - **Unified context service** : supports cross-user, system and computing engine to associate and manage user and system resource files (JAR, ZIP, Properties, etc.), result sets, parameter variables, functions, UDFs, etc., one setting, automatic reference everywhere; - **Unified materials** : provides system and user level material management, can share and flow, share materials across users, across systems; - **Unified data source management** : provides the ability to add, delete, check and change information of Hive, ElasticSearch, Mysql, Kafka, MongoDB and other data sources, version control, connection test, and query metadata information of corresponding data sources; - **Error code capability** : provides error codes and solutions for common errors of tasks, which is convenient for users to locate problems by themselves; # Engine Type | **Engine name** | **Support underlying component version<br/>(default dependency version)** | **Linkis Version Requirements** | **Included in Release Package By Default** | **Description** | |:---- |:---- |:---- |:---- |:---- | |Spark|Apache >= 2.0.0, <br/>CDH >= 5.4.0, <br/>(default Apache Spark 3.2.1)|\>=1.0.3|Yes|Spark EngineConn, supports SQL , Scala, Pyspark and R code| |Hive|Apache >= 1.0.0, <br/>CDH >= 5.4.0, <br/>(default Apache Hive 3.1.3)|\>=1.0.3|Yes |Hive EngineConn, supports HiveQL code| |Python|Python >= 2.6, <br/>(default Python2*)|\>=1.0.3|Yes |Python EngineConn, supports python code| |Shell|Bash >= 2.0|\>=1.0.3|Yes|Shell EngineConn, supports Bash shell code| |JDBC|MySQL >= 5.0, Hive >=1.2.1, <br/>(default Hive-jdbc 2.3.4)|\>=1.0.3|No |JDBC EngineConn, already supports ClickHouse, DB2, DM, Greenplum, kingbase, MySQL, Oracle, PostgreSQL and SQLServer, can be extended quickly Support other DB, such as SQLite| |Flink |Flink >= 1.12.2, <br/>(default Apache Flink 1.12.2)|\>=1.0.2|No |Flink EngineConn, supports FlinkSQL code, also supports starting a new Yarn in the form of Flink Jar Application| |Pipeline|-|\>=1.0.2|No|Pipeline EngineConn, supports file import and export| |openLooKeng|openLooKeng >= 1.5.0, <br/>(default openLookEng 1.5.0)|\>=1.1.1|No|openLooKeng EngineConn, supports querying data virtualization engine with Sql openLooKeng| |Sqoop| Sqoop >= 1.4.6, <br/>(default Apache Sqoop 1.4.6)|\>=1.1.2|No|Sqoop EngineConn, support data migration tool Sqoop engine| |Presto|Presto >= 0.180|\>=1.2.0|No|Presto EngineConn, supports Presto SQL code| |ElasticSearch|ElasticSearch >=6.0|\>=1.2.0|No|ElasticSearch EngineConn, supports SQL and DSL code| |Trino | Trino >=371 | >=1.3.1 | No | Trino EngineConn, supports Trino SQL code | |Seatunnel | Seatunnel >=2.1.2 | >=1.3.1 | No | Seatunnel EngineConn, supportt Seatunnel SQL code | # Download Please go to the [Linkis Releases Page](https://linkis.apache.org/download/main) to download a compiled distribution or a source code package of Linkis. # Compile and Deploy > For more detailed guidance see: >- [[Backend Compile]](https://linkis.apache.org/docs/latest/development/build) >- [[Management Console Build]](https://linkis.apache.org/docs/latest/development/build-console) ```shell Note: If you want use `-Dlinkis.build.web=true` to build linkis-web image, you need to compile linkis-web first. ## compile backend ### Mac OS/Linux # 1. When compiling for the first time, execute the following command first ./mvnw -N install # 2. make the linkis distribution package # - Option 1: make the linkis distribution package only ./mvnw clean install -Dmaven.javadoc.skip=true -Dmaven.test.skip=true # - Option 2: make the linkis distribution package and docker image # - Option 2.1: image without mysql jdbc jars ./mvnw clean install -Pdocker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true # - Option 2.2: image with mysql jdbc jars ./mvnw clean install -Pdocker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true -Dlinkis.build.with.jdbc=true # - Option 3: linkis distribution package and docker image (included web) ./mvnw clean install -Pdocker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true -Dlinkis.build.web=true # - Option 4: linkis distribution package and docker image (included web and ldh (hadoop all in one for test)) ./mvnw clean install -Pdocker -Dmaven.javadoc.skip=true -Dmaven.test.skip=true -Dlinkis.build.web=true -Dlinkis.build.ldh=true -Dlinkis.build.with.jdbc=true ### Windows mvnw.cmd -N install mvnw.cmd clean install -Dmaven.javadoc.skip=true -Dmaven.test.skip=true ## compile web cd linkis/linkis-web npm install npm run build ``` ### Bundled with MySQL JDBC Driver Due to the MySQL licensing restrictions, the MySQL Java Database Connectivity (JDBC) driver is not bundled with the official released linkis image by default. However, at current stage, linkis still relies on this library to work properly. To solve this problem, we provide a script which can help to creating a custom image with mysql jdbc from the official linkis image by yourself, the image created by this tool will be tagged as `linkis:with-jdbc` by default. ```shell $> LINKIS_IMAGE=linkis:1.3.1 $> ./linkis-dist/docker/scripts/make-linkis-image-with-mysql-jdbc.sh ``` Please refer to [Quick Deployment](https://linkis.apache.org/docs/latest/deployment/deploy-quick/) to do the deployment. # Examples and Guidance - [User Manual](https://linkis.apache.org/docs/latest/user-guide/how-to-use) - [Engine Usage Documents](https://linkis.apache.org/docs/latest/engine-usage/overview) - [API Documents](https://linkis.apache.org/docs/latest/api/overview) # Documentation & Vedio - The documentation of linkis is in [Linkis-Website Git Repository](https://github.com/apache/linkis-website) - Meetup videos on [Bilibili](https://space.bilibili.com/598542776?from=search&seid=14344213924133040656) # Architecture Linkis services could be divided into three categories: computation governance services, public enhancement services and microservice governance services - The computation governance services, support the 3 major stages of processing a task/request: submission -> preparation -> execution - The public enhancement services, including the material library service, context service, and data source service - The microservice governance services, including Spring Cloud Gateway, Eureka and Open Feign Below is the Linkis architecture diagram. You can find more detailed architecture docs in [Linkis-Doc/Architecture](https://linkis.apache.org/docs/latest/architecture/overview). ![architecture](https://user-images.githubusercontent.com/7869972/148767383-f87e84ba-5baa-4125-8b6e-d0aa4f7d3a66.png) # Contributing Contributions are always welcomed, we need more contributors to build Linkis together. either code, or doc, or other supports that could help the community. For code and documentation contributions, please follow the [contribution guide](https://linkis.apache.org/community/how-to-contribute). # Contact Us - Any questions or suggestions please kindly submit an [issue](https://github.com/apache/linkis/issues). - By mail [dev@linkis.apache.org](mailto:dev@linkis.apache.org) - You can scan the QR code below to join our WeChat group to get more immediate response <img src="https://linkis.apache.org/Images/wedatasphere_contact_01.png" width="256"/> # Who is Using Linkis We opened an issue [[Who is Using Linkis]](https://github.com/apache/linkis/issues/23) for users to feedback and record who is using Linkis. Since the first release of Linkis in 2019, it has accumulated more than **700** trial companies and **1000+** sandbox trial users, which involving diverse industries, from finance, banking, tele-communication, to manufactory, internet companies and so on.
0
tchiotludo/akhq
Kafka GUI for Apache Kafka to manage topics, topics data, consumers group, schema registry, connect and more...
2018-09-09T19:35:39Z
null
# AKHQ (previously known as KafkaHQ) ![Last Version](https://img.shields.io/github/tag-pre/tchiotludo/akhq.svg) ![License](https://img.shields.io/github/license/tchiotludo/akhq) ![Docker Pull](https://img.shields.io/docker/pulls/tchiotludo/akhq.svg) ![Github Downloads](https://img.shields.io/github/downloads/tchiotludo/akhq/total) ![Github Start](https://img.shields.io/github/stars/tchiotludo/akhq.svg) ![Main](https://github.com/tchiotludo/akhq/workflows/Main/badge.svg) [![Artifact HUB](https://img.shields.io/endpoint?url=https://artifacthub.io/badge/repository/akhq)](https://artifacthub.io/packages/search?repo=akhq) > Kafka GUI for [Apache Kafka](http://kafka.apache.org/) to manage topics, topics data, consumers group, schema registry, connect and more... <p align="center"> <img width="460" src="client/src/images/logo_black.svg" alt="AKHQ for Kafka logo" /><br /><br /> <img width="720" src="docs/.vuepress/public/assets/images/video.gif" alt="AKHQ for Kafka preview" /> </p> ## Documentation * The official AKHQ documentation can be found under: [akhq.io](https://akhq.io/docs) ## Sponsors <table> <tr> <td> <img width="1000" height="0"> <a href="https://upstash.com/?utm_source=AKHQ" > <img src="./docs/.vuepress/public/assets/images/logo-infosupport.svg" alt="Upstash" width="260" align="right"> </a> <h3>InfoSupport</h3> <p>Info Support is the specialist in developing high quality software<br /> solutions and leading in the field of artificial intelligence (AI), <br /> cloud architecture, managed services and IT training. </p> [Discover](https://infosupport.com/?utm_source=AKHQ) </td> </tr> <tr> <td> <img width="1000" height="0"> <a href="https://upstash.com/?utm_source=AKHQ" > <img src="https://raw.githubusercontent.com/upstash/sponsorship/master/kafka.png" alt="Upstash" width="260" align="right"> </a> <h3>Upstash: Serverless Kafka</h3> <ul> <li>True Serverless Kafka with per-request-pricing</li> <li>Managed Apache Kafka, works with all Kafka clients</li> <li>Built-in REST API designed for serverless and edge functions</li> </ul> [Start for free in 30 seconds!](https://upstash.com/?utm_source=AKHQ) </td> </tr> </table> ## From AKHQ project creator <table> <tr> <td> <img width="1000" height="0"> <a href="https://github.com/kestra-io/kestra?utm_source=AKHQ" > <img src="https://kestra.io/video.gif" alt="Upstash" width="320" align="right"> </a> <h3>Kestra: Open source data orchestration and scheduling platform</h3> <p> Kestra is an infinitely scalable orchestration and scheduling platform, creating, running, scheduling, and monitoring millions of complex pipelines. </p> [Discover the project!](https://github.com/kestra-io/kestra?utm_source=AKHQ) </td> </tr> </table> ## Who's using AKHQ * [Archer Aviation](https://archer.com/) * [Adeo](https://www.adeo.com/) * [Avlino](https://avlino.com/) * [Auchan Retail](https://www.auchan-retail.com/) * [BARMER](https://www.barmer.de/) * [Bell](https://www.bell.ca) * [Best buy](https://www.bestbuy.com) * [BMW Group](https://www.bmwgroup.com) * [Boulanger](https://www.boulanger.com/) * [BPCE-IT](https://www.bpce-it.fr/) * [Decathlon](https://www.decathlon.fr/) * [Depop](https://www.depop.com) * [Doximity](https://www.doximity.com) * [Fresha](https://www.fresha.com/) * [Galeries Lafayette](https://www.galerieslafayette.com/) * [GetYourGuide](https://www.getyourguide.com) * [GrtGaz](https://www.grtgaz.com/) * [Kitopi](https://kitopi.com) * [Klarna](https://www.klarna.com) * [La Redoute](https://laredoute.io/) * [Leroy Merlin](https://www.leroymerlin.fr/) * [MAIF](https://www.maif.fr/) * [ManoMano](https://www.manomano.fr/) * [NEXT Technologies](https://www.nextapp.co/) * [Nuxeo](https://www.nuxeo.com/) * [Pipedrive](https://www.pipedrive.com) * [TUI](https://www.tui.com) * [TVG](https://www.tvg.com) * [Vodeno](https://www.vodeno.com/) * [Baloise](https://www.baloise.ch/) * [Michelin](https://www.michelin.com) ## Credits Many thanks to: * [JetBrains](https://www.jetbrains.com/?from=AKHQ) for their free OpenSource license. * Apache, Apache Kafka, Kafka, and associated open source project names are trademarks of the Apache Software Foundation. AKHQ is not affiliated with, endorsed by, or otherwise associated with the Apache Software. [![Jetbrains](https://user-images.githubusercontent.com/2064609/55432917-6df7fc00-5594-11e9-90c4-5133fbb6d4da.png)](https://www.jetbrains.com/?from=AKHQ) ## License Apache 2.0 © [tchiotludo](https://github.com/tchiotludo)
0
JCTools/JCTools
null
2013-11-10T18:04:40Z
null
[![Total alerts](https://img.shields.io/lgtm/alerts/g/JCTools/JCTools.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/JCTools/JCTools/alerts/) [![Coverage Status](https://coveralls.io/repos/github/JCTools/JCTools/badge.svg?branch=master)](https://coveralls.io/github/JCTools/JCTools?branch=master) [![Build Status](https://app.travis-ci.com/JCTools/JCTools.svg?branch=master)](https://app.travis-ci.com/JCTools/JCTools) JCTools ========== Java Concurrency Tools for the JVM. This project aims to offer some concurrent data structures currently missing from the JDK: - SPSC/MPSC/SPMC/MPMC variations for concurrent queues: * SPSC - Single Producer Single Consumer (Wait Free, bounded and unbounded) * MPSC - Multi Producer Single Consumer (Lock less, bounded and unbounded) * SPMC - Single Producer Multi Consumer (Lock less, bounded) * MPMC - Multi Producer Multi Consumer (Lock less, bounded) - SPSC/MPSC linked array queues (bounded and unbounded) offer a balance between performance, allocation and footprint - MPSC/MPMC XAdd based, unbounded linked array queues offer reduced contention costs for producers (using XADD instead of a CAS loop), and pooled queue chunks for reduced allocation. - An expanded queue interface (MessagePassingQueue): * relaxedOffer/Peek/Poll: trade off conflated guarantee on full/empty queue state with improved performance. * drain/fill: batch read and write methods for increased throughput and reduced contention Many queues are available in both `Unsafe` (default, uses `sun.mic.Unsafe`) and `Atomic` (relying on `AtomicFieldUpdater`) variations, as well as `Unpadded` (lower footprint by removing false sharing avoiding field padding). There's more to come and contributions/suggestions are most welcome. JCTools has enjoyed support from the community and contributions in the form of issues/tests/documentation/code have helped it grow. JCTools offers excellent performance at a reasonable price (FREE! under the Apache 2.0 License). It's stable and in use by such distinguished frameworks as Netty, RxJava and others. JCTools is also used by commercial products to great result. Get it NOW! ========== Add the latest version as a dependency using Maven: ```xml <dependency> <groupId>org.jctools</groupId> <artifactId>jctools-core</artifactId> <version>4.0.3</version> </dependency> ``` Or use the awesome, built from source, <https://jitpack.io/> version, you'll need to add the Jitpack repository: ```xml <repository> <id>jitpack.io</id> <url>https://jitpack.io</url> </repository> ``` And setup the following dependency: ```xml <dependency> <groupId>com.github.JCTools.JCTools</groupId> <artifactId>jctools-core</artifactId> <version>v4.0.3</version> </dependency> ``` You can also depend on latest snapshot from this repository (live on the edge) by setting the version to '4.0.4-SNAPSHOT'. Build it from source ========== JCTools is maven built and requires an existing Maven installation and JDK8 (only for building, runtime is 1.6 compliant). With 'MAVEN_HOME/bin' on the path and JDK8 set to your 'JAVA_HOME' you should be able to run "mvn install" from this directory. But I have a zero-dependency/single-jar project ========== While you are free to copy & extend JCTools, we would much prefer it if you have a versioned dependency on JCTools to enable better support, upgrade paths and discussion. The shade plugin for Maven/Gradle is the preferred way to get JCTools fused with your library. Examples are available in the [ShadeJCToolsSamples](https://github.com/JCTools/ShadeJCToolsSamples) project. Benchmarks ========== JCTools is benchmarked using both JMH benchmarks and handrolled harnesses. The benchmarks and related instructions can be found in the jctools-benchmarks module [README](jctools-benchmarks/README.md). Go wild and please let us know how it did on your hardware. Concurrency Testing =========== ``` mvn package cd jctools-concurrency-test java -jar target/concurrency-test.jar -v ``` Come up to the lab... ========== Experimental work is available under the jctools-experimental module. Most of the stuff is developed with an eye to eventually porting it to the core where it will be stabilized and released, but some implementations are kept purely for reference and some may never graduate. Beware the Jabberwock my child. Have Questions? Suggestions? ========== The best way to discuss JCTools is on the GitHub issues system. Any question is good, and GitHub provides a better platform for knowledge sharing than twitter/mailing-list/gitter (or at least that's what we think). Thanks!!! ===== We have kindly been awarded [IntelliJ IDEA](https://www.jetbrains.com/idea/) licences by [JetBrains](https://www.jetbrains.com/) to aid in the development of JCTools. It's a great suite of tools which has benefited the developers and ultimately the community. It's an awesome and inspiring company, [**BUY THEIR PRODUCTS NOW!!!**](https://www.jetbrains.com/store/#edition=commercial) JCTools has enjoyed a steady stream of PRs, suggestions and user feedback. It's a community! Thank you all for getting involved!
0
tmobile/pacbot
PacBot (Policy as Code Bot)
2018-09-18T20:55:41Z
null
[![Latest release](https://img.shields.io/github/release/tmobile/pacbot.svg)](https://github.com/tmobile/pacbot/releases/latest) [![Build Status](https://travis-ci.com/tmobile/pacbot.svg?token=k3NCeDUn4HM7urPbq4oz&branch=master)](https://travis-ci.com/tmobile/pacbot) [![GitHub license](https://github.com/tmobile/pacbot/blob/master/wiki/license_apache.svg)](https://github.com/tmobile/pacbot/blob/master/LICENSE) [![GitHub contributors](https://img.shields.io/github/contributors/tmobile/pacbot.svg)](https://github.com/tmobile/pacbot/graphs/contributors) [![Gitter](https://github.com/tmobile/pacbot/blob/master/wiki/images/chat.svg)](https://gitter.im/TMO-OSS/PacBot) <img src="./wiki/images/banner_magenta.png"> # Introduction Policy as Code Bot (PacBot) is a platform for continuous compliance monitoring, compliance reporting and security automation for the cloud. In PacBot, security and compliance policies are implemented as code. All resources discovered by PacBot are evaluated against these policies to gauge policy conformance. The PacBot auto-fix framework provides the ability to automatically respond to policy violations by taking predefined actions. PacBot packs in powerful visualization features, giving a simplified view of compliance and making it easy to analyze and remediate policy violations. PacBot is more than a tool to manage cloud misconfiguration, it is a generic platform that can be used to do continuous compliance monitoring and reporting for any domain. ## More Than Cloud Compliance Assessment PacBot's plugin-based data ingestion architecture allows ingesting data from multiple sources. We have built plugins to pull data from Qualys Vulnerability Assessment Platform, Bitbucket, TrendMicro Deep Security, Tripwire, Venafi Certificate Management, Redhat Satellite, Spacewalk, Active Directory and several other custom-built internal solutions. We are working to open source these plugins and other tools as well. You could write rules based on data collected by these plugins to get a complete picture of your ecosystem and not just cloud misconfigurations. For example, within T-Mobile we have implemented a policy to mark all EC2 instances having one or more severity 5 (CVSS score > 7) vulnerabilities as non-compliant. ## Quick Demo [![](http://img.youtube.com/vi/_WnuSU5tfcs/0.jpg)](https://www.youtube.com/embed/_WnuSU5tfcs "") ## How Does It Work? **Assess -> Report -> Remediate -> Repeat** Assess -> Report -> Remediate -> Repeat is PacBot's philosophy. PacBot discovers resources and assesses them against the policies implemented as code. All policy violations are recorded as an issue. Whenever an Auto-Fix hook is available with the policies, those auto-fixes are executed when the resources fail the evaluation. Policy violations cannot be closed manually, the issue has to be fixed at the source and PacBot will mark it closed in the next scan. Exceptions can be added to policy violations. Sticky exceptions (Exception based on resource attribute matching criteria) can be added to exempt similar resources that may be created in future. PacBot's Asset Groups are a powerful way to visualize compliance. Asset Groups are created by defining one or more target resource's attribute matching criteria. For example, you could create an Asset Group of all running assets by defining criteria to match all EC2 instances with attribute instancestate.name=running. Any new EC2 instance launched after the creation of the Asset Group will be automatically included in the group. In PacBot UI you can select the scope of the portal to a specific asset group. All the data points shown in the PacBot portal will be confined to the selected Asset Group. Teams using cloud can set the scope of the portal to their application or org and focus only on their policy violations. This reduces noise and provides a clear picture to cloud users. At T-Mobile, we create an Asset Groups per stakeholder, per application, per AWS account, per Environment etc. Asset groups can also be used to define the scope of rule executions as well. PacBot policies are implemented as one or more rules. These rules can be configured to run against all resources or a specific Asset Group. The rules will evaluate all resources in the asset group configured as the scope for the rule. This provides an opportunity to write policies which are very specific to an application or org. For example, some teams would like to enforce additional tagging standards apart from the global standards set for all of the cloud. They can implement such policies with custom rules and configure these rules to run only on their assets. ## PacBot Key Capabilities * Continuous compliance assessment. * Detailed compliance reporting. * Auto-Fix for policy violations. * Omni Search - Ability to search all discovered resources. * Simplified policy violation tracking. * Self-Service portal. * Custom policies and custom auto-fix actions. * Dynamic asset grouping to view compliance. * Ability to create multiple compliance domains. * Exception management. * Email Digests. * Supports multiple AWS accounts. * Completely automated installer. * Customizable dashboards. * OAuth Support. * Azure AD integration for login. * Role-based access control. * Asset 360 degree. ## Technology Stack * Front End - Angular * Backend End APIs, Jobs, Rules - Java * Installer - Python and Terraform ## Deployment Stack * AWS ECS & ECR - For hosting UI and APIs * AWS Batch - For rules and resource collection jobs * AWS CloudWatch Rules - For rule trigger, scheduler * AWS Redshift - Data warehouse for all the inventory collected from multiple sources * AWS Elastic Search - Primary data store used by the web application * AWS RDS - For admin CRUD functionalities * AWS S3 - For storing inventory files and persistent storage of historical data * AWS Lambda - For gluing few components of PacBot PacBot installer automatically launches all of these services and configures them. For detailed instruction on installation look at the installation documentation. ## PacBot UI Dashboards & Widgets * ##### Asset Group Selection Widget <img src=./wiki/images/asset-group-applications.png> * ##### Compliance Dashboard <img src=./wiki/images/compliance.png> <img src=./wiki/images/compliance2.png> * ##### Policy Compliance Page - S3 buckets public read access <img src=./wiki/images/policy-compliance.png> * ##### Policy Compliance Trend Over Time <img src=./wiki/images/compliance-trend.png> * ##### Asset Dashboard <img src=./wiki/images/assets.png> * ##### Asset Dashboard - With Recommendations <img src=./wiki/images/asset-recommendation.png> * ##### Asset 360 / Asset Details Page <img src=./wiki/images/asset-details.png> * ##### Linux Server Quarterly Patch Compliance <img src=./wiki/images/linux-patch-compliance.png> * ##### Omni-Search Page <img src=./wiki/images/omni-search.png> * ##### Search Results Page With Results filtering <img src=./wiki/images/search-results.png> * ##### Tagging Compliance Summary Widget <img src=./wiki/images/tagging-summary.png> ## Installation Detailed installation instructions are available [here](https://github.com/tmobile/pacbot/wiki/Install) ## Usage The installer will launch required AWS services listed in the [installation instructions](https://github.com/tmobile/pacbot/wiki/Install). After successful installation, open the UI load balancer URL. Log into the application using the credentials supplied during the installation. The results from the policy evaluation will start getting populated within an hour. Trendline widgets will be populated when there are at least two data points. When you install PacBot, the AWS account where you install is the base account. PacBot installed on the base account can monitor other target AWS accounts. Refer to the instructions [here](https://github.com/tmobile/pacbot/wiki/Install#adding-new-aws-accounts-to-pacbot-to-monitor) to add new accounts to PacBot. By default base account will be monitored by PacBot. Login as Admin user and go to the Admin page from the top menu. In the Admin section, you can 1. Create/Manage Policies 2. Create/Manage Rules and associate Rules with Policies 3. Create/Manage Asset Groups 4. Create/Manage Sticky Exception 5. Manage Jobs 6. Create/Manage Access Roles 7. Manage PacBot Configurations See detailed instruction with screenshots on how to use the admin feature [here](https://github.com/tmobile/pacbot/wiki/Admin-Features ) ## User Guide / Wiki Wiki is [here](https://github.com/tmobile/pacbot/wiki). ## Announcement Blog Post [Introducing PacBot](https://opensource.t-mobile.com/blog/posts/introducing-pacbot/) ## License PacBot is open-sourced under the terms of section 7 of the Apache 2.0 license and is released AS-IS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
0
geotools/geotools
Official GeoTools repository
2011-11-10T23:22:12Z
null
![GeoTools logo](/geotools-logo.png) [GeoTools](http://geotools.org) is an open source Java library that provides tools for geospatial data. Our Users guide provides an [overview](http://docs.geotools.org/latest/userguide/geotools.html) of the core features, supported formats and standards support. [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5854676.svg)](https://doi.org/10.5281/zenodo.5854676) ## License GeoTools is licensed under the [LGPL](http://www.gnu.org/licenses/lgpl.html). The user guide [license](http://docs.geotools.org/latest/userguide/welcome/license.html) page describes the less restrictive license for documentation and source code examples. ## Contributing The developers guide outlines ways to [contribute ](http://docs.geotools.org/latest/developer/procedures/contribute.html) to GeoTools using patches, pull requests and setting up new modules. If you are already experienced with GitHub please check our [pull request](http://docs.geotools.org/latest/developer/procedures/pull_requests.html) page before you start! ## Building GeoTools uses [Apache Maven](http://maven.apache.org/) for a build system. To build the library run maven from the root of the repository. % mvn clean install See the [user guide](http://docs.geotools.org/latest/userguide/build/index.html) for more details. ## Bugs GeoTools uses [JIRA](https://osgeo-org.atlassian.net/browse/GEOT), hosted by [Atlassian](https://www.atlassian.com/), for issue tracking. ## Mailing Lists The [user list](mailto:geotools-gt2-users@lists.sourceforge.net) is for all questions related to GeoTools usage. The [dev list](mailto:geotools-devel@lists.sourceforge.net) is for questions related to hacking on the GeoTools library itself. ## More Information Visit the [website](http://geotools.org/) or read the [docs](http://docs.geotools.org/).
0
FlowCI/flow-core-x
Powerful and user-friendly CI/CD server with high availability, parallel processing, runner auto-scaling
2017-05-03T07:03:17Z
null
<h3 align="center"> <a href="https://flowci.github.io"> <img src="https://github.com/FlowCI/docs/raw/master/_images/logo.png" alt="Logo" width="100"> </a> </h3> <h3 align="center">A Simple & Powerful CI/CD Server</h3> <p align="center"> <a href="https://github.com/FlowCI/docs/blob/master/LICENSE"><img src="https://img.shields.io/github/license/flowci/flow-core-x"></a> <a href="https://github.com/FlowCI/flow-core-x/releases/"><img src="https://img.shields.io/github/v/release/flowci/flow-core-x"></a> <a href="https://github.com/FlowCI"><img alt="GitHub Org's stars" src="https://img.shields.io/github/stars/flowci"></a> <a href="https://hub.docker.com/u/flowci"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/flowci/core"></a> </p> <div align="center"> </div> ## What is flow.ci? flow.ci is an open-source CI/CD automation server that designed for setting up a self-hosted CI/CD service with the easiest, fastest and most painless way. It supports high availability, multiple building environment, and scalability with dynamic agents. - __High Availability__ flow.ci is designed to work in the cloud -- public, private, or hybrid, it could be deployed with multiple instances, the configuration/jobs data on the node may not be lost when the instance fails. - __High Performance__ - __scaling__: auto scaling agents either on K8s cluster or Linux host - __parallel__: job steps can be executed in parallel on multiple agents - __cache__: cache anything to speed up the build - __Zero Configuration__ flow.ci tries to minimize the complexity of any configuration, the server could be started with three command lines. It also provides build templates of many programming languages, a job could be started just using it. - __Online Debugging__ flow.ci supports the online TTY terminal so that you could find out the problems in the running job from runtime terminal. - __Flexible Plugins__ Using plugins on flow.ci is quite simple, you just need type the plugin name in the step. Developing a plugin is also quite easy, you could use any language on your own plugin development. - __Flexible Runtime__ Each step or step group can be run either on any docker images or native os. ## Quick start > [Docker](https://docs.docker.com/install/) & [Docker-Compose](https://docs.docker.com/compose/install/) are required ```bash git clone https://github.com/FlowCI/docker.git flow-docker cd flow-docker ./server.sh start ``` ## Documentation + [English](https://flowci.github.io/#/en/) + [中文文档](https://flowci.github.io/#/cn/) Need Help? submit issue from [here](https://github.com/FlowCI/docs/issues) or send email to `flowci@foxmail.com` ## Templates [maven, npm, golang, ruby, android and more](https://github.com/FlowCI/templates) ## Architecture ![architecture](https://github.com/FlowCI/docs/raw/master/_images/architecture.png) ## Preview ![demo](https://github.com/FlowCI/docs/raw/master/_images/demo.gif)
0
alibaba/jvm-sandbox
Real - time non-invasive AOP framework container based on JVM
2017-08-03T02:55:31Z
null
# ![BANNER](https://github.com/alibaba/jvm-sandbox/wiki/img/BANNER.png) [![Build Status](https://travis-ci.org/alibaba/jvm-sandbox.svg?branch=master)](https://travis-ci.org/alibaba/jvm-sandbox) [![codecov](https://codecov.io/gh/alibaba/jvm-sandbox/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/jvm-sandbox) [![Average time to resolve an issue](http://isitmaintained.com/badge/resolution/alibaba/jvm-sandbox.svg)](http://isitmaintained.com/project/alibaba/jvm-sandbox "Average time to resolve an issue") [![Percentage of issues still open](http://isitmaintained.com/badge/open/alibaba/jvm-sandbox.svg)](http://isitmaintained.com/project/alibaba/jvm-sandbox "Percentage of issues still open") > JVM沙箱容器,一种JVM的非侵入式运行期AOP解决方案<br/> > Real - time non-invasive AOP framework container based on JVM ## 目标群体 - [BTRACE](https://github.com/btraceio/btrace)好强大,也曾技痒想做一个更便捷、更适合自己的问题定位工具,既可支持线上链路监控排查,也可支持单机版问题定位。 - 有时候突然一个问题反馈上来,需要入参才能完成定位,但恰恰没有任何日志,甚至出现在别人的代码里,好想开发一个工具可以根据需要动态添加日志,最好还能按照业务ID进行过滤。 - 系统间的异常模拟可以使用的工具很多,可是系统内的异常模拟怎么办,加开关或是用AOP在开发系统中实现,好想开发一个更优雅的异常模拟工具,既能模拟系统间的异常,又能模拟系统内的异常。 - 好想获取行调用链路数据,可以用它识别场景、覆盖率统计等等,覆盖率统计工具不能原生支持,统计链路数据不准确。想自己开发一个工具获取行链路数据。 - 我想开发录制回放、故障模拟、动态日志、行链路获取等等工具,就算我开发完成了,这些工具底层实现原理相同,同时使用,要怎么消除这些工具之间的影响,怎么保证这些工具动态加载,怎么保证动态加载/卸载之后不会影响其他工具,怎么保证在工具有问题的时候,快速消除影响,代码还原 如果你有以上研发诉求,那么你就是JVM-SANDBOX(以下简称沙箱容器)的潜在客户。沙箱容器提供 1. 动态增强类你所指定的类,获取你想要的参数和行信息甚至改变方法执行 2. 动态可插拔容器框架 ## 项目简介 **JVM-SANDBOX(沙箱)实现了一种在不重启、不侵入目标JVM应用的AOP解决方案。** ### 沙箱的特性 1. `无侵入`:目标应用无需重启也无需感知沙箱的存在 2. `类隔离`:沙箱以及沙箱的模块不会和目标应用的类相互干扰 3. `可插拔`:沙箱以及沙箱的模块可以随时加载和卸载,不会在目标应用留下痕迹 4. `多租户`:目标应用可以同时挂载不同租户下的沙箱并独立控制 5. `高兼容`:支持JDK[6,11] ### 沙箱常见应用场景 - 线上故障定位 - 线上系统流控 - 线上故障模拟 - 方法请求录制和结果回放 - 动态日志打印 - 安全信息监测和脱敏 *JVM-SANDBOX还能帮助你做很多很多,取决于你的脑洞有多大了。* ### 实时无侵入AOP框架 在常见的AOP框架实现方案中,有静态编织和动态编织两种。 1. **静态编织**:静态编织发生在字节码生成时根据一定框架的规则提前将AOP字节码插入到目标类和方法中,实现AOP; 2. **动态编织**:动态编织则允许在JVM运行过程中完成指定方法的AOP字节码增强.常见的动态编织方案大多采用重命名原有方法,再新建一个同签名的方法来做代理的工作模式来完成AOP的功能(常见的实现方案如CgLib),但这种方式存在一些应用边界: - **侵入性**:对被代理的目标类需要进行侵入式改造。比如:在Spring中必须是托管于Spring容器中的Bean - **固化性**:目标代理方法在启动之后即固化,无法重新对一个已有方法进行AOP增强 要解决`无侵入`的特性需要AOP框架具备 **在运行时完成目标方法的增强和替换**。在JDK的规范中运行期重定义一个类必须准循以下原则 1. 不允许新增、修改和删除成员变量 2. 不允许新增和删除方法 3. 不允许修改方法签名 JVM-SANDBOX属于基于Instrumentation的动态编织类的AOP框架,**通过精心构造了字节码增强逻辑,使得沙箱的模块能在不违反JDK约束情况下实现对目标应用方法的`无侵入`运行时AOP拦截**。 ## 核心原理 ### 事件驱动 在沙箱的世界观中,任何一个Java方法的调用都可以分解为`BEFORE`、`RETURN`和`THROWS`三个环节,由此在三个环节上引申出对应环节的事件探测和流程控制机制。 ```java // BEFORE try { /* * do something... */ // RETURN return; } catch (Throwable cause) { // THROWS } ``` 基于`BEFORE`、`RETURN`和`THROWS`三个环节事件分离,沙箱的模块可以完成很多类AOP的操作。 1. 可以感知和改变方法调用的入参 2. 可以感知和改变方法调用返回值和抛出的异常 3. 可以改变方法执行的流程 - 在方法体执行之前直接返回自定义结果对象,原有方法代码将不会被执行 - 在方法体返回之前重新构造新的结果对象,甚至可以改变为抛出异常 - 在方法体抛出异常之后重新抛出新的异常,甚至可以改变为正常返回 ### 类隔离策略 沙箱通过自定义的SandboxClassLoader破坏了双亲委派的约定,实现了和目标应用的类隔离。所以不用担心加载沙箱会引起应用的类污染、冲突。各模块之间类通过ModuleJarClassLoader实现了各自的独立,达到模块之间、模块和沙箱之间、模块和应用之间互不干扰。 ![jvm-sandbox-classloader](https://github.com/alibaba/jvm-sandbox/wiki/img/jvm-sandbox-classloader.png) ### 类增强策略 沙箱通过在BootstrapClassLoader中埋藏的Spy类完成目标类和沙箱内核的通讯 ![jvm-sandbox-enhance-class](https://github.com/alibaba/jvm-sandbox/wiki/img/jvm-sandbox-enhance-class.jpg) ### 整体架构 ![jvm-sandbox-architecture](https://github.com/alibaba/jvm-sandbox/wiki/img/jvm-sandbox-architecture.png) ## 快速安装 - **下载并安装或自行打包** ```shell # 下载最新版本的JVM-SANDBOX,oss已到期,或者oss链接不可访问时,可选择自行打包 wget https://ompc.oss-cn-hangzhou.aliyuncs.com/jvm-sandbox/release/sandbox-1.3.3-bin.zip # 解压 unzip sandbox-1.3.3-bin.zip ``` ```shell #自行打包 cd bin ./sandbox-packages.sh #target路径下有多种构建件类型,选择一个合适的使用 cd ../target ``` - **挂载目标应用** ```shell # 进入沙箱执行脚本 cd sandbox/bin # 目标JVM进程33342 ./sandbox.sh -p 33342 ``` - **挂载成功后会提示** ```shell ./sandbox.sh -p 33342 NAMESPACE : default VERSION : 1.2.0 MODE : ATTACH SERVER_ADDR : 0.0.0.0 SERVER_PORT : 55756 UNSAFE_SUPPORT : ENABLE SANDBOX_HOME : /Users/vlinux/opt/sandbox SYSTEM_MODULE_LIB : /Users/vlinux/opt/sandbox/module USER_MODULE_LIB : ~/.sandbox-module; SYSTEM_PROVIDER_LIB : /Users/vlinux/opt/sandbox/provider EVENT_POOL_SUPPORT : DISABLE ``` - **卸载沙箱** ```shell ./sandbox.sh -p 33342 -S jvm-sandbox[default] shutdown finished. ``` ## 项目构建 当你修改了sandbox的代码后,想打包成自己需要的发行版,可以执行以下命令 > 脚本执行目录默认为项目主目录,后续不在另外说明 ```shell cd bin ./sandbox-package.sh ``` 命令执行成功后会在target目录下生成`sandbox-<版本号>-bin.zip`文件 ### 构建注意事项 1. 必须用JDK1.8进行构建,工程自身和maven插件中使用了tools.jar 2. 必须在Linux/Mac/Unix下进行构建,有部分测试用例没有考虑好$USER_HOME的目录路径在windows下的特殊性,会导致测试用例跑不通过。 ### 修改sandbox版本号 sandbox的版本号需要修改所有的pom文件以及`.//sandbox-core/src/main/resources/com/alibaba/jvm/sandbox/version`,这里有一个脚本方便执行 ```shell cd bin ./set-version.sh -s 1.4.0 ``` 脚本第一个参数是`[s|r]` - **s** : SNAPSHOT版,会自动在版本号后边追加`-SNAPSHOT` - **r** : 正式版 ### 本地仓库安装api包 如果本次你修改了sandbox-api、sandbox-common-api、sandbox-module-starter等本应该发布到中央仓库的包,但你需要本地测试验证,可以执行以下命令 ```shell mvn clean install ``` 以下四个包将会安装到本地manven仓库 - sandbox - sandbox-api - sandbox-common-api - sandbox-module-starter - sandbox-provider-api ## 项目背景 2014年[GREYS](https://github.com/oldmanpushcart/greys-anatomy)第一版正式发布,一路看着他从无到有,并不断优化强大,感慨羡慕之余,也在想GREYS是不是只能做问题定位。 2015年开始根据GREYS的底层代码完成了人生的第一个字节码增强工具——动态日志。之后又萌生了将其拆解成*录制回放*、*故障模拟*等工具的想法。扪心自问,我是想以一人一个团队的力量建立大而全的工具平台,还是做一个底层中台,让每一位技术人员都可以在它的基础上快速的实现业务功能。我选择了后者。 ## 相关文档 - **[WIKI](https://github.com/alibaba/jvm-sandbox/wiki/Home)**
0
methusalah/OpenRTS
Real-Time Strategy game 3D engine coded in pure java
2014-08-11T08:20:35Z
null
![please report broken links](https://s9.postimg.cc/9nsfu0wlr/code118.png) **<a href="https://twitter.com/dumas181" target="_blank">Follow me on twitter !</a>** # What is OpenRTS? OpenRTS is a 3D real-time strategy game engine. It's coded in Java 1.8, powered by jMonkeyEngine 3, and is open-source. OpenRTS intends to support any kind of common real-time strategy gameplay, design and control, providing its own editor and a versatile data structure. The project also wants to be a pool of RTS resources, giving access to a large and free-to-use set of maps, models, sounds, armies' data, and gameplays. OpenRTS is still under development. There is a long way to go and a huge and growing <a href="#github-issues-our-todo-list">TODO list</a>. We will be glad to receive any of your contributions! Watch <a href="https://www.youtube.com/watch?v=XjYJWFQFIVE" target="_blank">the engine in action!</a> # How to set up? The project uses Gradle to support any IDE, or none. Just <a href="https://help.github.com/articles/cloning-a-repository/" target="_blank">clone the repository</a>, then at the command-line in the clone's root directory run "`./gradlew run`" (or "`gradlew.bat run`" on windows). You want to set up in your favorite IDE like jMonkey SDK or Eclipse? Simple! Please follow <a href="https://github.com/methusalah/OpenRTS/wiki/Set-up-the-project-with-your-favorite-IDE-(Eclipse,-Netbeans,-etc.)" target="_blank">this page</a> of the wiki. The engine is set by default with a test dataset and some example maps you can load. - **F1** : Game Mode (static iso camera) - **F2** : Editor Mode - **F3** : First Person view (for testing purpose) # Need Help? First, you should take a look at the <a href="https://github.com/methusalah/OpenRTS/wiki" target="_blank">wiki</a>. Then you will likely want to go to the <a href="http://hub.jmonkeyengine.org/c/user-code-projects/openrts" target="_blank">forum</a>. And of course, you shouldn't hesitate to write to us at openRTS.team@gmail.com # How to contribute? You want to participate and make OpenRTS a fully functional game engine? Please do&mdash;the more the merrier! ### Forum The best place to start if you would like to contribute is in the <a href="http://hub.jmonkeyengine.org/c/user-code-projects/openrts" target="_blank">OpenRTS forum</a>! Join in on debates and brainstormings about how to make OpenRTS better. The forum is also the best place to meet our awesome team. ### GitHub issues, our TODO list We've got plenty of things you can work on right now, check our <a href="https://github.com/methusalah/OpenRTS/issues" target="_blank">current open issues</a>. And we will be happy to add your requested features to the <a href="https://github.com/methusalah/OpenRTS/labels/enhancement" target="_blank">enhancement list</a>. ### Resources OpenRTS wants to provide its own complete and workable dataset to allow immediate RTS creation. We are glad to welcome all your creations : models, sounds, maps, particle sprites, army data... And if your contribution respects the current <a href="https://pinterest.com/search/pins/?q=low%20poly" target="_blank">low-poly art style</a>, so much the only better! Please note that all your contributions will fall under the OpenRTS licence, and will become public and free-to-use, as is the engine itself. **Finaly, following (<a href="https://twitter.com/dumas181" target="_blank">twitter</a>), starring and sharing helps a lot !** ### Bug report If you find a bug (and you will probably see many), please search for existing <a href="https://github.com/methusalah/OpenRTS/issues?q=is%3Aopen+is%3Aissue+label%3Abug" target="_blank">bug reports</a> to avoid duplicates. Then open your issue with a little test case. You can also report it on the forum, if you prefer. # Licensing OpenRTS is released under the <a href="http://choosealicense.com/licenses/mit/" target="_blank">MIT License</a>, which will also apply to any contributions made to OpenRTS. See the file <a href="https://raw.githubusercontent.com/methusalah/OpenRTS/master/LICENSE" target="_blank">LICENSE</a>. ![please report broken links](http://s22.postimg.org/6j8jb89q9/5109be301e18c8bdeebafa35823b7f88a5af1555.png)
0
peng-zhihui/DeepVision
在我很多项目中用到的CV算法推理框架应用。
2020-07-27T11:10:17Z
null
## 前言 一个算法模型的落地需要经历从算法任务确立,到方法调研、模型选型和优化、数据采集标定、模型训练、部署验证等一整个pipeline,其中对于绝大多数的算法工程师,模型的训练和输出是没有问题的,但是要快速地进行模型在移动设备上的效果验证,则需要移动端开发人员和配合才能完成。另一方面,考虑到团队内CV算法研究方向很多,如果每个模型都单独在移动端开发一套验证APP的话显然费时费力,重复造轮子。 ![](img/1.jpg) 为了解决模型移动端部署验证困难,以及每个模型都单独在移动端开发一套验证APP带来的重复工作的问题,本项目实现了CV算法快速验证框架项目,旨在提供一套通用的CV算法验证框架。框架经过本人一年多的开发和维护,目前已经完成绝大部分API的开发,实现包括实时视频流模块、单帧图像处理模块、3D场景模块、云端推理模块等众多功能。 > **大家可以看到我做的很多其他项目都用到了这个框架,比如L-ink、火星车等,本仓库将这个框架的非核心部分开源出来,代码里整合了重新编译的OpenCV native和JAVA库,大家可以自己扩展用于实现自己的项目。** ## CV算法验证框架设计 构建包含推理的应用程序所涉及的不仅仅是运行深度学习推理模型,开发者还需要做到以下几点: - 利用各种设备的功能 - 平衡设备资源使用和推理结果的质量 - 通过流水线并行运行多个操作 - 确保时间序列数据同步正确 本框架解决了这些挑战,将上述软件框架解耦为`数据流控制层`、`nn推理引擎层`,以及`UI层`进行框架实现,把数据流处理管道构建为模块化组件,包括推理处理模型和媒体处理功能等。 * 其中数据流控制层包含三个大的模块 -- 视频流模块、图片和编辑模块、3D场景模块,每个模块提供可供配置的数据流参数接口,同时提供了一些常用的工具包如`OpenCV`、`QVision`等用于作为模型的数据输入和预处理。 * nn推理引擎层则集成了一些移动端常用的推理框架比如`SNPE`、`TensorFlow Lite`等,并提供统一模板便于后续持续维护扩展其他推理框架。 * UI层则封装好了图像渲染模块,以及各种调试控件。在API方面,该算法验证框架提供了Native/JAVA/Script三个层次的API,前两者可以在Android工程中进行快速模型集成,Script API则不需要编写任何APP 代码,通过文本脚本解析的形式配置模型推理选项。 通过以上功能使开发者可以专注于算法或模型开发,并使用本框架作为迭代改进其应用程序的环境,其结果可在不同的设备和平台上重现。 下图是本框架的模块划分架构图: ![](img/2.jpg) ## API接口说明 从图中各个模块的名字可以看出个模块的功能,输入是转换好的算法模型,以及图像数据流,其中图像数据流分为摄像头采集的视频数据帧、相册选取的单帧图像,以及应用于3DCNN的3维模型文件。 本框架提供了Native/JAVA/Script三个层次的API,前两者可以在Android工程中进行快速模型集成,其中Native为C/C++接口,提供JNI模板以及封装好的通信组件便于和JAVA进行数据交互;JAVA层则为Android API,使用和C++一样风格的进行封装,此外提供一些UI绘制函数接口;Script API则不需要编写任何APP 代码,通过文本脚本解析的形式配置模型推理选项。 举例在JAVA API下,算法模型在代码中的初始化方式如下,以高通平台的SNPE Runtime为例,只需要几行非常简单的代码即可加载并初始化模型: ![](img/3.jpg) 如代码所示,模型文件的加载方式比较灵活,可以作为FileInputStream加载,也可以作为APP的Asset进行加载。 而图像数据的预处理和结果回调使用也非常简单,通过提供的OpenCV、QVison等CV库封装接口,可以方便地调取很多图像处理函数: ![](img/4.jpg) 其中常用的一些操作比如数据的归一化等函数都经过底层优化,保证数据一致性和高效性,比如数据类型的转换使用了zero-copy: ![](img/5.jpg) 同时OpenCV的编译开启了NEON指令、OpenMP多核等加速选项,对于图像的归一化等操作可以做到并行化加速。 **具体的接口reference说明请参考工程代码。** ## 模型优化算法实现和工具封装 除了APP侧的接口外,本CV算法验证框架提供了一套配套的模型优化工具,包括: * 模型8bit量化工具 * 模型结构化剪枝工具 * 模型转换工具 使用TensorFlow或者PyTorch等Training框架训练好的pb、pth、onnx等模型文件并不能直接在移动端进行部署运行,而是需要做一些模型转换工作,本框架将各种转换工具打包,提供了一套方便的模型转换工具。 其中的模型量化工具基于TensorFlow的TOCO、Pytorch的QNNPACK等实现。 剪枝工具则是根据论文**Learning Efficient Convolutional Networks Through Network Slimming (ICCV 2017)**提到的模型剪枝方法进行复现实现的。 模型转换工具和具体的Inference Runtime有关,比如SNPE则是使用DLC转换脚本、TensorFlow使用的是TF Lite转换工具等等。 ![](img/6.jpg) 如上图所示,除了模型优化工具,框架的工具包中还提供了一些预训练和部署好的Model Zoo,用于做同平台性能对比测试的Baseline,目前以及实现部署好的有YOLO、MTCNN、Openpose等模型。 ## 框架在移动端的实际效果 > * Camera视频流、单帧图像,以及3D场景模块选择 > > * 同一框架下可以同时验证多个算法模型 > * 模型实际运行效果 ![](img/7.jpg)
0
andkulikov/Transitions-Everywhere
Set of extra Transitions on top of Jetpack Transitions Library
2014-10-15T03:37:03Z
null
Transitions Everywhere ============ Set of extra Transitions on top of [AndroidX Transitions Library][1]. About ============ [Article about transitions and library][2]<br> Originally this library was a full backport of Android Platform's Transitions API.<br> Then all the bug fixes from the library were ported into AndroidX Transitions (previously Support library).<br> Now this lib has minSdk version <b>14</b> (Android 4.0 ICS) and consist of some transitions which are not a part of the official set: 1) Internal Transitions that was marked as @hide in the platform: <b>Recolor</b>, <b>Rotate</b>, <b>ChangeText</b> and <b>Crossfade</b>. 2) Two extra transitions: <b>Scale</b> and <b>Translation</b>.<br><br> Quick start ============ This version should be used if you are specifying 29 (Q) as a `targetSdkVersion`: ```groovy dependencies { implementation "com.andkulikov:transitionseverywhere:2.1.0" } ``` Otherwise, if you specify 29 as `targetSdkVersion` some of the transitions will not work properly. Instead of the reflection calls this version uses the new public methods added in API Level 29. It is based on <b>androidx.transition:transition:1.2.0</b>. Previous version if you are not yet on 29 (Q) SDK: ```groovy dependencies { implementation "com.andkulikov:transitionseverywhere:2.0.0" } ``` This version is based on <b>androidx.transition:transition:1.1.0</b>. Migration from 1.x guide ============ 1) Migrate to <b>AndroidX</b>! Support libraries are not updating anymore, to get all the bug fixes you have to use AndroidX transitions. 2) Replace imports from <b>com.transitionseverywhere.</b> to <b>androidx.transition.</b> for all the classes which are a part of the AndroidX lib. 3) If you were using <b>Transition.TransitionListenerAdapter</b> class use <b>TransitionListenerAdapter</b> now. 4) Instead of <b>TransitionManager.setTransitionName()</b> use <b>ViewCompat.setTransitionName()</b>. 5) If you were inflating transitions via xml move your files from <b>anim</b> folder to <b>transition</b> and use <b>android:</b> namespace instead of <b>app:</b> 6) Some setters in AndroidX transitions are not following the builder pattern, please rewrite this usages with introducing a helper variable if you encounter the issue. 7) Instead of <b>TranslationTransition</b> use <b>Translation</b>. Articles about the version 1.x ============ [Article about transitions and library][2]<br> [Russian version][3]<br> Chinese: [version 1][5], [version 2][6]<br> [Changelog for version 1.x][4] ============ [1]: https://developer.android.com/reference/androidx/transition/package-summary [2]: https://medium.com/@andkulikov/animate-all-the-things-transitions-in-android-914af5477d50 [3]: http://habrahabr.ru/post/243363/ [4]: https://github.com/andkulikov/Transitions-Everywhere/blob/master/library(1.x)/CHANGELOG.md [5]: https://yanlu.me/animate-all-the-things-transitions-in-android/ [6]: http://www.jianshu.com/p/98f2ec280945 [7]: https://medium.com/@andkulikov/support-library-for-transitions-overview-and-comparison-c41be713cf8c
0
apache/tomcat
Apache Tomcat
2011-10-01T07:00:19Z
null
## Welcome to Apache Tomcat! ### What Is It? The Apache Tomcat® software is an open source implementation of the Jakarta Servlet, Jakarta Pages, Jakarta Expression Language and Jakarta WebSocket technologies. The Jakarta Servlet, Jakarta Pages, Jakarta Expression Language and Jakarta WebSocket specifications are developed as part of the [Jakarta EE Platform](https://jakarta.ee/specifications/). The Apache Tomcat software is developed in an open and participatory environment and released under the [Apache License version 2](https://www.apache.org/licenses/). The Apache Tomcat project is intended to be a collaboration of the best-of-breed developers from around the world. We invite you to participate in this open development project. To learn more about getting involved, [click here](https://tomcat.apache.org/getinvolved.html) or keep reading. Apache Tomcat software powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations. Some of these users and their stories are listed on the [PoweredBy wiki page](https://cwiki.apache.org/confluence/display/TOMCAT/PoweredBy). Apache Tomcat, Tomcat, Apache, the Apache feather, and the Apache Tomcat project logo are trademarks of the Apache Software Foundation. ### Get It For every major Tomcat version there is one download page containing links to the latest binary and source code downloads, but also links for browsing the download directories and archives: - [Tomcat 11](https://tomcat.apache.org/download-11.cgi) - [Tomcat 10](https://tomcat.apache.org/download-10.cgi) - [Tomcat 9](https://tomcat.apache.org/download-90.cgi) To facilitate choosing the right major Tomcat version one, we have provided a [version overview page](https://tomcat.apache.org/whichversion.html). ### Documentation The documentation available as of the date of this release is included in the docs webapp which ships with tomcat. You can access that webapp by starting tomcat and visiting <http://localhost:8080/docs/> in your browser. The most up-to-date documentation for each version can be found at: - [Tomcat 11](https://tomcat.apache.org/tomcat-11.0-doc/) - [Tomcat 10](https://tomcat.apache.org/tomcat-10.1-doc/) - [Tomcat 9](https://tomcat.apache.org/tomcat-9.0-doc/) ### Installation Please see [RUNNING.txt](RUNNING.txt) for more info. ### Licensing Please see [LICENSE](LICENSE) for more info. ### Support and Mailing List Information * Free community support is available through the [tomcat-users](https://tomcat.apache.org/lists.html#tomcat-users) email list and a dedicated [IRC channel](https://tomcat.apache.org/irc.html) (#tomcat on Freenode). * If you want freely available support for running Apache Tomcat, please see the resources page [here](https://tomcat.apache.org/findhelp.html). * If you want to be informed about new code releases, bug fixes, security fixes, general news and information about Apache Tomcat, please subscribe to the [tomcat-announce](https://tomcat.apache.org/lists.html#tomcat-announce) email list. * If you have a concrete bug report for Apache Tomcat, please see the instructions for reporting a bug [here](https://tomcat.apache.org/bugreport.html). ### Contributing Please see [CONTRIBUTING](CONTRIBUTING.md) for more info.
0
vavr-io/vavr
vʌvr (formerly called Javaslang) is a non-commercial, non-profit object-functional library that runs with Java 8+. It aims to reduce the lines of code and increase code quality.
2014-01-30T14:07:25Z
null
[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/vavr-io/vavr) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT) [![GitHub Release](https://img.shields.io/github/release/vavr-io/vavr.svg?style=flat-square)](https://github.com/vavr-io/vavr/releases) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.vavr/vavr/badge.svg?style=flat-square)](http://search.maven.org/#search|gav|1|g:"io.vavr"%20AND%20a:"vavr") [![Build Status](https://img.shields.io/travis/vavr-io/vavr.svg?branch=master&style=flat-square)](https://travis-ci.org/vavr-io/vavr) [![Code Coverage](https://codecov.io/gh/vavr-io/vavr/branch/master/graph/badge.svg)](https://codecov.io/gh/vavr-io/vavr) [![Gitter Chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/vavr-io/vavr) [![donate](https://img.shields.io/badge/Donate-PayPal-blue.svg?logo=paypal&style=flat-square)](https://paypal.me/danieldietrich13) [![vavr-logo](https://user-images.githubusercontent.com/743833/62367542-486f0500-b52a-11e9-815e-e9788d4c8c8d.png)](http://vavr.io/) Vavr is an object-functional language extension to Java 8, which aims to reduce the lines of code and increase code quality. It provides persistent collections, functional abstractions for error handling, concurrent programming, pattern matching and much more. Vavr fuses the power of object-oriented programming with the elegance and robustness of functional programming. The most interesting part is a feature-rich, persistent collection library that smoothly integrates with Java's standard collections. Because Vavr does not depend on any libraries (other than the JVM) you can easily add it as standalone .jar to your classpath. To stay up to date please follow the [blog](http://blog.vavr.io). ## Using Vavr See [User Guide](http://docs.vavr.io) and/or [Javadoc](http://www.javadoc.io/doc/io.vavr/vavr). ### Gradle tasks: * Build: `./gradlew check` * test reports: `./build/reports/tests/test/index.html` * coverage reports: `./build/reports/jacoco/test/html/index.html` * Javadoc (linting): `./gradlew javadoc` ### Contributing A small number of users have reported problems building Vavr. Read our [contribution guide](./CONTRIBUTING.md) for details.
0
gh0stkey/HaE
HaE - Highlighter and Extractor, Empower ethical hacker for efficient operations.
2020-03-24T10:12:50Z
null
<div align="center"> <img src="images/logo.png" style="width: 20%" /> <h4><a href="https://gh0st.cn/HaE/">赋能白帽,高效作战!</a></h4> <h5>第一作者: <a href="https://github.com/gh0stkey">EvilChen</a>(中孚信息元亨实验室), 第二作者: <a href="https://github.com/0chencc">0chencc</a>(米斯特安全团队)</h5> </div> ## 项目介绍 **HaE**是一款网络安全(数据安全)领域下的辅助型框架式项目,旨在实现对HTTP消息(包含WebSocket)的高亮标记和信息提取。本项目通过自定义正则表达式匹配响应报文或请求报文,并对匹配成功的报文进行标记和提取。 > 随着现代化Web应用采用前后端分离的开发模式,日常漏洞挖掘的过程中,捕获的HTTP请求流量也相应增加。若想全面评估一个Web应用,会花费大量时间在无用的报文上。**HaE的出现旨在解决这类情况**,借助HaE,您能够**有效减少**测试时间,将更多精力集中在**有价值且有意义**的报文上,从而**提高漏洞挖掘效率**。 **注意事项**: 1. 由于HaE 3.0版本开始采用`Montoya API`进行开发,因此使用新版HaE需要升级你的BurpSuite版本(>=2023.12.1)。 2. 由于HaE 2.6版本后对规则字段进行了更新,因此无法适配<=2.6版本的规则,请用户自行前往[规则转换页面](https://gh0st.cn/HaE/ConversionRule.html)进行转换。 3. HaE官方规则库存放在[Github](https://raw.githubusercontent.com/gh0stkey/HaE/gh-pages/Rules.yml)上,因此默认加载HaE官方规则库需使用代理(BApp审核不允许使用CDN)。 4. 自定义HaE规则必须用左右括号`()`将所需提取的表达式内容包含,例如你要匹配一个**Shiro应用**的响应报文,正常匹配规则为`rememberMe=delete`,在HaE的规则中就需要变成`(rememberMe=delete)`。 ## 使用方法 插件装载: `Extender - Extensions - Add - Select File - Next` 初次装载`HaE`会自动获取官方规则库`https://raw.githubusercontent.com/gh0stkey/HaE/gh-pages/Rules.yml`,配置文件(`Config.yml`)和规则文件(`Rules.yml`)会放在固定目录下: 1. Linux/Mac用户的配置文件目录:`~/.config/HaE/` 2. Windows用户的配置文件目录:`%USERPROFILE%/.config/HaE/` 除此之外,您也可以选择将配置文件存放在`HaE Jar包`的同级目录下的`/.config/HaE/`中,**以便于离线携带**。 ### 规则释义 HaE目前的规则一共有8个字段,分别是规则名称、规则正则、规则作用域、正则引擎、规则匹配颜色、规则敏感性。 详细的含义如下所示: | 字段 | 含义 | |-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Name | 规则名称,主要用于简短概括当前规则的作用。 | | F-Regex | 规则正则,主要用于填写正则表达式。在HaE中所需提取匹配的内容需要用`(`、`)`将正则表达式进行包裹。| | S-Regex | 规则正则,作用及使用同F-Regex。S-Regex为二次正则,可以用于对F-Regex匹配的数据结果进行二次的匹配提取,如不需要的情况下可以留空。| | Format | 格式化输出,在NFA引擎的正则表达式中,我们可以通过`{0}`、`{1}`、`{2}`…的方式进行取分组格式化输出。默认情况下使用`{0}`即可。 | | Scope | 规则作用域,主要用于表示当前规则作用于HTTP报文的哪个部分。支持请求、响应的行、头、体,以及完整的报文。 | | Engine | 正则引擎,主要用于表示当前规则的正则表达式所使用的引擎。**DFA引擎**:对于文本串里的每一个字符只需扫描一次,速度快、特性少;**NFA引擎**:要翻来覆去标注字符、取消标注字符,速度慢,但是特性(如:分组、替换、分割)丰富。 | | Color | 规则匹配颜色,主要用于表示当前规则匹配到对应HTTP报文时所需标记的高亮颜色。在HaE中具备颜色升级算法,当出现相同颜色时会自动向上升级一个颜色进行标记。 | | Sensitive | 规则敏感性,主要用于表示当前规则对于大小写字母是否敏感,敏感(`True`)则严格按照大小写要求匹配,不敏感(`False`)则反之。 | ## 优势特点 1. 精细配置:高度自由的配置选项,以满足各类精细化场景需求。 2. 分类标签:使用标签对规则进行分类,便于管理和组织规则。 3. 高亮标记:在HTTP History页面,通过颜色高亮和注释判断请求的价值。 4. 易读配置:使用易读的YAML格式存储配置文件,方便阅读和修改。 5. 数据集合:将匹配到的数据、请求和响应集中在数据面板中,提高测试和梳理效率。 6. 简洁可视:清晰可视的界面设计,更轻松地了解和配置HaE,操作简单、使用便捷。 7. 颜色升级:内置颜色升级算法,避免“屠龙者终成恶龙”场景,突出最具价值的请求。 8. 实战规则:官方规则库是基于实战化场景总结输出,提升数据发现的有效性、精准性。 | 界面名称 | 界面展示 | | ------------------------ | ---------------------------------------------------- | | Rules(规则管理) | <img src="images/rules.png" style="width: 80%" /> | | Config(配置管理) | <img src="images/config.png" style="width: 80%" /> | | Databoard(数据集合) | <img src="images/databoard.png" style="width: 80%" /> | | MarkInfo(数据展示) | <img src="images/markinfo.png" style="width: 80%" /> | ## 文末随笔 正义感是一个不可丢失的东西。 如果你觉得HaE好用,可以打赏一下作者,给作者持续更新下去的动力! <div align=center> <img src="images/reward.jpeg" style="width: 30%" /> </div> ## 404StarLink 2.0 - Galaxy ![404StarLink Logo](https://github.com/knownsec/404StarLink-Project/raw/master/logo.png) `HaE` 是 404Team [星链计划2.0](https://github.com/knownsec/404StarLink2.0-Galaxy) 中的一环,如果对 `HaE` 有任何疑问又或是想要找小伙伴交流,可以参考星链计划的加群方式。 - [https://github.com/knownsec/404StarLink2.0-Galaxy#community](https://github.com/knownsec/404StarLink2.0-Galaxy#community)
0