├── .gitignore ├── README.md ├── akka-taste ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── jacobs │ │ │ └── akka │ │ │ ├── basicdemo │ │ │ ├── DeadMain.java │ │ │ ├── Greeter.java │ │ │ ├── HelloMainSimple.java │ │ │ ├── HelloWorld.java │ │ │ ├── InboxMain.java │ │ │ ├── JavaPongActor.java │ │ │ ├── MyWorker.java │ │ │ ├── RestartActor.java │ │ │ ├── Supervisor.java │ │ │ ├── WatchActor.java │ │ │ ├── future │ │ │ │ ├── AskMain.java │ │ │ │ ├── FutureWorker.java │ │ │ │ └── Printer.java │ │ │ └── router │ │ │ │ ├── RouteMain.java │ │ │ │ └── WatchRouteActor.java │ │ │ └── memorydb │ │ │ ├── GetRequest.java │ │ │ ├── KeyNotFoundException.java │ │ │ ├── MemDbClient.java │ │ │ ├── MemDbServer.java │ │ │ └── SetRequest.java │ ├── resources │ │ └── samplehello.conf │ └── scala │ │ └── com │ │ └── jacobs │ │ └── akka │ │ └── scala │ │ └── QuickStartMain.scala │ └── test │ └── java │ └── com │ └── jacobs │ └── akka │ └── test │ └── MemDbServerTest.java ├── apidoc.json ├── basic-learning ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── jacobs │ └── basic │ ├── algorithm │ ├── ConsistentHash.java │ ├── LFUCache.java │ ├── LRUCache.java │ ├── Practice.java │ ├── SkipList.java │ ├── TreeLinkNode.java │ ├── TreeNode.java │ ├── array │ │ ├── ArraysProblems.java │ │ ├── BooleanArray.java │ │ ├── FindOnlyoneInArray.java │ │ ├── GetLongestSortableSubArr.java │ │ ├── GetNeedSortMinLength.java │ │ ├── GetWater.java │ │ ├── ListPartition.java │ │ ├── MaxChildListSum.java │ │ ├── MaxLengthArray.java │ │ ├── MaxMatrix.java │ │ ├── MaxWindow.java │ │ ├── PrintUniquePairWithFixedSum.java │ │ └── TopNProblem.java │ ├── binarytree │ │ ├── BST.java │ │ ├── BSTIterator.java │ │ ├── BinaryHeap.java │ │ ├── BinaryTree.java │ │ ├── FindPath.java │ │ ├── GetDistanceOfTwoNodes.java │ │ ├── GetMaxLengthSum.java │ │ ├── GetNextNode.java │ │ ├── GetTwoErrorNodes.java │ │ ├── IsSubTree.java │ │ ├── MaxDistance.java │ │ ├── MaxTree.java │ │ ├── MinimumHeap.java │ │ ├── PrintByLevel.java │ │ ├── PrintEdge.java │ │ ├── PrintZigZag.java │ │ ├── RBTNode.java │ │ ├── RBTree.java │ │ ├── SumCompleteBinaryTreeNodes.java │ │ └── SumTotalTreesByArray.java │ ├── dp │ │ ├── ChangeCoins.java │ │ ├── CoinsProblem.java │ │ ├── DynamicProgramProblems.java │ │ ├── FeiBoNaQie.java │ │ ├── HannoTa.java │ │ ├── HouseRobber.java │ │ ├── JumpGame.java │ │ ├── LCSE.java │ │ ├── LCST.java │ │ ├── LongestIncrementSubStr.java │ │ ├── MaxGold.java │ │ ├── MinEditCost.java │ │ ├── MinHP.java │ │ ├── MinPathSum.java │ │ ├── NQueens.java │ │ ├── PackageProblem.java │ │ ├── PalindromePartitioning.java │ │ ├── StrToCharMethods.java │ │ ├── StringIsCross.java │ │ └── WordBreak.java │ ├── leetcode │ │ ├── ProblemsMedium_08.java │ │ ├── ProblemsMedium_09.java │ │ ├── ProblemsMedium_10.java │ │ ├── ProblemsMedium_11.java │ │ ├── Problems_01.java │ │ ├── Problems_02.java │ │ ├── Problems_03.java │ │ ├── Problems_04.java │ │ ├── Problems_05.java │ │ ├── Problems_06.java │ │ ├── Problems_07.java │ │ ├── TopInterviewQuestions.java │ │ └── hard │ │ │ └── ProblemsHard_01.java │ ├── linklist │ │ ├── ChaperForLinkedList.java │ │ ├── CustomLinkedListBlockingQueue.java │ │ ├── JosephusKill.java │ │ └── ReverseNode.java │ ├── recursion │ │ └── RecursionSamples.java │ ├── sortmethods │ │ ├── BinarySearch.java │ │ ├── MergeSort.java │ │ ├── QuickSort.java │ │ ├── RadixSort.java │ │ ├── ShellSort.java │ │ └── SortBalls.java │ ├── stack │ │ └── StackReverse.java │ ├── string │ │ ├── KMP.java │ │ ├── LongestPalindrome.java │ │ ├── Palidrome.java │ │ └── StringSamples.java │ └── swordoffer │ │ └── SwordOffer.java │ ├── calcite │ └── CalciteMain.java │ ├── designpattern │ └── SingleTonTest.java │ ├── effctive3rd │ └── EnumInterface.java │ ├── java8pratice │ ├── FcInterfaceTest.java │ ├── ForkJoinSumCalculator.java │ ├── GenericsDemo.java │ ├── Java8MainTest.java │ ├── Lambda.java │ ├── Person.java │ ├── lazylist │ │ ├── LazyList.java │ │ └── MyList.java │ └── predicate.java │ ├── jinjia2java │ ├── AirflowVariableEnum.java │ ├── CustomELFunctionDefinition.java │ ├── DemoForJinjia.java │ ├── Macros.java │ └── MacrosUtil.java │ ├── leetcode │ └── editor │ │ └── cn │ │ ├── A1NYOS.java │ │ ├── AseY1I.java │ │ ├── BinaryTreeMaximumPathSum.java │ │ ├── JFETK5.java │ │ ├── LongestSubstringWithoutRepeatingCharacters.java │ │ ├── MaximumFrequencyStack.java │ │ ├── MinimumWindowSubstring.java │ │ ├── OneFGaJU.java │ │ ├── OpenTheLock.java │ │ ├── POCWxh.java │ │ ├── QTMn0o.java │ │ ├── ReverseNodesInKGroup.java │ │ ├── TwoVG8Kg.java │ │ ├── WGki4K.java │ │ ├── Xoh6Oh.java │ │ ├── Ygoe9J.java │ │ ├── ZVAVXX.java │ │ ├── all.json │ │ ├── doc │ │ ├── 0-he-1-ge-shu-xiang-tong-de-zi-shu-zu-by-xbyt.md │ │ ├── er-cha-shu-zhong-de-zui-da-lu-jing-he-by-leetcode-.md │ │ ├── er-jin-zhi-jia-fa-by-leetcode-solution-fa6t.md │ │ ├── han-jia-da-qia-ji-lu-jian-zhi-ii-offer-0-kahk.md │ │ ├── he-da-yu-deng-yu-target-de-zui-duan-zi-s-ixef.md │ │ ├── p__-10+max_9,35_=25_.png │ │ ├── p__0_le_i_n_.png │ │ ├── p__0sim31_.png │ │ ├── p__20+max_15,7_=35_.png │ │ ├── p__Aoplus_B_.png │ │ ├── p__Aoplus_Boplus_C_.png │ │ ├── p__O_log_C__.png │ │ ├── p__O_log_n__.png │ │ ├── p__O_max_{_|a|,_|b|_}__.png │ │ ├── p__O_n_log_C__.png │ │ ├── p__O_n_log_n__.png │ │ ├── p__O_|a|_+_|b|_+_X_cdot_max__{|a|_+_|b|}___.png │ │ ├── p___00_to_01_to_10_to_00__.png │ │ ├── p___a_i_=_a_i'b_i'x_i_+_a_ib_i'x_i'_=_b_i'_a_i_oplus_x_i___.png │ │ ├── p___b_i_=_a_i'b_i'x_i_+_a_i'b_ix_i'_=_a_i'_b_i_oplus_x_i___.png │ │ ├── p___textit{carry}_+_a_i_+_b_i__bmod{2}_.png │ │ ├── p__i-textit{prevIndex}_.png │ │ ├── p__lfloor_frac{textit{carry}_+_a_i_+_b_i}{2}_rfloor_.png │ │ ├── p__lfloor_n_3_rfloor_+_1_.png │ │ ├── p__log_C=log_2^{32}_=_32_.png │ │ ├── p__n_=_max{_|a|,_|b|_}_.png │ │ ├── p__textit{bound}-_i-1__.png │ │ ├── p__textit{bound}_.png │ │ ├── p__textit{carry}_.png │ │ ├── p__textit{counter}_.png │ │ ├── p__textit{end}-textit{start}+1_.png │ │ ├── p__textit{end}_.png │ │ ├── p__textit{newNums}_.png │ │ ├── p__textit{newNums}_i_=-1_.png │ │ ├── p__textit{newNums}_i_=1_.png │ │ ├── p__textit{nums}_.png │ │ ├── p__textit{nums}_i_=0_.png │ │ ├── p__textit{nums}_i_=1_.png │ │ ├── p__textit{prefixSums}_.png │ │ ├── p__textit{prefixSums}_i__.png │ │ ├── p__textit{prefixSums}_k_-textit{prefixSums}_j_=0_.png │ │ ├── p__textit{prefixSums}_k_-textit{prefixSums}_j__.png │ │ ├── p__textit{prevIndex}+1_.png │ │ ├── p__textit{prevIndex}_.png │ │ ├── p__textit{start}_.png │ │ ├── p__textit{sum}_.png │ │ ├── p__textit{sum}___s_.png │ │ ├── p__textit{sum}_ge_s_.png │ │ ├── p__texttt{Python}_.png │ │ ├── p__texttt{_x____i__&_1}_.png │ │ ├── p__texttt{int}_.png │ │ ├── p__text{nums}_.png │ │ ├── p__text{nums}_0__.png │ │ ├── p__text{nums}_end__.png │ │ ├── p__text{nums}_i-1__.png │ │ ├── p__text{nums}_start__.png │ │ ├── p__text{nums}_textit{end}__.png │ │ ├── p__text{nums}_textit{start}__.png │ │ ├── p__text{sums}_.png │ │ ├── p__text{sums}_i__.png │ │ ├── p__text{sums}_textit{bound}_-text{sums}_i-1__ge_s_.png │ │ ├── p__{_0,_1,_2_}_.png │ │ └── zhi-chu-xian-yi-ci-de-shu-zi-by-leetcode-0vrt.md │ │ └── translation.json │ ├── models │ ├── ListNode.java │ ├── RandomListNode.java │ └── UndirectedGraphNode.java │ ├── multithread │ ├── AtomicIntegerDemo.java │ ├── BoundedPriorityBlockingQueue.java │ ├── CompleteFutureTest.java │ ├── ConditionTest.java │ ├── ConsumerAndProducer.java │ ├── ControlSendThreads.java │ ├── CyclicBarrierTest.java │ ├── CyclicBarrierTest2.java │ ├── DeadLock.java │ ├── EnemyShip.java │ ├── ForkJoinTest.java │ ├── InterruptedTest.java │ ├── LockSupportDemo.java │ ├── MainTest.java │ ├── Memoizer.java │ ├── PrintABC.java │ ├── ReentrantLockTets.java │ ├── SynchronousQueueTest.java │ ├── TestReentrantLock.java │ ├── TestSynchronized.java │ ├── ThreadJoin.java │ └── disruptor │ │ ├── Consumer.java │ │ ├── DisruptorWithMultiProducer.java │ │ ├── DisruptorWithSingleProducer.java │ │ ├── Order.java │ │ └── Producer.java │ ├── proxy │ ├── CglibProxyFactory.java │ ├── ProxyFactory.java │ ├── Test.java │ ├── principle │ │ ├── MyInvocationHandler.java │ │ ├── Test.java │ │ ├── UserService.java │ │ └── UserServiceImpl.java │ ├── student.java │ └── studentImpl.java │ ├── thrift │ ├── Add │ ├── AdditionService.java │ ├── AddtionServiceHandler.java │ └── test │ │ ├── AdditionClient.java │ │ └── MyServer.java │ └── zookeeper │ ├── SnapshotAnalyze.java │ ├── ZooKeeperWatcher.java │ ├── ZookeeperCreateNode.java │ ├── ZookeeperGetData.java │ ├── ZookeeperGetNotice.java │ ├── ZookeeperTest.java │ ├── curator │ ├── CuratorBase.java │ ├── CuratorWatcher.java │ ├── CuratorWatcher1.java │ ├── DistributeCounter.java │ └── DistributeLock.java │ └── zkclient │ ├── Lock.java │ ├── TestMainClient.java │ └── TestMainServer.java ├── core-web ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── jacobs │ │ │ ├── Application.java │ │ │ ├── aspects │ │ │ ├── AutoGenerateRowMapper.java │ │ │ ├── Log.java │ │ │ ├── LogAspect.java │ │ │ ├── LogBefore.java │ │ │ ├── LogMethod.java │ │ │ ├── MapperProcessorAnnotation.java │ │ │ └── RowMapper.java │ │ │ ├── conditional │ │ │ ├── ConditionalOnMyProperties.java │ │ │ ├── ElasticServiceCondition.java │ │ │ └── OnMyPropertiesCondition.java │ │ │ ├── constants │ │ │ └── BaseConstant.java │ │ │ ├── elasticserach │ │ │ ├── ElasticConfiguration.java │ │ │ └── ElasticsearchProperties.java │ │ │ ├── exception │ │ │ ├── CommonException.java │ │ │ ├── CommonExceptionMapper.java │ │ │ ├── CommonRestException.java │ │ │ ├── CommonResult.java │ │ │ ├── CommonValidationMapper.java │ │ │ ├── ExFactor.java │ │ │ └── HBaseSystemException.java │ │ │ ├── filters │ │ │ └── PoweredByResponseFilter.java │ │ │ ├── hbase │ │ │ ├── AdminConfig.java │ │ │ ├── HBaseAccessor.java │ │ │ ├── HBaseOperations.java │ │ │ ├── HBaseTemplate.java │ │ │ ├── MainHbaseConfiguration.java │ │ │ ├── ZookeeperConfig.java │ │ │ ├── callback │ │ │ │ ├── MutatorCallback.java │ │ │ │ └── TableCallback.java │ │ │ ├── factory │ │ │ │ ├── MainHTableFactory.java │ │ │ │ └── TableFactory.java │ │ │ ├── results │ │ │ │ ├── HBaseResultBuilder.java │ │ │ │ ├── PutExtension.java │ │ │ │ ├── ResultsExtractor.java │ │ │ │ ├── RowMapper.java │ │ │ │ └── RowMapperResultsExtractor.java │ │ │ └── util │ │ │ │ └── HBaseUtil.java │ │ │ ├── hive │ │ │ ├── HiveDataSource.java │ │ │ ├── HiveDataSourceConfiguration.java │ │ │ ├── HiveJdbcTemplate.java │ │ │ ├── config │ │ │ │ ├── HiveJdbcConfig.java │ │ │ │ └── HiveJdbcPoolConfig.java │ │ │ └── rowmapper │ │ │ │ ├── HiveBeanPropertyRowMappper.java │ │ │ │ ├── HiveRowMapper.java │ │ │ │ └── HiveRowMapperPlugin.java │ │ │ ├── javapoet │ │ │ ├── GenerateMapperProcessor.java │ │ │ ├── GenerateRowMapper.java │ │ │ └── LoadPackageClasses.java │ │ │ ├── jersey │ │ │ ├── CommonExceptionFactor.java │ │ │ ├── ContainerRequestUtil.java │ │ │ ├── EnableJerseyConfiguration.java │ │ │ ├── JerseyAnnotationConfiguration.java │ │ │ ├── JerseyConfig.java │ │ │ ├── ParamDesc.java │ │ │ ├── RuntimeAnnotations.java │ │ │ └── params │ │ │ │ ├── DoubleRange.java │ │ │ │ ├── FloatRange.java │ │ │ │ ├── IntRange.java │ │ │ │ ├── LongRange.java │ │ │ │ ├── ParamRange.java │ │ │ │ └── RangeFactory.java │ │ │ ├── lock │ │ │ ├── DistributedLock.java │ │ │ ├── Watcher.java │ │ │ └── ZkConfig.java │ │ │ ├── logger │ │ │ ├── LogggerInitializer.java │ │ │ ├── MyLogLayOut.java │ │ │ └── MyThrowableRender.java │ │ │ ├── module │ │ │ ├── Address.java │ │ │ ├── MongoUser.java │ │ │ ├── PageableResponse.java │ │ │ ├── TestCase.java │ │ │ ├── User.java │ │ │ ├── UserPropertyTest.java │ │ │ ├── WeixiaobaoUploadInfo.java │ │ │ └── messagecloud │ │ │ │ ├── CommonResponse.java │ │ │ │ ├── Product.java │ │ │ │ └── Topic.java │ │ │ ├── resource │ │ │ ├── ABTestResourcre.java │ │ │ ├── MessageResource.java │ │ │ ├── SecurityResource.java │ │ │ └── TestResource.java │ │ │ ├── service │ │ │ ├── DemoService.java │ │ │ └── ElasticSearchService.java │ │ │ └── task │ │ │ └── Task.java │ └── resources │ │ ├── application-test.yaml │ │ ├── application.yaml │ │ ├── configs.properties │ │ ├── hbase-site.xml │ │ ├── logback-spring.xml │ │ └── spring.factories │ └── test │ └── java │ └── com │ └── jacobs │ ├── GraphiteData.java │ ├── IvrDialTest.java │ ├── JerseyTest.java │ ├── MockitoTest.java │ ├── ModelMapperTest.java │ ├── MongoConstants.java │ ├── PaloFeConfigTest.java │ ├── QuickStartSample.java │ ├── ReactorTest.java │ ├── Student.java │ ├── User.java │ └── models │ ├── Config.java │ └── ConfigBase.java ├── docs ├── 优秀博文汇总.pdf └── 算法相关汇总.pdf ├── flink-demos ├── pom.xml └── src │ └── main │ └── scala │ └── com │ └── jacobs │ └── jobs │ └── realtime │ ├── utils │ └── ParquetWriters.java │ ├── watermark │ └── WatermarkTest.scala │ └── wordcount │ ├── WindowWordCount.scala │ ├── WordCount.scala │ └── WordCountData.java ├── netty-learning ├── pom.xml └── src │ └── main │ └── java │ └── com │ └── jacobs │ └── netty │ ├── aiotimeserver1 │ ├── AsyncTimeClientHandler.java │ ├── AsyncTimeServerHandler.java │ ├── TimeClient.java │ └── TimeServer.java │ ├── bio │ ├── TimeClient.java │ ├── TimeServer.java │ └── TimeServerHandler.java │ ├── client │ ├── EchoClient.java │ └── EchoClientHandler.java │ ├── http_helloworld │ ├── HttpHelloWorldServer.java │ ├── HttpHelloWorldServerHandler.java │ └── HttpHelloWorldServerInitializer.java │ ├── redisclient │ ├── RedisClient.java │ └── RedisClientHandler.java │ ├── server │ ├── EchoServer.java │ └── ServerHandler.java │ ├── subscribe │ └── SubReqServer.java │ ├── timeserver1 │ ├── MutiplexerTimeServer.java │ ├── TimeClient.java │ ├── TimeClientHandle.java │ └── TimeServer.java │ ├── timeserver2 │ ├── TimeClient.java │ └── TimeServer.java │ └── websocketx │ ├── benchmarkserver │ ├── WebSocketServer.java │ ├── WebSocketServerBenchmarkPage.java │ ├── WebSocketServerHandler.java │ └── WebSocketServerInitializer.java │ ├── client │ ├── WebSocketClient.java │ └── WebSocketClientHandler.java │ └── server │ ├── WebSocketFrameHandler.java │ ├── WebSocketIndexPageHandler.java │ ├── WebSocketServer.java │ ├── WebSocketServerIndexPage.java │ └── WebSocketServerInitializer.java ├── pom.xml ├── spark-demos ├── pom.xml └── src │ └── main │ └── scala │ └── com │ └── jacobs │ └── spark │ └── InteractionExamples.scala ├── spring-webflux ├── pom.xml └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── jacobs │ │ │ └── webflux │ │ │ ├── SpringWebFluxApplication.java │ │ │ ├── config │ │ │ ├── EventLoopNettyCustomizer.java │ │ │ └── RoutingConfiguration.java │ │ │ ├── controller │ │ │ └── HelloController.java │ │ │ ├── dao │ │ │ └── UserRepository.java │ │ │ ├── handler │ │ │ └── UserHandler.java │ │ │ └── model │ │ │ ├── NearByUserModel.java │ │ │ ├── NearByUserResponse.java │ │ │ └── User.java │ └── resources │ │ └── application.yaml │ └── test │ └── java │ └── com │ └── jacobs │ └── webflux │ └── SpringWebfluxApplicationTests.java └── utils ├── pom.xml └── src ├── main └── java │ └── com │ └── jacobs │ ├── kotlin_inaction │ ├── Compose.kt │ ├── Dataclasses.kt │ ├── Delegate.kt │ ├── EnumDemo.kt │ ├── IteratorDemo.kt │ ├── LearningDemo.kt │ ├── WhenDemo.kt │ ├── app.kt │ └── ex1.kt │ └── utils │ └── CommonHttpUtil.java └── test └── java └── com └── jacobs ├── AppTest.java └── UtilTest.java /README.md: -------------------------------------------------------------------------------- 1 | ## java_learning_practice 2 | 3 | - 学习java的积累示例:面试高频算法、akka、多线程、zookeeper、Disruptor、NIO、Netty、Thrift 等 4 | 5 | ## 项目组成 6 | 7 | ### [优秀博文汇总pdf](./docs/优秀博文汇总.pdf) 8 | 9 | - 收集总结后端&&大数据方向看到的优秀文章和系列博客;不定期更新pdf 10 | 11 | ### akka-taste 12 | 13 | - akka 学习demo 14 | 15 | ### basic_learning 16 | 17 | - [算法训练汇总](./docs/算法相关汇总.pdf) 18 | - 总结刷leetcode过程中一些值得归类记录的算法题解;包含关键思路分析等;不定期更新pdf 19 | - 一些算法,语言方面的练习 20 | - 算法: leetcode, nowcoder, swordoffer,以及算法红皮书等 21 | - 语言技术: kotlin, java8函数式,多线程等 22 | - 框架: akka,zookeeper,Disruptor等 23 | 24 | ### core-web 25 | - springboot相关练习 26 | - jersey 封装 27 | - spring security练习 28 | - 基于curator fremework的分布式锁封装 29 | - hbase封装 30 | - javapoet尝试 31 | - elasticserach 封装 32 | - 基于druid pool的hive jdbc client pool封装;扩展BeanPropertyRowMappper,实现轻量级ORM框架 33 | 34 | ### netty_learning 35 | - 《netty权威指南第五版》的相关练习demo 36 | 37 | ### flink-demos 38 | 39 | - flink 学习demo;watermark 40 | 41 | ### spark-demos 42 | 43 | - standalone模式下的spark 示例demo 44 | - spark MLlib api 练习 45 | - 注意:运行时需要预先下载官方[spark安装包](https://spark.apache.org/downloads.html),将jars下的jar包依赖添加到spark-demos依赖里 46 | 47 | 48 | ### spring-webflux 49 | - 基于springboot 2.0 以上的响应式编程尝试。 50 | - Flux,Mono练习 51 | 52 | ### utils 53 | - 封装一些常用的类库,如okhttp3 client封装等 54 | - kotlin 相关练习 55 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/DeadMain.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import com.typesafe.config.ConfigFactory; 4 | 5 | import akka.actor.ActorRef; 6 | import akka.actor.ActorSystem; 7 | import akka.actor.Props; 8 | 9 | /** 10 | * Created by lichao on 2016/12/1. 11 | */ 12 | public class DeadMain { 13 | public static void main(String[] args) { 14 | // ActorSystem actorSystem = ActorSystem.create("deadwatch", 15 | // ConfigFactory.load("samplehello.conf")); 16 | // ActorRef worker = actorSystem.actorOf(Props.create(MyWorker.class), "worker"); 17 | // actorSystem.actorOf(Props.create(WatchActor.class, worker), "watcher"); 18 | // worker.tell(MyWorker.Msg.WORKING, ActorRef.noSender()); 19 | // worker.tell(MyWorker.Msg.DONE, ActorRef.noSender()); 20 | // worker.tell(PoisonPill.getInstance(), ActorRef.noSender()); 21 | ActorSystem actorSystem = ActorSystem.create("lifecycle", 22 | ConfigFactory.load("samplehello.conf")); 23 | customStrategy(actorSystem); 24 | } 25 | 26 | public static void customStrategy(ActorSystem system) { 27 | ActorRef a = system.actorOf(Props.create(Supervisor.class), "Supervisor"); 28 | System.out.println("a path is:" + a.path()); 29 | //a.tell(Props.create(RestartActor.class), ActorRef.noSender()); 30 | ActorRef restart = system.actorOf(Props.create(RestartActor.class), "restartActor"); 31 | System.out.println("restart path is: " + restart.path()); 32 | 33 | //ActorSelection sel = system.actorSelection("akka://lifecycle/user/Supervisor/restartActor"); 34 | for (int i = 0; i < 100; i++) { 35 | restart.tell(RestartActor.Msg.RESTART, ActorRef.noSender()); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/Greeter.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import akka.actor.UntypedActor; 4 | 5 | /** 6 | * Created by lichao on 2016/12/1. 7 | */ 8 | public class Greeter extends UntypedActor { 9 | 10 | public static enum Msg { 11 | GREET, DONE 12 | } 13 | 14 | @Override 15 | public void onReceive(Object o) throws Throwable { 16 | if (o == Msg.GREET) { 17 | System.out.println("hello world"); 18 | getSender().tell(Msg.DONE, getSelf()); 19 | } else { 20 | unhandled(o); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/HelloMainSimple.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import com.typesafe.config.ConfigFactory; 4 | 5 | import java.util.stream.LongStream; 6 | 7 | import akka.actor.ActorRef; 8 | import akka.actor.ActorSystem; 9 | import akka.actor.Props; 10 | 11 | /** 12 | * Created by lichao on 2016/12/1. 13 | */ 14 | public class HelloMainSimple { 15 | 16 | public static void main(String[] args) { 17 | ActorSystem system = ActorSystem.create("Hello", ConfigFactory.load("simplehello.conf")); 18 | //ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld"); 19 | ActorRef a = system.actorOf(Props.create(HelloWorld.class), "helloWorld"); 20 | LongStream.range(0, 100).forEach(index -> { 21 | a.tell(Greeter.Msg.GREET, ActorRef.noSender()); 22 | //System.out.println("HelloWorld Actor Path:" + a.path()); 23 | }); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Props; 5 | import akka.actor.UntypedActor; 6 | 7 | /** 8 | * Created by lichao on 2016/12/1. 9 | */ 10 | public class HelloWorld extends UntypedActor { 11 | 12 | ActorRef greeter; 13 | 14 | @Override 15 | public void preStart() throws Exception { 16 | greeter = getContext().actorOf(Props.create(Greeter.class), "greeter"); 17 | System.out.println("Greeter Actor Path:" + greeter.path()); 18 | greeter.tell(Greeter.Msg.GREET, getSelf()); 19 | } 20 | 21 | @Override 22 | public void onReceive(Object o) throws Throwable { 23 | if (o == Greeter.Msg.DONE) { 24 | greeter.tell(Greeter.Msg.GREET, getSelf()); 25 | getContext().stop(getSelf()); 26 | } else { 27 | unhandled(o); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/InboxMain.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import com.typesafe.config.ConfigFactory; 4 | 5 | import java.util.concurrent.TimeUnit; 6 | import java.util.concurrent.TimeoutException; 7 | 8 | import akka.actor.ActorRef; 9 | import akka.actor.ActorSystem; 10 | import akka.actor.Inbox; 11 | import akka.actor.Props; 12 | import akka.actor.Terminated; 13 | import scala.concurrent.duration.Duration; 14 | 15 | /** 16 | * Created by lichao on 2016/12/2. 17 | */ 18 | public class InboxMain { 19 | 20 | public static void main(String[] args) throws TimeoutException { 21 | ActorSystem system = ActorSystem.create("inboxdemo", 22 | ConfigFactory.load("samplehello.conf")); 23 | ActorRef worker = system.actorOf(Props.create(MyWorker.class), "worker"); 24 | ActorRef helloworld = system.actorOf(Props.create(HelloWorld.class), "hello"); 25 | 26 | final Inbox inbox = Inbox.create(system); 27 | inbox.watch(worker); 28 | inbox.send(worker, MyWorker.Msg.WORKING); 29 | inbox.send(worker, MyWorker.Msg.DONE); 30 | inbox.send(worker, MyWorker.Msg.CLOSE); 31 | 32 | while (true) { 33 | Object msg = inbox.receive(Duration.create(1, TimeUnit.SECONDS)); 34 | if (msg == MyWorker.Msg.CLOSE) { 35 | System.out.println("My worker is Closing"); 36 | } else if (msg instanceof Terminated) { 37 | System.out.println("My worker is dead"); 38 | system.terminate(); 39 | break; 40 | } else { 41 | System.out.println("received:" + msg); 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/MyWorker.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import akka.actor.UntypedActor; 4 | import akka.event.Logging; 5 | import akka.event.LoggingAdapter; 6 | import scala.Option; 7 | 8 | /** 9 | * Created by lichao on 2016/12/1. 10 | */ 11 | public class MyWorker extends UntypedActor { 12 | 13 | private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); 14 | 15 | public enum Msg { 16 | WORKING, DONE, CLOSE 17 | } 18 | 19 | @Override 20 | public void preRestart(Throwable reason, Option message) throws Exception { 21 | System.out.println("MyWorker is starting"); 22 | } 23 | 24 | @Override 25 | public void postStop() throws Exception { 26 | System.out.println("My working is stopping"); 27 | } 28 | 29 | @Override 30 | public void onReceive(Object msg) throws Throwable { 31 | if (msg == Msg.WORKING) { 32 | System.out.println("I am working"); 33 | } 34 | if (msg == Msg.DONE) { 35 | System.out.println("Stop working"); 36 | } 37 | if (msg == Msg.CLOSE) { 38 | System.out.println("I will shutdown"); 39 | getSender().tell(Msg.CLOSE, getSelf()); 40 | } 41 | 42 | unhandled(msg); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/RestartActor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import akka.actor.UntypedActor; 4 | import scala.Option; 5 | 6 | /** 7 | * Created by lichao on 2016/12/2. 8 | */ 9 | public class RestartActor extends UntypedActor { 10 | 11 | public enum Msg { 12 | DONE, RESTART 13 | } 14 | 15 | @Override 16 | public void preRestart(Throwable reason, Option message) throws Exception { 17 | System.out.println("prestart"); 18 | } 19 | 20 | @Override 21 | public void postStop() throws Exception { 22 | System.out.println("postStop"); 23 | } 24 | 25 | @Override 26 | public void postRestart(Throwable reason) throws Exception { 27 | super.postRestart(reason); 28 | System.out.println("post restart"); 29 | } 30 | 31 | @Override 32 | public void preStart() throws Exception { 33 | System.out.println("pre restart"); 34 | } 35 | 36 | @Override 37 | public void onReceive(Object o) throws Throwable { 38 | if (o == Msg.DONE) { 39 | getContext().stop(getSelf()); 40 | } else if (o == Msg.RESTART) { 41 | System.out.println(((Object) null).toString()); 42 | //抛出异常,默认会被restart,但这里会resume 43 | double a = 0 / 0; 44 | } 45 | unhandled(o); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/Supervisor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import akka.actor.OneForOneStrategy; 6 | import akka.actor.Props; 7 | import akka.actor.SupervisorStrategy; 8 | import akka.actor.UntypedActor; 9 | import scala.concurrent.duration.Duration; 10 | 11 | /** 12 | * Created by lichao on 2016/12/2. 13 | */ 14 | public class Supervisor extends UntypedActor { 15 | 16 | //一分钟内进行三次尝试 17 | private static SupervisorStrategy strategy = new OneForOneStrategy(3, 18 | Duration.create(1, TimeUnit.MINUTES), throwable -> { 19 | if (throwable instanceof ArithmeticException) { 20 | System.out.println("meet ArithmeticException, just resume"); 21 | return SupervisorStrategy.resume(); 22 | } else if (throwable instanceof NullPointerException) { 23 | System.out.println("meet NullPointerException ,restart"); 24 | return SupervisorStrategy.restart(); 25 | } else if (throwable instanceof IllegalArgumentException) { 26 | return SupervisorStrategy.stop(); 27 | } else { 28 | return SupervisorStrategy.escalate(); 29 | } 30 | }); 31 | 32 | @Override 33 | public SupervisorStrategy supervisorStrategy() { 34 | //自定义监督策略 35 | return strategy; 36 | } 37 | 38 | @Override 39 | public void onReceive(Object o) throws Throwable { 40 | if (o instanceof Props) { 41 | getContext().actorOf((Props) o, "restartActor"); 42 | } else { 43 | unhandled(o); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/WatchActor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo; 2 | 3 | import akka.actor.ActorRef; 4 | import akka.actor.Terminated; 5 | import akka.actor.UntypedActor; 6 | import akka.event.Logging; 7 | import akka.event.LoggingAdapter; 8 | 9 | /** 10 | * Created by lichao on 2016/12/1. 11 | */ 12 | public class WatchActor extends UntypedActor { 13 | 14 | private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); 15 | 16 | public WatchActor(ActorRef actorRef) { 17 | getContext().watch(actorRef); 18 | } 19 | 20 | @Override 21 | public void onReceive(Object msg) throws Throwable { 22 | if (msg instanceof Terminated) { 23 | System.out.println(String.format("%s has terminated, shutting down system", 24 | ((Terminated) msg).getActor().path())); 25 | getContext().system().terminate(); 26 | } else { 27 | unhandled(msg); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/future/AskMain.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo.future; 2 | 3 | import com.jacobs.akka.basicdemo.MyWorker; 4 | import com.jacobs.akka.basicdemo.WatchActor; 5 | import com.typesafe.config.ConfigFactory; 6 | 7 | import akka.actor.ActorRef; 8 | import akka.actor.ActorSystem; 9 | import akka.actor.Props; 10 | 11 | /** 12 | * Created by lichao on 2016/12/2. 13 | */ 14 | public class AskMain { 15 | 16 | public static void main(String[] args) { 17 | ActorSystem system = ActorSystem.create("askdemo", ConfigFactory.load("samplehello.conf")); 18 | ActorRef worker = system.actorOf(Props.create(MyWorker.class), "worker"); 19 | ActorRef printer = system.actorOf(Props.create(Printer.class), "printer"); 20 | system.actorOf(Props.create(WatchActor.class, worker), "watcher"); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/future/FutureWorker.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo.future; 2 | 3 | import akka.actor.UntypedActor; 4 | import akka.event.Logging; 5 | import akka.event.LoggingAdapter; 6 | 7 | /** 8 | * Created by lichao on 2016/12/3. 9 | */ 10 | public class FutureWorker extends UntypedActor { 11 | 12 | private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); 13 | 14 | public static enum Msg { 15 | WORKING, DONE, CLOSE 16 | } 17 | 18 | @Override 19 | public void onReceive(Object msg) throws Throwable { 20 | if (msg instanceof Integer) { 21 | int i = (Integer) msg; 22 | try { 23 | Thread.sleep(1000); 24 | } catch (InterruptedException e) { 25 | 26 | } 27 | getSender().tell(i * i, getSelf()); 28 | } 29 | if (msg == Msg.DONE) { 30 | log.info("stop working"); 31 | } 32 | if (msg == Msg.CLOSE) { 33 | log.info("I will shutdown"); 34 | getSender().tell(Msg.CLOSE, getSelf()); 35 | getContext().stop(getSelf()); 36 | } else { 37 | unhandled(msg); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/future/Printer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo.future; 2 | 3 | import akka.actor.UntypedActor; 4 | import akka.event.Logging; 5 | import akka.event.LoggingAdapter; 6 | 7 | /** 8 | * Created by lichao on 2016/12/3. 9 | */ 10 | public class Printer extends UntypedActor { 11 | private final LoggingAdapter log = Logging.getLogger(getContext().system(), this); 12 | 13 | @Override 14 | public void onReceive(Object msg) throws Throwable { 15 | if (msg instanceof Integer) { 16 | System.out.println("Printer:" + msg); 17 | } 18 | if (msg == FutureWorker.Msg.DONE) { 19 | log.info("stop working"); 20 | } 21 | if (msg == FutureWorker.Msg.CLOSE) { 22 | log.info("I will shutdown"); 23 | getSender().tell(FutureWorker.Msg.CLOSE, getSelf()); 24 | getContext().stop(getSelf()); 25 | } else { 26 | unhandled(msg); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/basicdemo/router/RouteMain.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.basicdemo.router; 2 | 3 | import com.jacobs.akka.basicdemo.MyWorker; 4 | import com.typesafe.config.ConfigFactory; 5 | 6 | import akka.actor.ActorRef; 7 | import akka.actor.ActorSystem; 8 | import akka.actor.Props; 9 | import akka.agent.Agent; 10 | import akka.dispatch.ExecutionContexts; 11 | 12 | /** 13 | * Created by lichao on 2016/12/2. 14 | */ 15 | public class RouteMain { 16 | public static Agent flag = Agent.create(true, ExecutionContexts.global()); 17 | 18 | public static void main(String[] args) throws InterruptedException { 19 | ActorSystem system = ActorSystem.create("route", ConfigFactory.load("simplehello.conf")); 20 | ActorRef w = system.actorOf(Props.create(WatchRouteActor.class), "routeWatcher"); 21 | int i = 0; 22 | while (flag.get()) { 23 | w.tell(MyWorker.Msg.WORKING, ActorRef.noSender()); 24 | if (i % 10 == 0) { 25 | w.tell(MyWorker.Msg.CLOSE, ActorRef.noSender()); 26 | } 27 | i++; 28 | Thread.sleep(100); 29 | } 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/memorydb/GetRequest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.memorydb; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author lichao 7 | * Created on 2019-05-18 8 | */ 9 | public class GetRequest implements Serializable { 10 | public final String key; 11 | 12 | public GetRequest(String key) { 13 | this.key = key; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/memorydb/KeyNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.memorydb; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author lichao 7 | * Created on 2019-05-18 8 | */ 9 | public class KeyNotFoundException extends Exception implements Serializable { 10 | public final String key; 11 | 12 | public KeyNotFoundException(String key) { 13 | this.key = key; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/memorydb/MemDbClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.memorydb; 2 | 3 | import static akka.pattern.Patterns.ask; 4 | import static scala.compat.java8.FutureConverters.toJava; 5 | 6 | import java.util.concurrent.CompletionStage; 7 | 8 | import akka.actor.ActorRef; 9 | 10 | /** 11 | * @author lichao 12 | * Created on 2019-05-18 13 | */ 14 | public class MemDbClient { 15 | 16 | private final ActorRef serverRef; 17 | 18 | public MemDbClient(ActorRef actorRef) { 19 | this.serverRef = actorRef; 20 | } 21 | 22 | public CompletionStage set(String key, Object value) { 23 | return toJava(ask(serverRef, SetRequest.builder().key(key).value(value).build(), 24 | 2000)); 25 | } 26 | 27 | public CompletionStage get(String key) { 28 | return toJava(ask(serverRef, new GetRequest(key), 2000)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/memorydb/MemDbServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.memorydb; 2 | 3 | import java.util.Map; 4 | 5 | import com.google.common.collect.Maps; 6 | 7 | import akka.actor.AbstractActor; 8 | import akka.actor.Status; 9 | import akka.event.Logging; 10 | import akka.event.LoggingAdapter; 11 | import lombok.Getter; 12 | 13 | /** 14 | * @author lichao 15 | * Created on 2019-05-18 16 | */ 17 | public class MemDbServer extends AbstractActor { 18 | 19 | protected final LoggingAdapter log = Logging.getLogger(context().system(), this); 20 | //简单的内存k-v存储 21 | @Getter 22 | private final Map store = Maps.newHashMap(); 23 | 24 | @Override 25 | public Receive createReceive() { 26 | return receiveBuilder() 27 | .match(SetRequest.class, 28 | message -> { 29 | log.info("Received Set request: {}", message); 30 | store.put(message.getKey(), message.getValue()); 31 | }) 32 | .match(GetRequest.class, message -> { 33 | log.info("Received Get request: {}", message); 34 | String value = (String) store.get(message.key); 35 | Object response = (value != null) 36 | ? value 37 | : new Status.Failure(new KeyNotFoundException(message.key)); 38 | sender().tell(response, self()); 39 | }) 40 | .matchAny(o -> sender().tell(new Status.Failure(new ClassNotFoundException()), self())) 41 | .build(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /akka-taste/src/main/java/com/jacobs/akka/memorydb/SetRequest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.akka.memorydb; 2 | 3 | import java.io.Serializable; 4 | 5 | import lombok.Builder; 6 | import lombok.Data; 7 | 8 | /** 9 | * @author lichao 10 | * Created on 2019-05-18 11 | */ 12 | @Data 13 | @Builder 14 | public class SetRequest implements Serializable { 15 | 16 | private final String key; 17 | private final Object value; 18 | } 19 | -------------------------------------------------------------------------------- /akka-taste/src/main/resources/samplehello.conf: -------------------------------------------------------------------------------- 1 | akka { 2 | loglevel = INFO 3 | actor { 4 | provider = "akka.remote.RemoteActorRefProvider" 5 | } 6 | remote { 7 | enabled-transports = ["akka.remote.netty.tcp"] 8 | netty.tcp { 9 | hostname = "127.0.0.1" 10 | port = 2552 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /apidoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "abtest接口文档", 3 | "version": "1.0.0", 4 | "description": "abtest接口文档", 5 | "title": "abtest接口文档", 6 | "url": "" 7 | } -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/TreeLinkNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm; 2 | 3 | /** 4 | * @author lichao 5 | * @date 2018/12/07 6 | */ 7 | public class TreeLinkNode { 8 | 9 | public int val; 10 | public TreeLinkNode left, right, next; 11 | 12 | public TreeLinkNode(int x) { 13 | val = x; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/TreeNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm; 2 | 3 | /** 4 | * Created by lichao on 2016/11/2. 5 | */ 6 | public class TreeNode { 7 | 8 | public int val; 9 | public TreeNode next; 10 | public TreeNode left; 11 | public TreeNode right; 12 | public TreeNode parent; 13 | 14 | public TreeNode(int data) { 15 | this.val = data; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "TreeNode{" + 21 | "val=" + val + 22 | ", next=" + next + 23 | ", left=" + left + 24 | ", right=" + right + 25 | ", parent=" + parent + 26 | '}'; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/array/BooleanArray.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.array; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * 实现一个布尔数组, 要求压缩布尔值到bit上 思路比较敏捷, 最后代码实现也比较完整. 代码规范和异常判断做的不错. 7 | */ 8 | public class BooleanArray { 9 | 10 | private int size = 0; 11 | //private static final int DEFAULT_SIZE = 100; 12 | public int[] array; 13 | 14 | public BooleanArray(int size) { 15 | this.size = size; 16 | array = new int[size % 32 + 1]; 17 | } 18 | 19 | public int getIndex(int number) { 20 | return number / 32; 21 | } 22 | 23 | public int getPosition(int number) { 24 | return number % 32; 25 | } 26 | 27 | public void add(int number) { 28 | array[getIndex(number)] = array[getIndex(number)] | (1 << getPosition(number)); 29 | } 30 | 31 | public boolean getValue(int number) { 32 | if (number > size) { 33 | return false; 34 | } 35 | int index = getIndex(number); 36 | int position = getPosition(number); 37 | 38 | return ((array[index] >> position)) == 1; 39 | } 40 | 41 | public static void main(String[] args) { 42 | BooleanArray booleanArray = new BooleanArray(100); 43 | booleanArray.add(64); 44 | System.out.println(booleanArray.getValue(64)); 45 | Arrays.stream(booleanArray.array) 46 | .forEach(System.out::print); 47 | 48 | System.out.println(55 >> 1); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/array/GetLongestSortableSubArr.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.array; 2 | 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | 6 | /** 7 | * 最长的可整合子数组的长度。定义:一个数组在排序之后,每相邻两个数差的绝对值都为1,则该数组称为可整合数组 8 | * 9 | * 例如:[5,5,3,2,6,4,3] 最大可整合子数组为【5,3,2,6,4】 10 | * 11 | * @author lichao 12 | * @date 2017/11/18 13 | */ 14 | public class GetLongestSortableSubArr { 15 | 16 | public static void main(String[] args) { 17 | System.out.println(getLIL(new int[]{5, 5, 3, 2, 6, 4, 3})); 18 | } 19 | 20 | /** 21 | * 检验规则:一个数组中如果没有重复元素,并且如果最大值减去最小值,再加上1的结果等于元素个数 22 | * 23 | * (max-min+1==元素个数),那么这个数组就是可整合数组 24 | * 25 | * @param arr 数组 26 | * @return 最大可整合子数组长度 27 | */ 28 | public static int getLIL(int[] arr) { 29 | if (arr == null || arr.length == 0) { 30 | return 0; 31 | } 32 | 33 | int maxLen = 0; 34 | int min = 0; 35 | int max = 0; 36 | //确保子数组中间不出现重复的元素 37 | Set set = new HashSet<>(); 38 | 39 | for (int i = 0; i < arr.length; i++) { 40 | min = Integer.MAX_VALUE; 41 | max = Integer.MIN_VALUE; 42 | 43 | for (int j = i; j < arr.length; j++) { 44 | if (set.contains(arr[j])) { 45 | break; 46 | } 47 | 48 | min = Math.min(arr[j], min); 49 | max = Math.max(arr[j], max); 50 | if (max - min == j - i) { 51 | maxLen = Math.max(maxLen, j - i + 1); 52 | } 53 | } 54 | 55 | set.clear(); 56 | } 57 | 58 | return maxLen; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/array/GetNeedSortMinLength.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.array; 2 | 3 | /** 4 | * 需要排序的最短子数组长度 5 | * 6 | * @author lichao 7 | * @date 2017/11/17 8 | */ 9 | public class GetNeedSortMinLength { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | /** 16 | * 给定一个无序数组arr,求出需要排序的最短子数组长度 17 | * 18 | * @param arr 数组arr 19 | * @return 返回需要排序的长度 20 | */ 21 | public static int getMinLength(int[] arr) { 22 | if (arr == null || arr.length < 2) { 23 | return 0; 24 | } 25 | 26 | int min = arr[arr.length - 1]; 27 | int noMinIndex = -1; 28 | for (int i = arr.length - 2; i != -1; i--) { 29 | if (arr[i] > min) { 30 | noMinIndex = i; 31 | } else { 32 | min = Math.min(min, arr[i]); 33 | } 34 | } 35 | 36 | if (noMinIndex == -1) { 37 | return 0; 38 | } 39 | 40 | int max = arr[0]; 41 | int noMaxIndex = -1; 42 | for (int i = 1; i != arr.length; i++) { 43 | if (arr[i] < max) { 44 | noMaxIndex = i; 45 | } else { 46 | max = Math.max(max, arr[i]); 47 | } 48 | } 49 | 50 | return noMaxIndex - noMinIndex + 1; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/array/ListPartition.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.array; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | 5 | /** 6 | * 将单向链表按某值划分成左边小,中间相等,右边大的形式 Created by lichao on 2017/1/8. 7 | */ 8 | public class ListPartition { 9 | // public static void main(String[] args) { 10 | // 11 | // } 12 | 13 | public static TreeNode listPartition1(TreeNode head, int pivot) { 14 | if (head == null) { 15 | return head; 16 | } 17 | TreeNode curr = head; 18 | int i = 0; 19 | while (curr != null) { 20 | i++; 21 | curr = curr.next; 22 | } 23 | TreeNode[] treeNodeArray = new TreeNode[i]; 24 | curr = head; 25 | for (i = 0; i != treeNodeArray.length; i++) { 26 | treeNodeArray[i] = curr; 27 | curr = curr.next; 28 | } 29 | arrPartition(treeNodeArray, pivot); 30 | for (i = 1; i != treeNodeArray.length; i++) { 31 | treeNodeArray[i - 1].next = treeNodeArray[i]; 32 | } 33 | treeNodeArray[i - 1].next = null; 34 | return treeNodeArray[0]; 35 | } 36 | 37 | public static void arrPartition(TreeNode[] treeNodeArray, int pivot) { 38 | int small = -1; 39 | int big = treeNodeArray.length; 40 | int index = 0; 41 | while (index != big) { 42 | if (treeNodeArray[index].val < pivot) { 43 | swap(treeNodeArray, ++small, index++); 44 | } else if (treeNodeArray[index].val == pivot) { 45 | index++; 46 | } else { 47 | swap(treeNodeArray, --big, index); 48 | } 49 | } 50 | } 51 | 52 | public static void swap(TreeNode[] treeNodeArr, int a, int b) { 53 | TreeNode temp = treeNodeArr[a]; 54 | treeNodeArr[a] = treeNodeArr[b]; 55 | treeNodeArr[b] = temp; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/binarytree/GetMaxLengthSum.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.binarytree; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | import java.util.HashMap; 5 | 6 | /** 7 | * Created by lichao on 2017/9/5. 在二叉树中找到累加和为指定值的最长路径长度 8 | * 9 | * 用哈希表sumMap ,key代表从head开始的一条路径上的累加和出现情况,value值代表这个累加和在路径中最早出现的层数 如果在遍历到 10 | * cur即节点的时候,我们能够知道从head到cur节点这条路径上的累加和出现情况,那么求以cur节点结尾的累加和 为指定值的最长路径长度就非常容易,所以这里我们采用先序遍历 11 | */ 12 | public class GetMaxLengthSum { 13 | 14 | public static void main(String[] args) { 15 | 16 | } 17 | 18 | 19 | public int getMaxLengthSum(TreeNode head, int sum) { 20 | HashMap sumMap = new HashMap<>(); 21 | sumMap.put(0, 0);//重要 22 | return preOrder(head, sum, 0, 1, 0, sumMap); 23 | } 24 | 25 | public int preOrder(TreeNode head, int sum, int preSum, int level, int maxLen, 26 | HashMap sumMap) { 27 | if (head == null) { 28 | return maxLen; 29 | } 30 | 31 | int curSum = preSum + head.val; 32 | if (!sumMap.containsKey(curSum)) { 33 | sumMap.put(curSum, level); 34 | } 35 | 36 | if (sumMap.containsKey(curSum - sum)) { 37 | maxLen = Math.max(level - sumMap.get(curSum - sum), maxLen); 38 | } 39 | 40 | maxLen = preOrder(head.left, sum, curSum, level + 1, maxLen, sumMap); 41 | maxLen = preOrder(head.right, sum, curSum, level + 1, maxLen, sumMap); 42 | 43 | //这里得注意,返回到父节点的时候记得删除map里面属于父节点的记录,否则会造成路径不通的情况 44 | if (level == sumMap.get(curSum)) { 45 | sumMap.remove(curSum); 46 | } 47 | 48 | return maxLen; 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/binarytree/GetTwoErrorNodes.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.binarytree; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | 5 | import java.util.Stack; 6 | 7 | /** 8 | * Created by lichao on 2017/9/10. 9 | */ 10 | public class GetTwoErrorNodes { 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | /** 16 | * 思路是中序遍历的时候会出现两次降序 17 | * 18 | * @param head 19 | * @return 20 | */ 21 | public static TreeNode[] getTwoErrorNodes(TreeNode head) { 22 | TreeNode[] errors = new TreeNode[2]; 23 | if (head == null) { 24 | return errors; 25 | } 26 | 27 | Stack stack = new Stack<>(); 28 | TreeNode pre = null; 29 | 30 | while (!stack.isEmpty() || head != null) { 31 | if (head != null) { 32 | stack.push(head); 33 | head = head.left; 34 | } else { 35 | head = stack.pop(); 36 | if (head != null && pre != null && head.val < pre.val) { 37 | errors[0] = errors[0] == null ? pre : errors[0]; 38 | errors[1] = head; 39 | } 40 | 41 | pre = head; 42 | head = head.right; 43 | } 44 | 45 | } 46 | 47 | return errors; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/binarytree/MaxDistance.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.binarytree; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | 5 | /** 6 | * Created by lichao on 2017/9/19. 二叉树节点间的最大距离问题 7 | * 8 | * 一个以h为头的树上,最大距离只可能来自以下三种情况: 9 | * 10 | * 1)h的左子树上的最大距离 2)h的右子树上的最大距离 3)h左子树离h.left最远的距离+1(h)+h右子树上离h.right最远的距离 11 | */ 12 | public class MaxDistance { 13 | 14 | public static void main(String[] args) { 15 | 16 | } 17 | 18 | public static int getMaxDistance(TreeNode head) { 19 | int[] record = new int[1]; 20 | return posOrder(head, record); 21 | } 22 | 23 | public static int posOrder(TreeNode head, int[] record) { 24 | if (head == null) { 25 | record[0] = 0; 26 | return 0; 27 | } 28 | 29 | int lMax = posOrder(head.left, record); 30 | int maxFromLeft = record[0]; 31 | 32 | int rMax = posOrder(head.right, record); 33 | int maxFromRight = record[0];//右子树最大距离 34 | 35 | int curNodeMax = maxFromLeft + maxFromRight + 1; //跨节点距离 36 | record[0] = Math.max(maxFromLeft, maxFromRight) + 1;//距离当前头节点最远的距离,作为上一层的左/右最大距离 37 | 38 | return Math.max(Math.max(lMax, rMax), curNodeMax); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/binarytree/RBTNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.binarytree; 2 | 3 | /** 4 | * Created by lichao on 2017/2/5. 5 | */ 6 | public class RBTNode> { 7 | boolean color; // 颜色 8 | T key; // 关键字(键值) 9 | RBTNode left; // 左孩子 10 | RBTNode right; // 右孩子 11 | RBTNode parent; // 父结点 12 | 13 | public RBTNode(T key, boolean color, RBTNode parent, RBTNode left, RBTNode right) { 14 | this.key = key; 15 | this.color = color; 16 | this.parent = parent; 17 | this.left = left; 18 | this.right = right; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/binarytree/SumCompleteBinaryTreeNodes.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.binarytree; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | 5 | /** 6 | * Created by lichao on 2017/9/24. 统计完全二叉树的节点数(给定头节点,返回这棵树的节点个数) 7 | */ 8 | public class SumCompleteBinaryTreeNodes { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | /** 15 | * 直接遍历即可,时间复杂度为O(2^n),n为二叉树的高度 16 | */ 17 | public static int sumCompleteBinaryTreeNodes(TreeNode head) { 18 | if (head == null) { 19 | } 20 | 21 | return 0; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/FeiBoNaQie.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/2/5. 5 | */ 6 | public class FeiBoNaQie { 7 | public static void main(String[] args) { 8 | //System.out.println(getMethodNumber(10)); 9 | } 10 | 11 | /** 12 | * 给定整数N,代表台阶数,一次可以跨2个或者一个台阶,返回有多少种走法(暴力递归 复杂度O(2^n)) 13 | */ 14 | public static int getMethodNumber1(int n) { 15 | if (n == 1) { 16 | return 1; 17 | } 18 | 19 | if (n == 2) { 20 | return 2; 21 | } 22 | 23 | return getMethodNumber1(n - 1) + getMethodNumber1(n - 2); 24 | } 25 | 26 | /** 27 | * 复杂度为O(N) 28 | */ 29 | public static int getMethodNumber2(int n) { 30 | if (n < 1) { 31 | return 0; 32 | } 33 | if (n == 1 || n == 2) { 34 | return 1; 35 | } 36 | int result = 1; 37 | int pre = 1; 38 | int temp = result; 39 | for (int i = 3; i < n; i++) { 40 | temp = result; 41 | result = result + pre; 42 | pre = temp; 43 | } 44 | 45 | return result; 46 | } 47 | 48 | 49 | /** 50 | * 农场1头母牛,第二年生小母牛,每只小母牛三年之后成熟又可以生小母牛,求N年后牛的数量。牛永远不会死 51 | */ 52 | public static int getCowNumber(int n) { 53 | if (n == 1 || n == 2 || n == 3) { 54 | return n; 55 | } 56 | 57 | return getCowNumber(n - 1) + getCowNumber(n - 3); 58 | } 59 | 60 | 61 | } 62 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/HannoTa.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/9/29. 5 | */ 6 | public class HannoTa { 7 | 8 | public static void main(String[] args) { 9 | hannoi(5); 10 | } 11 | 12 | //原始题目 13 | public static void hannoi(int n) { 14 | if (n > 0) { 15 | func(n, "left", "mid", "right"); 16 | } 17 | } 18 | 19 | public static void func(int n, String from, String mid, String to) { 20 | if (n == 1) { 21 | System.out.println("move from " + from + " to " + to); 22 | } else { 23 | func(n - 1, from, to, mid); 24 | func(1, from, mid, to); 25 | func(n - 1, mid, from, to); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/HouseRobber.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/2/19. 5 | */ 6 | public class HouseRobber { 7 | public static void main(String[] args) { 8 | 9 | } 10 | 11 | /** 12 | * 暴力递归思路 13 | */ 14 | public static int robMaxValue(int index, int[] values) { 15 | if (index < 0) { 16 | return 0; 17 | } 18 | 19 | return Math.max(values[index] + robMaxValue(index - 2, values), robMaxValue(index - 1, values)); 20 | } 21 | 22 | /** 23 | * 动态规划 24 | */ 25 | public static int robMaxValue(int[] values) { 26 | if (values == null || values.length <= 0) { 27 | return 0; 28 | } 29 | 30 | int max0 = 0; 31 | int max1 = 0; 32 | 33 | for (int i = 0; i < values.length; i++) { 34 | int temp = max0; 35 | max0 = Math.max(max0, max1); 36 | max1 = temp + values[i]; 37 | } 38 | 39 | return Math.max(max0, max1); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/JumpGame.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/10/8. 5 | */ 6 | //给定一个数组arr,arr[j]=k代表可以从位置i向右跳1~k个距离 7 | //比如arr[2]=3,代表从位置2跳到位置3,4,5。如果从位置0出发,返回最少跳几次 8 | //能跳到arr最后的位置上 9 | public class JumpGame { 10 | 11 | public static void main(String[] args) { 12 | System.out.println(jumpStep(new int[]{3, 2, 3, 1, 1, 4})); 13 | } 14 | 15 | public static int jumpStep(int[] arr) { 16 | if (arr == null || arr.length == 0) { 17 | return 0; 18 | } 19 | 20 | //当前步骤可以覆盖到的位置 21 | int curr = 0; 22 | //下一步可以覆盖到的最远的位置 23 | int next = 0; 24 | //需要跳跃的次数 25 | int jump = 0; 26 | 27 | for (int i = 0; i < arr.length; i++) { 28 | if (curr < i) { 29 | jump++; 30 | curr = next; 31 | } 32 | 33 | //快速退出 34 | if (curr >= arr.length - 1) { 35 | break; 36 | } 37 | 38 | next = Math.max(next, i + arr[i]); 39 | } 40 | 41 | return jump; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/MaxGold.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * @author lichao 5 | * @date 2017/11/7 6 | */ 7 | //国王和金矿: 8 | //有一个国家发现了5座金矿,每座金矿的黄金储量不同,需要参与挖掘的工人数也不同。 9 | // 参与挖矿工人的总数是10人。每座金矿要么全挖,要么不挖,不能派出一半人挖取一半金矿。 10 | // 要求用程序求解出,要想得到尽可能多的黄金,应该选择挖取哪几座金矿? 11 | //Math.max(dp[i - 1][j], dp[i - 1][j - person[i]] + gold[i]); 12 | public class MaxGold { 13 | 14 | public static void main(String[] args) { 15 | //金矿数组 16 | int[] gold = new int[]{400, 500, 200, 300, 350}; 17 | int[] person = new int[]{5, 5, 3, 4, 3}; 18 | int personCount = 10; 19 | 20 | System.out.println(getMaxGold(gold, person, personCount)); 21 | } 22 | 23 | public static int getMaxGold(int[] gold, int[] person, int personCount) { 24 | if (gold == null || person == null || gold.length == 0 || person.length == 0) { 25 | return 0; 26 | } 27 | 28 | int[][] dp = new int[gold.length][personCount + 1]; 29 | //填充边界 30 | for (int i = 0; i <= personCount; i++) { 31 | if (person[0] > i) { 32 | dp[0][i] = 0; 33 | } else { 34 | dp[0][i] = gold[0]; 35 | } 36 | } 37 | 38 | for (int i = 1; i < gold.length; i++) { 39 | for (int j = 1; j <= personCount; j++) { 40 | if (j < person[i]) { 41 | dp[i][j] = dp[i - 1][j]; 42 | } else { 43 | //递推式 44 | dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - person[i]] + gold[i]); 45 | } 46 | } 47 | } 48 | 49 | return dp[gold.length - 1][personCount]; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/MinEditCost.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * 最小编辑代价,给定俩个字符串str1和str2,再给定三个整数ic、dc、和rc,分别代表插入、删除和替换一个字符的代价,返回将str1编辑成str2的最小代价 5 | */ 6 | public class MinEditCost { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static int minCost1(String str1, String str2, int ic, int dc, int rc) { 13 | if (str1 == null || str2 == null) { 14 | return 0; 15 | } 16 | 17 | char[] chs1 = str1.toCharArray(); 18 | char[] chs2 = str2.toCharArray(); 19 | int row = chs1.length + 1; 20 | int col = chs2.length + 1; 21 | //dp[i][j]表示把str1[0,i]编辑成str2[0,j]的最小代价 22 | int[][] dp = new int[row][col]; 23 | 24 | for (int i = 1; i < row; i++) { 25 | dp[i][0] = dc * i; 26 | } 27 | 28 | for (int j = 1; j < col; j++) { 29 | dp[0][j] = ic * j; 30 | } 31 | 32 | //来自四种情况 33 | for (int i = 1; i < row; i++) { 34 | for (int j = 1; j < col; j++) { 35 | if (chs1[i - 1] == chs2[j - 1]) { 36 | dp[i][j] = dp[i - 1][j - 1]; 37 | } else { 38 | dp[i][j] = dp[i - 1][j - 1] + rc; 39 | } 40 | 41 | dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + dc); 42 | dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + ic); 43 | } 44 | } 45 | 46 | return dp[row - 1][col - 1]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/NQueens.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/10/4. 5 | */ 6 | //N皇后问题。N*N的棋盘上要摆N个皇后,要求任何两个皇后不同行,不同列,也不在同一条斜线上。给定一个整数n,返回n皇后的摆法有 7 | //多少种 8 | public class NQueens { 9 | 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static int num1(int n) { 15 | if (n < 1) { 16 | return 0; 17 | } 18 | 19 | //表示第i行皇后所在的列数 20 | int[] record = new int[n]; 21 | return process(1, record, n); 22 | } 23 | 24 | public static int process(int i, int[] record, int n) { 25 | if (i == n) { 26 | return 1; 27 | } 28 | 29 | int res = 0; 30 | for (int j = 0; j < n; j++) { 31 | if (isvaild(record, i, j)) { 32 | record[i] = j; 33 | res += process(i + 1, record, n); 34 | } 35 | } 36 | 37 | return res; 38 | } 39 | 40 | public static boolean isvaild(int[] record, int i, int j) { 41 | for (int k = 0; k < i; k++) { 42 | if (j == record[k] || Math.abs(record[k] - j) == Math.abs(i - k)) { 43 | return false; 44 | } 45 | } 46 | 47 | return true; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/dp/StrToCharMethods.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.dp; 2 | 3 | /** 4 | * Created by lichao on 2017/10/4. 5 | */ 6 | // 数字字符串转换为字母组合的种数 7 | // 给定一个字符串str, str全部由数字字符组成,如果str中某一个或某相邻俩个字符组成的子串 8 | // 在1~26 之间,则这个子串可以转换为一个字母,规定"1"转换为A,"2"转换为B 9 | public class StrToCharMethods { 10 | 11 | public static void main(String[] args) { 12 | 13 | } 14 | 15 | //暴力递归 16 | public static int num1(String str) { 17 | if (str == null || str.equals("")) { 18 | return 0; 19 | } 20 | 21 | char[] chars = str.toCharArray(); 22 | return process(chars, 0); 23 | } 24 | 25 | public static int process(char[] chars, int i) { 26 | if (i == chars.length) { 27 | return 1; 28 | } 29 | 30 | if (chars[i] == '0') { 31 | return 0; 32 | } 33 | 34 | int res = process(chars, i + 1); 35 | if (i + 1 < chars.length && ((chars[i] - '0') * 10 + chars[i + 1] - '0') < 27) { 36 | res += process(chars, i + 2); 37 | } 38 | 39 | return res; 40 | } 41 | 42 | // 从后往前计算p(i)=p(i+1)+p(i+2) 43 | public static int num2(String str) { 44 | if (str == null || str.equals("")) { 45 | return 0; 46 | } 47 | 48 | char[] chars = str.toCharArray(); 49 | int cur = chars[chars.length - 1] == '0' ? 0 : 1; 50 | int next = 1; 51 | int tmp = 0; 52 | for (int i = chars.length - 2; i >= 0; i--) { 53 | if (chars[i] == '0') { 54 | next = cur; 55 | cur = 0; 56 | } else { 57 | tmp = cur; 58 | if ((chars[i] - '0') * 10 + chars[i + 1] - '0' < 27) { 59 | cur += next; 60 | next = tmp; 61 | } 62 | } 63 | } 64 | 65 | return cur; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/linklist/JosephusKill.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.linklist; 2 | 3 | import com.jacobs.basic.algorithm.TreeNode; 4 | 5 | /** 6 | * Created by lichao on 2017/1/7. 7 | * 约瑟夫环问题 8 | */ 9 | public class JosephusKill { 10 | public static void main(String[] args) { 11 | 12 | } 13 | 14 | public static TreeNode josephusKill1(TreeNode head, int m) { 15 | if (head == null || head.next == head || m < 1) { 16 | return head; 17 | } 18 | 19 | TreeNode last = head; 20 | while (last.next != head) { 21 | last = last.next; 22 | } 23 | int count = 1; 24 | while (head != last) { 25 | if (++count != m) { 26 | last = last.next; 27 | } else { 28 | last.next = head.next; 29 | count = 1; 30 | } 31 | head = last.next; 32 | } 33 | return head; 34 | } 35 | 36 | /** 37 | * B=(A-1)%i+1 38 | * old=(new+s-1)%i+1 39 | * s=(m-1)%i+1 40 | * old=(new+m-1)%i+1 41 | */ 42 | public static TreeNode josephusKill2(TreeNode head, int m) { 43 | if (head == null || head.next == head || m < 1) { 44 | return head; 45 | } 46 | 47 | TreeNode cur = head.next; 48 | int temp = 1; 49 | while (cur != head) { 50 | temp++; 51 | cur = cur.next; 52 | } 53 | temp = getLive(temp, m); 54 | while (--temp != 0) { 55 | head = head.next; 56 | } 57 | return head.next; 58 | } 59 | 60 | public static int getLive(int i, int m) { 61 | if (i == 1) { 62 | return 1; 63 | } 64 | 65 | return (getLive(i - 1, m) + m - i) % i + 1; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/recursion/RecursionSamples.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.recursion; 2 | 3 | /** 4 | * Created by lichao on 2017/9/25. 5 | */ 6 | public class RecursionSamples { 7 | 8 | public static void main(String[] args) { 9 | //feibonaqie 10 | System.out.println(getCowNum(5)); 11 | } 12 | 13 | 14 | //斐波那契额数组 15 | public static int feibonaqie(int n) { 16 | if (n < 0) { 17 | return 0; 18 | } 19 | if (n == 1 || n == 2) { 20 | return 1; 21 | } 22 | 23 | return feibonaqie(n - 1) + feibonaqie(n - 2); 24 | } 25 | 26 | //斐波那契非递归 27 | public static int feibonaqie2(int n) { 28 | if (n < 0) { 29 | return 0; 30 | } 31 | 32 | if (n == 1 || n == 2) { 33 | return 1; 34 | } 35 | 36 | int f1 = 1; 37 | int f2 = 1; 38 | 39 | int fi = 0; 40 | for (int i = 3; i <= n; i++) { 41 | fi = f1 + f2; 42 | f1 = f2; 43 | f2 = fi; 44 | } 45 | 46 | return fi; 47 | } 48 | 49 | //给定整数N,代表台阶数,一次可以跨2个或者1个台阶,返回有多少种走法 50 | public static int getStepsNum(int n) { 51 | if (n < 0) { 52 | return 0; 53 | } 54 | if (n == 1 || n == 2) { 55 | return n; 56 | } 57 | 58 | return getStepsNum(n - 1) + getStepsNum(n - 2); 59 | } 60 | 61 | //农场奶牛每年生一头小母牛,永远不会死,第一年有一只成熟的母牛,从第二年开始,母牛开始生小母牛,每只小母牛3年后又可以生小母牛 62 | //给定整数N,求出N年后牛的数量 63 | public static int getCowNum(int n) { 64 | if (n < 0) { 65 | return 0; 66 | } 67 | if (n < 3) { 68 | return n; 69 | } 70 | 71 | return getCowNum(n - 3) + getCowNum(n - 1); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/sortmethods/MergeSort.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.sortmethods; 2 | 3 | import java.util.Arrays; 4 | 5 | /** 6 | * Created by lichao on 2017/1/21. 7 | */ 8 | public class MergeSort { 9 | public static void main(String[] args) { 10 | int[] list = {1, 5, 6, 8, 10, 25, 16}; 11 | mergeSort(list, 0, list.length - 1); 12 | Arrays.stream(list) 13 | .forEach(System.out::println); 14 | } 15 | 16 | // 详细步骤: 17 | // 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列 18 | // 设定两个指针,最初位置分别为两个已经排序序列的起始位置 19 | // 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置 20 | // 重复步骤3直到某一序列的指针达到序列尾 21 | // 将另一序列剩下的所有元素直接复制到合并序列尾,一次归并结束 22 | public static void mergeSort(int[] list, int left, int right) { 23 | if (left >= right) { 24 | //退栈 25 | return; 26 | } 27 | int center = (left + right) >> 1; 28 | mergeSort(list, left, center); 29 | mergeSort(list, center + 1, right); 30 | merge(list, left, center, right); 31 | } 32 | 33 | public static void merge(int[] list, int left, int center, int right) { 34 | int[] tempArr = new int[right + 1]; 35 | int index = left; 36 | int tmpLeft = left; 37 | int tmpMid = center + 1; 38 | 39 | while (tmpLeft <= center && tmpMid <= right) { 40 | tempArr[index++] = list[tmpLeft] >= list[tmpMid] ? list[tmpMid++] : list[tmpLeft++]; 41 | } 42 | while (tmpMid <= right) { 43 | tempArr[index++] = list[tmpMid++]; 44 | } 45 | while (tmpLeft <= center) { 46 | tempArr[index++] = list[tmpLeft++]; 47 | } 48 | 49 | //复制到原数组 50 | for (int i = left; i <= right; i++) { 51 | list[i] = tempArr[i]; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/sortmethods/RadixSort.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.sortmethods; 2 | 3 | import static java.lang.Math.pow; 4 | 5 | import java.util.Arrays; 6 | 7 | /** 8 | * Created by lichao on 2017/9/19. 9 | */ 10 | public class RadixSort { 11 | 12 | 13 | /** 14 | * 稳定排序与非稳定排序的区别:非稳定排序在排序的过程中元素之间的相对位置会发生变化 15 | */ 16 | public static void main(String[] args) { 17 | int[] arr = new int[]{3, 4, 12, 34, 33, 22, 25, 44, 12}; 18 | sort(arr); 19 | Arrays.stream(arr).forEach(System.out::println); 20 | } 21 | 22 | 23 | //有n个数,取值范围是0~n^2 24 | public static void sort(int[] a) { 25 | int n = a.length; 26 | int[] c = new int[n]; 27 | int[] remainder = new int[a.length]; 28 | int[] b = new int[a.length]; 29 | 30 | //考虑的是两位数的排序,所以这里先取个位,再取十位 31 | for (int i = 0; i < 2; i++) { 32 | for (int j = 0; j < a.length; j++) { 33 | int temp = getRadix(a[j], i, n); 34 | remainder[j] = temp; 35 | c[temp]++; 36 | } 37 | 38 | for (int k = 1; k < n; k++) { 39 | c[k] += c[k - 1]; 40 | } 41 | 42 | for (int j = a.length - 1; j >= 0; j--) { 43 | b[--c[remainder[j]]] = a[j]; 44 | } 45 | 46 | for (int j = 0; j < n; j++) { 47 | c[j] = 0; 48 | } 49 | 50 | for (int j = 0; j < a.length; j++) { 51 | a[j] = b[j]; 52 | } 53 | } 54 | } 55 | 56 | public static int getRadix(int a, int i, int radix) { 57 | return ((int) (a / pow(radix, i))) % radix; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/sortmethods/ShellSort.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.sortmethods; 2 | 3 | /** 4 | * Created by lichao on 2017/9/16. 希尔排序 5 | */ 6 | public class ShellSort { 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | 12 | public static void shellSort(int[] a) { 13 | int N = a.length; 14 | 15 | int h = 1; 16 | while (h < N / 3) { 17 | h = 3 * h + 1;//1,4,13,40,121 18 | } 19 | 20 | while (h >= 1) { 21 | for (int i = h; i < N; i++) { 22 | for (int j = i; j > h && less(a[j], a[j - h]); j -= h) { 23 | exch(a, a[j], a[j - h]); 24 | } 25 | } 26 | 27 | h = h / 3; 28 | } 29 | } 30 | 31 | public static boolean less(int a, int b) { 32 | return a > b ? false : true; 33 | } 34 | 35 | public static void exch(int[] a, int b, int c) { 36 | int temp = a[b]; 37 | a[b] = a[c]; 38 | a[c] = temp; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/algorithm/string/LongestPalindrome.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.algorithm.string; 2 | 3 | /** 4 | * Created by lichao on 2017/3/17. 5 | */ 6 | public class LongestPalindrome { 7 | public static void main(String[] args) { 8 | System.out.println(longestPalindrome1("abcdce")); 9 | } 10 | 11 | /** 12 | * 返回值为0表示不存在回文字串,假设中心为i,向两边扩展。 13 | */ 14 | public static int longestPalindrome1(String str) { 15 | if (str == null || str.length() <= 0) { 16 | return 0; 17 | } 18 | 19 | int length = str.length(); 20 | int max = 0; 21 | int loopLength = 0; 22 | for (int i = 0; i < str.length(); i++) { 23 | for (int j = 0; (i - j >= 0) && (i + j < length); j++) { 24 | if (str.charAt(i - j) != str.charAt(i + j)) { 25 | break; 26 | } 27 | loopLength = j * 2 + 1; 28 | } 29 | 30 | if (loopLength > max) { 31 | max = loopLength; 32 | } 33 | 34 | for (int j = 0; (i - j >= 0) && (i + j + 1 < length); j++) { 35 | if (str.charAt(i - j) != str.charAt(i + j + 1)) { 36 | break; 37 | } 38 | loopLength = j * 2 + 2; 39 | } 40 | 41 | if (loopLength > max) { 42 | max = length; 43 | } 44 | } 45 | 46 | return max; 47 | } 48 | 49 | /** 50 | * 优化复杂度为 O(n) Manacher算法...待实现 51 | */ 52 | public static int longestPalindrome2(String str) { 53 | if (str == null || str.length() <= 0) { 54 | return 0; 55 | } 56 | 57 | return 0; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/designpattern/SingleTonTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.designpattern; 2 | 3 | /** 4 | * Created by lichao on 2017/2/15. 5 | */ 6 | public class SingleTonTest { 7 | 8 | //延迟加载,由java内部实现线程安全 9 | private static class Holder { 10 | 11 | static SingleTonTest singleTonTest = new SingleTonTest(); 12 | } 13 | 14 | public static SingleTonTest getInstance() { 15 | return Holder.singleTonTest; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/FcInterfaceTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | /** 4 | * Created by lichao on 16/8/11. 5 | */ 6 | @FunctionalInterface 7 | public interface FcInterfaceTest { 8 | T parseString(int number); 9 | } 10 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/ForkJoinSumCalculator.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | /** 4 | * Created by lichao on 16/7/27. 5 | */ 6 | public class ForkJoinSumCalculator extends java.util.concurrent.RecursiveTask { 7 | 8 | private final long[] numbers; 9 | private final int start; 10 | private final int end; 11 | 12 | public static final long THRESHOLD = 10000; 13 | 14 | public ForkJoinSumCalculator(long[] numbers) { 15 | this(numbers, 0, numbers.length); 16 | } 17 | 18 | private ForkJoinSumCalculator(long[] numbers, int start, int end) { 19 | this.numbers = numbers; 20 | this.start = start; 21 | this.end = end; 22 | } 23 | 24 | @Override 25 | protected Long compute() { 26 | int length = end - start; 27 | if (length <= THRESHOLD) { 28 | return computeSequentially(); 29 | } 30 | ForkJoinSumCalculator leftTask = new ForkJoinSumCalculator(numbers, start, start + length / 2); 31 | //利用另一个forkjoinpool线程异步执行新创建的任务 32 | leftTask.fork(); 33 | ForkJoinSumCalculator rigthTask = new ForkJoinSumCalculator(numbers, start + length / 2, end); 34 | Long rightResult = rigthTask.join(); 35 | Long leftResult = leftTask.join(); 36 | return leftResult + rightResult; 37 | } 38 | 39 | private long computeSequentially() { 40 | long sum = 0; 41 | for (int i = start; i < end; i++) { 42 | sum += numbers[i]; 43 | } 44 | return sum; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/GenericsDemo.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | import java.util.HashMap; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | /** 8 | * @author lichao 9 | * @date 2017/11/5 10 | */ 11 | public class GenericsDemo { 12 | 13 | public static void main(String[] args) { 14 | 15 | } 16 | 17 | //不能把null之外的任何值放到List中。所以可以编写一个helper方法用来转换 18 | public static void swap(List list, int i, int j) { 19 | swapHelper(list, i, j); 20 | } 21 | 22 | private static void swapHelper(List list, int i, int j) { 23 | list.set(i, list.set(j, list.get(i))); 24 | } 25 | 26 | public static class Favorites { 27 | 28 | private Map, Object> favorites = new HashMap, Object>(); 29 | 30 | public void putFavorites(Class type, T instance) { 31 | if (type == null) { 32 | throw new NullPointerException("type is null"); 33 | } 34 | favorites.put(type, instance); 35 | } 36 | 37 | public T getFavorites(Class type) { 38 | return type.cast(favorites.get(type)); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/Java8MainTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | import java.util.concurrent.ForkJoinPool; 4 | import java.util.concurrent.ForkJoinTask; 5 | import java.util.stream.LongStream; 6 | 7 | /** 8 | * Created by lichao on 16/7/27. 9 | */ 10 | public class Java8MainTest { 11 | 12 | public static void main(String[] args) { 13 | System.out.println(forkJoinSum(200000)); 14 | } 15 | 16 | public static long forkJoinSum(long n) { 17 | long[] numbers = LongStream.rangeClosed(1, n).toArray(); 18 | ForkJoinTask task = new ForkJoinSumCalculator(numbers); 19 | return new ForkJoinPool().invoke(task); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/Person.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | /** 9 | * Created by lichao on 16/7/11. 10 | */ 11 | @Data 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @Builder 15 | public class Person { 16 | private String firstName; 17 | private String lastName; 18 | private String job; 19 | private String gender; 20 | private int salary; 21 | private int age; 22 | } 23 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/lazylist/LazyList.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice.lazylist; 2 | 3 | import java.util.function.Supplier; 4 | 5 | /** 6 | * Created by lichao on 16/8/14. 7 | */ 8 | public class LazyList implements MyList { 9 | final T head; 10 | final Supplier> tail; 11 | 12 | public LazyList(T head, Supplier> tail) { 13 | this.head = head; 14 | this.tail = tail; 15 | } 16 | 17 | @Override 18 | public T head() { 19 | return head; 20 | } 21 | 22 | @Override 23 | public MyList tail() { 24 | return tail.get(); 25 | } 26 | 27 | @Override 28 | public boolean isEmpty() { 29 | return false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/lazylist/MyList.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice.lazylist; 2 | 3 | /** 4 | * Created by lichao on 16/8/14. 5 | */ 6 | public interface MyList { 7 | T head(); 8 | 9 | MyList tail(); 10 | 11 | default boolean isEmpty() { 12 | return true; 13 | } 14 | 15 | } 16 | 17 | class MyLinkedList implements MyList { 18 | private final T head; 19 | private final MyList tail; 20 | 21 | public MyLinkedList(T head, MyList tail) { 22 | this.head = head; 23 | this.tail = tail; 24 | } 25 | 26 | @Override 27 | public Object head() { 28 | return head; 29 | } 30 | 31 | @Override 32 | public MyList tail() { 33 | return tail; 34 | } 35 | 36 | @Override 37 | public boolean isEmpty() { 38 | return false; 39 | } 40 | } 41 | 42 | class Empty implements MyList { 43 | @Override 44 | public T head() { 45 | return head(); 46 | } 47 | 48 | @Override 49 | public MyList tail() { 50 | return tail(); 51 | } 52 | 53 | @Override 54 | public boolean isEmpty() { 55 | return false; 56 | } 57 | } 58 | 59 | 60 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/java8pratice/predicate.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.java8pratice; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | /** 7 | * Created by lichao on 16/7/18. 8 | */ 9 | public interface predicate { 10 | boolean test(T t); 11 | 12 | default List filter(List list, predicate p) { 13 | List result = new ArrayList<>(); 14 | for (T e : list) { 15 | if (p.test(e)) { 16 | result.add(e); 17 | } 18 | } 19 | return result; 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/jinjia2java/AirflowVariableEnum.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.jinjia2java; 2 | 3 | import org.joda.time.LocalDate; 4 | import org.joda.time.format.DateTimeFormat; 5 | import org.joda.time.format.DateTimeFormatter; 6 | 7 | /** 8 | * 自定义sql兼容airflow macros 对时间的操作 9 | */ 10 | public enum AirflowVariableEnum implements Operation { 11 | DS("ds") { 12 | 13 | @Override 14 | public String apply() { 15 | return addDays(-1, DATE_TIME_FORMATTER); 16 | } 17 | }, 18 | 19 | DS_NO_DASH("ds_nodash") { 20 | 21 | @Override 22 | public String apply() { 23 | return addDays(-1, DATE_TIME_FORMATTER_NO_DASH); 24 | } 25 | }; 26 | 27 | private String name; 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | AirflowVariableEnum(String name) { 34 | this.name = name; 35 | } 36 | } 37 | 38 | interface Operation { 39 | 40 | DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd"); 41 | DateTimeFormatter DATE_TIME_FORMATTER_NO_DASH = DateTimeFormat.forPattern("yyyyMMdd"); 42 | 43 | String apply(); 44 | 45 | default String addDays(int days, DateTimeFormatter dateTimeFormatter) { 46 | return dateTimeFormatter.print(LocalDate.now().plusDays(days)); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/jinjia2java/CustomELFunctionDefinition.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.jinjia2java; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import com.hubspot.jinjava.lib.fn.ELFunctionDefinition; 6 | 7 | public class CustomELFunctionDefinition extends ELFunctionDefinition { 8 | 9 | private String namespace; 10 | private String localName; 11 | private Method method; 12 | 13 | public CustomELFunctionDefinition(String namespace, String localName, Class methodClass, 14 | String methodName, Class... parameterTypes) { 15 | super(namespace, localName, methodClass, methodName, parameterTypes); 16 | this.namespace = namespace; 17 | this.localName = localName; 18 | } 19 | 20 | public String getNamespace() { 21 | return namespace; 22 | } 23 | 24 | public String getLocalName() { 25 | return localName; 26 | } 27 | 28 | @Override 29 | public String getName() { 30 | return namespace + "." + localName; 31 | } 32 | 33 | public Method getMethod() { 34 | return method; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/jinjia2java/Macros.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.jinjia2java; 2 | 3 | public class Macros { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/WGki4K.java: -------------------------------------------------------------------------------- 1 | //给你一个整数数组 nums ,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 。请你找出并返回那个只出现了一次的元素。 2 | // 3 | // 4 | // 5 | // 示例 1: 6 | // 7 | // 8 | //输入:nums = [2,2,3,2] 9 | //输出:3 10 | // 11 | // 12 | // 示例 2: 13 | // 14 | // 15 | //输入:nums = [0,1,0,1,0,1,100] 16 | //输出:100 17 | // 18 | // 19 | // 20 | // 21 | // 提示: 22 | // 23 | // 24 | // 1 <= nums.length <= 3 * 104 25 | // -231 <= nums[i] <= 231 - 1 26 | // nums 中,除某个元素仅出现 一次 外,其余每个元素都恰出现 三次 27 | // 28 | // 29 | // 30 | // 31 | // 进阶:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? 32 | // 33 | // 34 | // 35 | // 注意:本题与主站 137 题相同:https://leetcode-cn.com/problems/single-number-ii/ 36 | // Related Topics 位运算 数组 37 | // 👍 40 👎 0 38 | 39 | 40 | package com.jacobs.basic.leetcode.editor.cn; 41 | 42 | public class WGki4K { 43 | public static void main(String[] args) { 44 | Solution solution = new WGki4K().new Solution(); 45 | } 46 | 47 | //leetcode submit region begin(Prohibit modification and deletion) 48 | class Solution { 49 | public int singleNumber(int[] nums) { 50 | // 由于每个元素都出现3次,必然每一位都为3的倍数,如果不是则说明目标元素在那个位上为1 51 | int result = 0; 52 | for (int i = 0; i < 32; i++) { 53 | int tmpSum = 0; 54 | for (int j = 0; j < nums.length; j++) { 55 | //得到每一位上的值 56 | tmpSum += (nums[j] >> i) & 1; 57 | } 58 | if (tmpSum % 3 != 0) { 59 | //取或操作 60 | result |= 1 << i; 61 | } 62 | } 63 | 64 | return result; 65 | } 66 | } 67 | //leetcode submit region end(Prohibit modification and deletion) 68 | 69 | } -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/han-jia-da-qia-ji-lu-jian-zhi-ii-offer-0-kahk.md: -------------------------------------------------------------------------------- 1 | ### 解题思路 2 | 可以用一个 int 型整数记录某个字符串中出现的字符。如果字符串包含 'a',那么整数最右边的数位为 1,如果字符串包含 'b',那么整数从右边起倒数第 2 位为 1。这样做的好处就是能更快地判定两个字符串是否包含相同的字符。如果两个字符串包含相同的字符,那么两个整数的与运算将不等于 0。反之,如果两个字符串不包含相同的字符,那么两个整数的与运算将等于 0 。 3 | ![image.png](https://pic.leetcode-cn.com/1642600177-jECTYO-image.png) 4 | 5 | ### 代码 6 | 7 | ```java 8 | class Solution { 9 | public int maxProduct(String[] words) { 10 | int res = 0, len = words.length; 11 | int[] nums = new int[len]; 12 | for(int i = 0; i < len; i++){ 13 | for(int j = 0, size = words[i].length(); j < size; j++){ 14 | nums[i] |= 1 << (words[i].charAt(j) - 'a'); 15 | } 16 | } 17 | for(int i = 0; i < len; i++){ 18 | for(int j = i + 1; j < len; j++){ 19 | if((nums[i] & nums[j]) == 0) res = Math.max(res, words[i].length() * words[j].length()); 20 | } 21 | } 22 | return res; 23 | } 24 | } 25 | ``` -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__-10+max_9,35_=25_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__-10+max_9,35_=25_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__0_le_i_n_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__0_le_i_n_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__0sim31_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__0sim31_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__20+max_15,7_=35_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__20+max_15,7_=35_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__Aoplus_B_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__Aoplus_B_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__Aoplus_Boplus_C_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__Aoplus_Boplus_C_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_log_C__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_log_C__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_log_n__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_log_n__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_max_{_|a|,_|b|_}__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_max_{_|a|,_|b|_}__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_n_log_C__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_n_log_C__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_n_log_n__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_n_log_n__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_|a|_+_|b|_+_X_cdot_max__{|a|_+_|b|}___.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__O_|a|_+_|b|_+_X_cdot_max__{|a|_+_|b|}___.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___00_to_01_to_10_to_00__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___00_to_01_to_10_to_00__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___a_i_=_a_i'b_i'x_i_+_a_ib_i'x_i'_=_b_i'_a_i_oplus_x_i___.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___a_i_=_a_i'b_i'x_i_+_a_ib_i'x_i'_=_b_i'_a_i_oplus_x_i___.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___b_i_=_a_i'b_i'x_i_+_a_i'b_ix_i'_=_a_i'_b_i_oplus_x_i___.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___b_i_=_a_i'b_i'x_i_+_a_i'b_ix_i'_=_a_i'_b_i_oplus_x_i___.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___textit{carry}_+_a_i_+_b_i__bmod{2}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p___textit{carry}_+_a_i_+_b_i__bmod{2}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__i-textit{prevIndex}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__i-textit{prevIndex}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__lfloor_frac{textit{carry}_+_a_i_+_b_i}{2}_rfloor_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__lfloor_frac{textit{carry}_+_a_i_+_b_i}{2}_rfloor_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__lfloor_n_3_rfloor_+_1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__lfloor_n_3_rfloor_+_1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__log_C=log_2^{32}_=_32_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__log_C=log_2^{32}_=_32_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__n_=_max{_|a|,_|b|_}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__n_=_max{_|a|,_|b|_}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{bound}-_i-1__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{bound}-_i-1__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{bound}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{bound}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{carry}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{carry}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{counter}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{counter}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{end}-textit{start}+1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{end}-textit{start}+1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{end}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{end}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_i_=-1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_i_=-1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_i_=1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{newNums}_i_=1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_i_=0_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_i_=0_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_i_=1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{nums}_i_=1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_i__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_i__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_k_-textit{prefixSums}_j_=0_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_k_-textit{prefixSums}_j_=0_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_k_-textit{prefixSums}_j__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prefixSums}_k_-textit{prefixSums}_j__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prevIndex}+1_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prevIndex}+1_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prevIndex}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{prevIndex}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{start}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{start}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}___s_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}___s_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}_ge_s_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__textit{sum}_ge_s_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{Python}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{Python}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{_x____i__&_1}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{_x____i__&_1}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{int}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__texttt{int}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_0__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_0__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_end__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_end__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_i-1__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_i-1__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_start__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_start__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_textit{end}__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_textit{end}__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_textit{start}__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{nums}_textit{start}__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_i__.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_i__.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_textit{bound}_-text{sums}_i-1__ge_s_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__text{sums}_textit{bound}_-text{sums}_i-1__ge_s_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__{_0,_1,_2_}_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/basic-learning/src/main/java/com/jacobs/basic/leetcode/editor/cn/doc/p__{_0,_1,_2_}_.png -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/models/ListNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.models; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by lichao on 2017/10/6. 7 | */ 8 | @Data 9 | public class ListNode { 10 | 11 | public int val; 12 | public ListNode next; 13 | 14 | public ListNode(int x) { 15 | val = x; 16 | next = null; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/models/RandomListNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.models; 2 | 3 | /** 4 | * Created by lichao on 2017/10/11. 5 | */ 6 | public class RandomListNode { 7 | 8 | public int label; 9 | public RandomListNode next, random; 10 | 11 | public RandomListNode(int x) { 12 | this.label = x; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/models/UndirectedGraphNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.models; 2 | 3 | import java.util.ArrayList; 4 | 5 | /** 6 | * Created by lichao on 2017/10/14. 7 | */ 8 | public class UndirectedGraphNode { 9 | 10 | public int label; 11 | public ArrayList neighbors; 12 | 13 | public UndirectedGraphNode(int x) { 14 | label = x; 15 | neighbors = new ArrayList(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/AtomicIntegerDemo.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Callable; 5 | import java.util.concurrent.ExecutionException; 6 | import java.util.concurrent.ExecutorService; 7 | import java.util.concurrent.Executors; 8 | import java.util.concurrent.FutureTask; 9 | import java.util.concurrent.atomic.AtomicInteger; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | /** 14 | * Created by lichao on 2016/12/16. 15 | */ 16 | public class AtomicIntegerDemo { 17 | 18 | static AtomicInteger number = new AtomicInteger(); 19 | 20 | public static class AddThread implements Callable { 21 | @Override 22 | public Integer call() throws Exception { 23 | for (int k = 0; k < 10000; k++) { 24 | number.incrementAndGet(); 25 | } 26 | return 1; 27 | } 28 | } 29 | 30 | public static void main(String[] args) throws InterruptedException, ExecutionException { 31 | Integer count = 0; 32 | ExecutorService executorService = Executors.newFixedThreadPool(10); 33 | List> futures = Stream.generate(() -> { 34 | FutureTask future = new FutureTask<>(new AddThread()); 35 | executorService.submit(future); 36 | return future; 37 | }) 38 | .limit(30) 39 | .collect(Collectors.toList()); 40 | for (FutureTask futureTask : futures) { 41 | futureTask.get(); 42 | } 43 | 44 | System.out.println(number.get()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/ConsumerAndProducer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.concurrent.BlockingQueue; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.LinkedBlockingDeque; 7 | 8 | /** 9 | * Created by lichao on 16/8/21. 10 | */ 11 | public class ConsumerAndProducer { 12 | 13 | //所有 14 | private static BlockingQueue blockingQueue = new LinkedBlockingDeque<>(5); 15 | static ExecutorService executorService = Executors.newFixedThreadPool(2); 16 | 17 | public static void main(String[] args) { 18 | executorService.submit(new ConsumerAndProducer().new Consumer()); 19 | executorService.submit(new ConsumerAndProducer().new Producer()); 20 | } 21 | 22 | class Producer implements Runnable { 23 | 24 | @Override 25 | public void run() { 26 | for (int i = 0; i < 10; i++) { 27 | try { 28 | blockingQueue.put("第" + i + "号产品"); 29 | System.out.println("生产了第" + i + "号产品"); 30 | } catch (InterruptedException e) { 31 | e.printStackTrace(); 32 | } 33 | } 34 | } 35 | } 36 | 37 | class Consumer implements Runnable { 38 | 39 | @Override 40 | public void run() { 41 | while (true) { 42 | try { 43 | String product = blockingQueue.take(); 44 | System.out.println("消费了" + product); 45 | } catch (InterruptedException e) { 46 | e.printStackTrace(); 47 | } 48 | } 49 | } 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/ControlSendThreads.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.Date; 4 | import java.util.concurrent.ExecutorService; 5 | import java.util.concurrent.Executors; 6 | import java.util.concurrent.Semaphore; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | /** 10 | * Created by lichao on 2016/10/28. 11 | */ 12 | public class ControlSendThreads { 13 | final static int MAX_QPS = 10; 14 | 15 | final static Semaphore semaphore = new Semaphore(MAX_QPS); 16 | 17 | public static void main(String... args) throws Exception { 18 | 19 | Executors.newScheduledThreadPool(1).scheduleAtFixedRate(() -> { 20 | //按一定速率去释放信号量 21 | semaphore.release(MAX_QPS / 2); 22 | }, 1000, 500, TimeUnit.MILLISECONDS); 23 | 24 | //lots of concurrent calls:100 * 1000 25 | ExecutorService pool = Executors.newFixedThreadPool(100); 26 | 27 | for (int i = 100; i > 0; i--) { 28 | 29 | final int x = i; 30 | 31 | pool.submit(() -> { 32 | for (int j = 1000; j > 0; j--) { 33 | semaphore.acquireUninterruptibly(1); 34 | remoteCall(x, j); 35 | } 36 | }); 37 | } 38 | 39 | pool.shutdown(); 40 | 41 | pool.awaitTermination(1, TimeUnit.HOURS); 42 | 43 | System.out.println("DONE"); 44 | } 45 | 46 | private static void remoteCall(int i, int j) { 47 | System.out.println(String.format("%s - %s: %d %d", new Date(), Thread.currentThread(), i, j)); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/DeadLock.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | /** 4 | * @author lichao 5 | * @date 2017/11/19 6 | */ 7 | public class DeadLock extends Thread { 8 | 9 | protected Object tool; 10 | static Object fork1 = new Object(); 11 | static Object fork2 = new Object(); 12 | 13 | public DeadLock(Object tool) { 14 | this.tool = tool; 15 | if (tool == fork1) { 16 | this.setName("哲学家A"); 17 | } 18 | if (tool == fork2) { 19 | this.setName("哲学家B"); 20 | } 21 | } 22 | 23 | @Override 24 | public void run() { 25 | if (tool == fork1) { 26 | synchronized (fork1) { 27 | try { 28 | Thread.sleep(500); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | synchronized (fork2) { 33 | System.out.println("哲学家A开始吃饭了"); 34 | } 35 | } 36 | } 37 | 38 | if (tool == fork2) { 39 | synchronized (fork2) { 40 | try { 41 | Thread.sleep(500); 42 | } catch (InterruptedException e) { 43 | e.printStackTrace(); 44 | } 45 | } 46 | synchronized (fork1) { 47 | System.out.println("哲学家B开始吃饭了"); 48 | } 49 | } 50 | } 51 | 52 | public static void main(String[] args) throws InterruptedException { 53 | DeadLock peopleA = new DeadLock(DeadLock.fork1); 54 | DeadLock peopleB = new DeadLock(DeadLock.fork2); 55 | peopleA.start(); 56 | peopleB.start(); 57 | Thread.sleep(1000); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/EnemyShip.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | /** 4 | * Created by lichao on 16/7/16. 5 | */ 6 | public abstract class EnemyShip { 7 | 8 | private String name; 9 | private double amtDamage; 10 | 11 | public String getName() { 12 | return name; 13 | } 14 | 15 | public void setName(String name) { 16 | this.name = name; 17 | } 18 | 19 | public double getAmtDamage() { 20 | return amtDamage; 21 | } 22 | 23 | public void setAmtDamage(double amtDamage) { 24 | this.amtDamage = amtDamage; 25 | } 26 | 27 | public void followHeroShip(){ 28 | System.out.println(getName()+"is following the hero"); 29 | } 30 | 31 | public void displayEnemyShip(){ 32 | System.out.println(getName()+" is on the screen"); 33 | } 34 | 35 | public void enemyShipShoots() { 36 | 37 | System.out.println(getName() + " attacks and does " + getAmtDamage() + " damage to hero"); 38 | 39 | } 40 | 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/ForkJoinTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.ArrayList; 4 | import java.util.concurrent.RecursiveTask; 5 | 6 | /** 7 | * Created by lichao on 2016/11/30. 8 | */ 9 | public class ForkJoinTest extends RecursiveTask { 10 | private static final int THRESHOLD = 10000; 11 | private long start; 12 | private long end; 13 | 14 | public ForkJoinTest(long start, long end) { 15 | this.start = start; 16 | this.end = end; 17 | } 18 | 19 | @Override 20 | protected Long compute() { 21 | long sum = 0; 22 | boolean canCompute = (end - start) < THRESHOLD; 23 | if (canCompute) { 24 | for (long i = start; i <= end; i++) { 25 | sum += i; 26 | } 27 | } else { 28 | //分成一百个小任务 29 | long step = (end - start) / 100; 30 | ArrayList subTasks = new ArrayList<>(); 31 | long pos = start; 32 | for (int i = 0; i < 100; i++) { 33 | long lastOne = pos + step; 34 | if (lastOne > end) { 35 | lastOne = end; 36 | } 37 | ForkJoinTest subTask = new ForkJoinTest(pos, lastOne); 38 | pos += step + 1; 39 | subTasks.add(subTask); 40 | subTask.fork(); 41 | } 42 | for (ForkJoinTest forkJoinTest : subTasks) { 43 | sum += forkJoinTest.join(); 44 | } 45 | } 46 | 47 | return sum; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/InterruptedTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | /** 4 | * Created by lichao on 2017/1/20. 5 | */ 6 | public class InterruptedTest extends Thread { 7 | 8 | volatile boolean stop = false;// 线程中断信号量 9 | 10 | public static void main(String args[]) throws Exception { 11 | InterruptedTest thread = new InterruptedTest(); 12 | System.out.println("Starting thread..."); 13 | thread.start(); 14 | Thread.sleep(3000); 15 | System.out.println("Asking thread to stop..."); 16 | // 设置中断信号量 17 | thread.stop = true; 18 | Thread.sleep(3000); 19 | System.out.println("Stopping application..."); 20 | } 21 | 22 | public void run() { 23 | // 每隔一秒检测一下中断信号量 24 | while (!stop) { 25 | System.out.println("Thread is running..."); 26 | long time = System.currentTimeMillis(); 27 | /* 28 | * 使用while循环模拟 sleep 方法,这里不要使用sleep,否则在阻塞时会 抛 29 | * InterruptedException异常而退出循环,这样while检测stop条件就不会执行, 30 | * 失去了意义。 31 | */ 32 | while ((System.currentTimeMillis() - time < 1000)) { 33 | } 34 | } 35 | System.out.println("Thread exiting under request..."); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/LockSupportDemo.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.concurrent.locks.LockSupport; 4 | 5 | /** 6 | * @author lichao 7 | * @date 2017/11/19 8 | */ 9 | public class LockSupportDemo { 10 | 11 | public static Object u = new Object(); 12 | static ChangeObjectThread t1 = new ChangeObjectThread("t1"); 13 | static ChangeObjectThread t2 = new ChangeObjectThread("t2"); 14 | 15 | public static class ChangeObjectThread extends Thread { 16 | 17 | ChangeObjectThread(String name) { 18 | super.setName(name); 19 | } 20 | 21 | @Override 22 | public void run() { 23 | synchronized (u) { 24 | System.out.println("in " + getName()); 25 | //通过信号量机制阻塞当前线程 26 | LockSupport.park(); 27 | } 28 | } 29 | } 30 | 31 | public static void main(String[] args) throws InterruptedException { 32 | t1.start(); 33 | Thread.sleep(100); 34 | t2.start(); 35 | LockSupport.unpark(t1); 36 | LockSupport.unpark(t2); 37 | t1.join(); 38 | t2.join(); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/Memoizer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import java.util.concurrent.Callable; 4 | import java.util.concurrent.CancellationException; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | import java.util.concurrent.ConcurrentMap; 7 | import java.util.concurrent.ExecutionException; 8 | import java.util.concurrent.Future; 9 | import java.util.concurrent.FutureTask; 10 | 11 | /** 12 | * 高效可伸缩结果缓存 13 | * 14 | * @author lichao 15 | * @date 2018/1/29 16 | */ 17 | public class Memoizer implements Computable { 18 | 19 | private final ConcurrentMap> cache 20 | = new ConcurrentHashMap>(); 21 | private final Computable c; 22 | 23 | public Memoizer(Computable c) { 24 | this.c = c; 25 | } 26 | 27 | @Override 28 | public V compute(final A arg) throws InterruptedException { 29 | while (true) { 30 | Future f = cache.get(arg); 31 | if (f == null) { 32 | Callable eval = () -> c.compute(arg); 33 | FutureTask ft = new FutureTask<>(eval); 34 | f = cache.putIfAbsent(arg, ft); 35 | //省去重复计算的过程 36 | if (f == null) { 37 | f = ft; 38 | ft.run(); 39 | } 40 | } 41 | try { 42 | return f.get(); 43 | } catch (CancellationException e) { 44 | cache.remove(arg, f); 45 | } catch (ExecutionException e) { 46 | throw new RuntimeException(e.getCause()); 47 | } 48 | } 49 | } 50 | } 51 | 52 | 53 | interface Computable { 54 | 55 | V compute(A arg) throws InterruptedException; 56 | } 57 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/SynchronousQueueTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import java.util.concurrent.SynchronousQueue; 5 | 6 | /** 7 | * @author lichao 8 | * @date 2017/11/28 9 | */ 10 | public class SynchronousQueueTest { 11 | 12 | /** 13 | * @param args 14 | */ 15 | public static void main(String[] args) throws Exception { 16 | SynchronousQueue queue = new SynchronousQueue(); 17 | for (int i = 0; i < 5; i++) { 18 | Thread t = new SQThread(queue, 1); 19 | t.start(); 20 | } 21 | //Thread.sleep(1000); 22 | for (int i = 0; i < 5; i++) { 23 | if (!queue.offer("test")) { 24 | System.out.println("Failure"); 25 | } 26 | } 27 | } 28 | 29 | public static class SQThread extends Thread { 30 | 31 | private SynchronousQueue queue; 32 | int mode; 33 | 34 | SQThread(SynchronousQueue queue, int mode) { 35 | this.queue = queue; 36 | this.mode = mode; 37 | } 38 | 39 | @Override 40 | public void run() { 41 | Object item = null; 42 | try { 43 | System.out.println(Thread.currentThread().getId()); 44 | if (mode == 1) { 45 | while ((item = queue.take()) != null) { 46 | System.out.println(JSON.toJSONString(item)); 47 | } 48 | } else { 49 | // 50 | } 51 | } catch (Exception e) { 52 | // 53 | } 54 | System.out.println("end"); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/ThreadJoin.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread; 2 | 3 | /** 4 | * @author lichao 5 | * @date 2017/11/2 6 | */ 7 | 8 | public class ThreadJoin { 9 | 10 | public static int a = 0; 11 | 12 | public static void main(String[] args) { 13 | Thread thread = new Thread(new Runnable() { 14 | @Override 15 | public void run() { 16 | for (int i = 0; i < 5; i++) { 17 | a++; 18 | } 19 | } 20 | }); 21 | thread.start(); 22 | try { 23 | thread.join(); 24 | } catch (InterruptedException e) { 25 | e.printStackTrace(); 26 | } 27 | System.out.println(a); 28 | 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/disruptor/Consumer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread.disruptor; 2 | 3 | import com.lmax.disruptor.WorkHandler; 4 | import java.util.concurrent.atomic.AtomicInteger; 5 | 6 | /** 7 | * @author lichao 8 | * @date 2019/03/31 9 | */ 10 | public class Consumer implements WorkHandler { 11 | 12 | private String consumerId; 13 | 14 | private static AtomicInteger count = new AtomicInteger(0); 15 | 16 | public Consumer(String consumerId) { 17 | this.consumerId = consumerId; 18 | } 19 | 20 | @Override 21 | public void onEvent(Order order) throws Exception { 22 | System.out.println("当前消费者: " + this.consumerId + ",消费信息:" + order.getId()); 23 | count.incrementAndGet(); 24 | } 25 | 26 | public int getCount() { 27 | return count.get(); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/disruptor/Order.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread.disruptor; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author lichao 7 | * @date 2019/03/31 8 | */ 9 | @Data 10 | public class Order { 11 | 12 | private String id;//ID 13 | private String name; 14 | private double price;//金额 15 | } 16 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/multithread/disruptor/Producer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.multithread.disruptor; 2 | 3 | import com.lmax.disruptor.EventTranslatorOneArg; 4 | import com.lmax.disruptor.RingBuffer; 5 | import lombok.Getter; 6 | 7 | /** 8 | * @author lichao 9 | * @date 2019/03/31 10 | */ 11 | public class Producer { 12 | @Getter 13 | private final String producerName; 14 | private final RingBuffer ringBuffer; 15 | 16 | public Producer(int producerId, RingBuffer ringBuffer) { 17 | this.producerName = String.format("producer-%d", producerId); 18 | this.ringBuffer = ringBuffer; 19 | } 20 | 21 | private final static EventTranslatorOneArg translator = (order, l, content) -> order 22 | .setId(content); 23 | 24 | /** 25 | * 解决多个producer线程问题并发生产的问题 26 | */ 27 | public void onData(String data) { 28 | ringBuffer.publishEvent(translator, data); 29 | } 30 | 31 | // /** 32 | // * onData用来发布事件,每调用一次就发布一次事件 它的参数会用过事件传递给消费者 33 | // * 34 | // * 过时的写法 35 | // */ 36 | // @Deprecated 37 | // public void onData(String data) { 38 | // //可以把ringBuffer看做一个事件队列,那么next就是得到下面一个事件槽 39 | // long sequence = ringBuffer.next(); 40 | // try { 41 | // //用上面的索引取出一个空的事件用于填充(获取该序号对应的事件对象) 42 | // Order order = ringBuffer.get(sequence); 43 | // //获取要通过事件传递的业务数据 44 | // order.setId(data); 45 | // System.out.println(producerName + String.format("produce order: %s", order)); 46 | // } finally { 47 | // //发布事件 48 | // //注意,最后的 ringBuffer.publish 方法必须包含在 finally 中以确保必须得到调用;如果某个请求的 sequence 未被提交,将会堵塞后续的发布操作或者其它的 producer。 49 | // ringBuffer.publish(sequence); 50 | // } 51 | // } 52 | } 53 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/CglibProxyFactory.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy; 2 | 3 | import org.springframework.cglib.proxy.Enhancer; 4 | import org.springframework.cglib.proxy.MethodInterceptor; 5 | import org.springframework.cglib.proxy.MethodProxy; 6 | 7 | import java.lang.reflect.Method; 8 | 9 | /** 10 | * Created by lichao on 16/8/5. 11 | */ 12 | public class CglibProxyFactory implements MethodInterceptor { 13 | 14 | private Object object; 15 | 16 | public Object createStudent(Object object) { 17 | this.object = object; 18 | Enhancer enhancer = new Enhancer(); 19 | enhancer.setSuperclass(object.getClass()); 20 | enhancer.setCallback(this); 21 | return enhancer.create(); 22 | } 23 | 24 | @Override 25 | public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) 26 | throws Throwable { 27 | System.out.println("this is Cglib"); 28 | return method.invoke(object, null); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/ProxyFactory.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | /** 8 | * Created by lichao on 16/8/5. 9 | */ 10 | public class ProxyFactory implements InvocationHandler { 11 | 12 | private Object student; 13 | 14 | public Object createStudentProxy(Object student) { 15 | this.student = student; 16 | return Proxy 17 | .newProxyInstance(student.getClass().getClassLoader(), student.getClass().getInterfaces(), 18 | this); 19 | 20 | 21 | } 22 | 23 | @Override 24 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 25 | System.out.println("this is proxy"); 26 | return method.invoke(student, null); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/Test.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy; 2 | 3 | import java.lang.reflect.Proxy; 4 | 5 | /** 6 | * Created by lichao on 16/8/5. 7 | */ 8 | public class Test { 9 | 10 | public static void main(String[] args) { 11 | student student = new studentImpl("lichao"); 12 | // CglibProxyFactory proxyFactory = new CglibProxyFactory(); 13 | // student s2 = (student) proxyFactory.createStudent(student); 14 | // s2.print(); 15 | // s2.yell(); 16 | // ProxyFactory proxyFactory = new ProxyFactory(); 17 | // student s2 = (student) proxyFactory.createStudentProxy(student); 18 | // s2.print(); 19 | // s2.yell(); 20 | Object proxyObject = Proxy.newProxyInstance(student.getClass().getClassLoader(), 21 | student.getClass().getInterfaces(), (proxy, method, params) -> { 22 | System.out.println("this is proxy print"); 23 | return method.invoke(student, null); 24 | }); 25 | 26 | ((student) proxyObject).yell(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/principle/MyInvocationHandler.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy.principle; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | /** 8 | * Created by lichao on 16/8/29. 9 | */ 10 | public class MyInvocationHandler implements InvocationHandler { 11 | // 目标对象 12 | private Object target; 13 | 14 | /** 15 | * 构造方法 16 | * 17 | * @param target 目标对象 18 | */ 19 | public MyInvocationHandler(Object target) { 20 | super(); 21 | this.target = target; 22 | } 23 | 24 | 25 | @Override 26 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 27 | // 在目标对象的方法执行之前简单的打印一下 28 | System.out.println("------------------before------------------"); 29 | 30 | // 执行目标对象的方法 31 | Object result = method.invoke(target, args); 32 | 33 | // 在目标对象的方法执行之后简单的打印一下 34 | System.out.println("-------------------after------------------"); 35 | 36 | return result; 37 | } 38 | 39 | public Object getProxy() { 40 | return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), 41 | target.getClass().getInterfaces(), this); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/principle/Test.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy.principle; 2 | 3 | /** 4 | * Created by lichao on 16/8/29. 5 | */ 6 | public class Test { 7 | // public static void main(String[] args){ 8 | // // 实例化目标对象 9 | // UserService userService = new UserServiceImpl(); 10 | // 11 | // // 实例化InvocationHandler 12 | // MyInvocationHandler invocationHandler = new MyInvocationHandler(userService); 13 | // 14 | // // 根据目标对象生成代理对象 15 | // UserService proxy = (UserService) invocationHandler.getProxy(); 16 | // 17 | // // 调用代理对象的方法 18 | // proxy.add(); 19 | // } 20 | } 21 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/principle/UserService.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy.principle; 2 | 3 | /** 4 | * Created by lichao on 16/8/29. 5 | */ 6 | public interface UserService { 7 | /** 8 | * 目标方法 9 | */ 10 | public abstract void add(); 11 | } 12 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/principle/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy.principle; 2 | 3 | 4 | /* 5 | * Created by lichao on 16/8/29. 6 | */ 7 | public class UserServiceImpl implements UserService { 8 | @Override 9 | public void add() { 10 | System.out.println("--------------------add---------------"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/student.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy; 2 | 3 | /** 4 | * Created by lichao on 16/8/5. 5 | */ 6 | public interface student { 7 | void print(); 8 | 9 | void yell(); 10 | } 11 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/proxy/studentImpl.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.proxy; 2 | 3 | /** 4 | * Created by lichao on 16/8/5. 5 | */ 6 | public class studentImpl implements student { 7 | private String name; 8 | 9 | public studentImpl() { 10 | 11 | } 12 | 13 | public studentImpl(String name) { 14 | this.name = name; 15 | } 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public void setName(String name) { 22 | this.name = name; 23 | } 24 | 25 | @Override 26 | public void print() { 27 | System.out.println("Hello world" + name); 28 | } 29 | 30 | @Override 31 | public void yell() { 32 | System.out.println("yell"); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/thrift/Add: -------------------------------------------------------------------------------- 1 | namespace java com.example.basic.thrift //defines the namespace 2 | 3 | typedef i32 int //get convinent names for types 4 | 5 | service AdditionService{ 6 | int add(1:int n1,2:int n2); 7 | } -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/thrift/AddtionServiceHandler.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.thrift; 2 | 3 | import org.apache.thrift.TException; 4 | 5 | /** 6 | * Created by lichao on 16/8/25. 7 | */ 8 | public class AddtionServiceHandler implements AdditionService.Iface { 9 | @Override 10 | public int add(int n1, int n2) throws TException { 11 | return n1 + n2; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/thrift/test/AdditionClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.thrift.test; 2 | 3 | import com.jacobs.basic.thrift.AdditionService; 4 | 5 | import org.apache.thrift.protocol.TBinaryProtocol; 6 | import org.apache.thrift.protocol.TProtocol; 7 | import org.apache.thrift.transport.TSocket; 8 | import org.apache.thrift.transport.TTransport; 9 | 10 | /** 11 | * Created by lichao on 16/8/25. 12 | */ 13 | public class AdditionClient { 14 | public static void main(String[] args) { 15 | try { 16 | TTransport tTransport; 17 | tTransport = new TSocket("localhost", 9090); 18 | tTransport.open(); 19 | 20 | TProtocol protocol = new TBinaryProtocol(tTransport); 21 | AdditionService.Client client = new AdditionService.Client(protocol); 22 | System.out.println(client.add(3, 5)); 23 | } catch (Exception e) { 24 | e.printStackTrace(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/thrift/test/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.thrift.test; 2 | 3 | import com.jacobs.basic.thrift.AdditionService; 4 | import com.jacobs.basic.thrift.AddtionServiceHandler; 5 | 6 | import org.apache.thrift.server.TServer; 7 | import org.apache.thrift.server.TSimpleServer; 8 | import org.apache.thrift.transport.TServerSocket; 9 | import org.apache.thrift.transport.TServerTransport; 10 | 11 | /** 12 | * Created by lichao on 16/8/25. 13 | */ 14 | public class MyServer { 15 | public static void StartsimplServer(AdditionService.Processor processor) { 16 | try { 17 | TServerTransport serverTransport = new TServerSocket(9090); 18 | TServer tServer = new TSimpleServer(new TServer.Args(serverTransport).processor(processor)); 19 | System.out.println("Starting the simple server...."); 20 | tServer.serve(); 21 | } catch (Exception e) { 22 | e.printStackTrace(); 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | StartsimplServer( 28 | new AdditionService.Processor<>(new AddtionServiceHandler())); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/zookeeper/ZookeeperCreateNode.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.zookeeper; 2 | 3 | import org.apache.zookeeper.AsyncCallback; 4 | import org.apache.zookeeper.CreateMode; 5 | import org.apache.zookeeper.WatchedEvent; 6 | import org.apache.zookeeper.Watcher; 7 | import org.apache.zookeeper.ZooDefs; 8 | import org.apache.zookeeper.ZooKeeper; 9 | 10 | import java.util.concurrent.CountDownLatch; 11 | 12 | /** 13 | * Created by lichao on 16/8/25. 14 | */ 15 | public class ZookeeperCreateNode implements Watcher { 16 | private static CountDownLatch connectedSemaphore = new CountDownLatch(1); 17 | 18 | public static void main(String[] args) throws Exception { 19 | ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new ZookeeperCreateNode()); 20 | connectedSemaphore.await(); 21 | zooKeeper.create("/zk-test-zookeeper-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, 22 | CreateMode.EPHEMERAL_SEQUENTIAL, new IStringCallback(), "I am context."); 23 | 24 | zooKeeper.create("/zk-test-zookeeper-", "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, 25 | CreateMode.EPHEMERAL, new IStringCallback(), "I am context."); 26 | 27 | Thread.sleep(Integer.MAX_VALUE); 28 | } 29 | 30 | @Override 31 | public void process(WatchedEvent event) { 32 | if (Event.KeeperState.SyncConnected == event.getState()) { 33 | connectedSemaphore.countDown(); 34 | } 35 | } 36 | } 37 | 38 | class IStringCallback implements AsyncCallback.StringCallback { 39 | 40 | @Override 41 | public void processResult(int rc, String path, Object ctx, String name) { 42 | System.out.println( 43 | "Create path result:[" + rc + ", " + path + ", " + ctx + ", real path name: " + name); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/zookeeper/ZookeeperTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.zookeeper; 2 | 3 | import org.apache.zookeeper.WatchedEvent; 4 | import org.apache.zookeeper.Watcher; 5 | import org.apache.zookeeper.ZooKeeper; 6 | 7 | import java.io.IOException; 8 | import java.util.concurrent.CountDownLatch; 9 | 10 | /** 11 | * Created by lichao on 16/8/24. 12 | */ 13 | public class ZookeeperTest implements Watcher { 14 | 15 | private static CountDownLatch connectedSemaphore = new CountDownLatch(1); 16 | 17 | public static void main(String[] args) { 18 | try { 19 | ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new ZookeeperTest()); 20 | System.out.println(zooKeeper.getState()); 21 | try { 22 | connectedSemaphore.await(); 23 | } catch (InterruptedException e) { 24 | } 25 | System.out.println("Zookeeper session established"); 26 | } catch (IOException e) { 27 | e.printStackTrace(); 28 | } 29 | } 30 | 31 | @Override 32 | public void process(WatchedEvent event) { 33 | System.out.println("Receive watched event: " + event); 34 | if (Event.KeeperState.SyncConnected == event.getState()) { 35 | connectedSemaphore.countDown(); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/zookeeper/curator/DistributeCounter.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.zookeeper.curator; 2 | 3 | import org.apache.curator.framework.CuratorFramework; 4 | import org.apache.curator.framework.recipes.atomic.AtomicValue; 5 | import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger; 6 | import org.apache.curator.retry.RetryNTimes; 7 | 8 | /** 9 | * @author lichao 10 | * @date 2019/03/26 11 | */ 12 | public class DistributeCounter { 13 | 14 | public static void main(String[] args) throws Exception { 15 | CuratorFramework cf = CuratorBase.getInstance(); 16 | //3 开启连接 17 | cf.start(); 18 | //cf.delete().forPath("/super"); 19 | //4 使用DistributedAtomicInteger 20 | DistributedAtomicInteger atomicIntger = new DistributedAtomicInteger(cf, "/super", new RetryNTimes(3, 1000)); 21 | AtomicValue value = atomicIntger.add(1); 22 | System.out.println(value.succeeded()); 23 | System.out.println(value.postValue()); //最新值 24 | System.out.println(value.preValue()); //原始值 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/zookeeper/zkclient/TestMainClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.zookeeper.zkclient; 2 | 3 | import org.apache.zookeeper.WatchedEvent; 4 | import org.apache.zookeeper.Watcher; 5 | import org.apache.zookeeper.ZooKeeper; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * Created by lichao on 16/8/26. 11 | */ 12 | public class TestMainClient implements Watcher { 13 | 14 | protected static ZooKeeper zooKeeper = null; 15 | protected static Integer mutex; 16 | int sessionTimeout = 10000; 17 | protected String root; 18 | 19 | public TestMainClient(String connectString) { 20 | if (zooKeeper == null) { 21 | try { 22 | System.out.println("启动zookeeper"); 23 | zooKeeper = new ZooKeeper(connectString, sessionTimeout, this); 24 | 25 | mutex = new Integer(-1); 26 | } catch (IOException e) { 27 | zooKeeper = null; 28 | } 29 | } 30 | } 31 | 32 | synchronized public void process(WatchedEvent event) { 33 | synchronized (mutex) { 34 | mutex.notify(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /basic-learning/src/main/java/com/jacobs/basic/zookeeper/zkclient/TestMainServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.basic.zookeeper.zkclient; 2 | 3 | import org.apache.zookeeper.server.ZooKeeperServerMain; 4 | 5 | import java.io.IOException; 6 | 7 | /** 8 | * Created by lichao on 16/8/30. 9 | */ 10 | public class TestMainServer extends ZooKeeperServerMain { 11 | 12 | public static final int CLIENT_PORT = 2181; 13 | 14 | public static class MainThread extends Thread { 15 | 16 | //final File confFile; 17 | final TestMainServer main; 18 | 19 | public MainThread(int clientPort) throws IOException { 20 | super("Standalone server with clientPort:" + clientPort); 21 | //confFile = new File(tmpDir, "zoo.cfg"); 22 | main = new TestMainServer(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/Application.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.scheduling.annotation.EnableAsync; 7 | 8 | @SpringBootApplication 9 | @EnableAsync 10 | //@EnableEurekaClient 11 | //@EnableJerseyConfiguration(scanPackage = "", applicationPath = "v1") 12 | //@AutoGenerateRowMapper(scanPackage = "com.example.module", annotationFilter = RowMapper.class, outPath = "core/src/main/java/") 13 | public class Application { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(Application.class, args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/AutoGenerateRowMapper.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.annotation.Documented; 5 | import java.lang.annotation.ElementType; 6 | import java.lang.annotation.Inherited; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | /** 12 | * Created by lichao on 2017/7/30. 13 | */ 14 | @Target(ElementType.TYPE) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Documented 17 | @Inherited 18 | public @interface AutoGenerateRowMapper { 19 | 20 | String scanPackage(); 21 | 22 | Class annotationFilter(); 23 | 24 | String outPath(); 25 | } 26 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/Log.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by lichao on 16/7/31. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface Log { 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/LogAspect.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import org.aspectj.lang.ProceedingJoinPoint; 4 | import org.aspectj.lang.annotation.Around; 5 | import org.aspectj.lang.annotation.Aspect; 6 | import org.aspectj.lang.annotation.Before; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.PropertySource; 9 | import org.springframework.stereotype.Component; 10 | 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | /** 14 | * Created by lichao on 16/8/1. 15 | */ 16 | @Slf4j 17 | @Aspect 18 | @Component 19 | @PropertySource(value = "classpath:configs.properties") 20 | public class LogAspect { 21 | 22 | @Value("${test.name}") 23 | private String testConfig; 24 | 25 | 26 | @Around("@annotation(com.jacobs.aspects.Log)") 27 | public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 28 | System.out.println("this is the method before" + testConfig); 29 | proceedingJoinPoint.proceed(); 30 | System.out.println("this is the method after" + testConfig); 31 | } 32 | 33 | @Around("execution(* com.jacobs.aspects.LogMethod.sayHello())") 34 | public void sayHello(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 35 | System.out.println("Hello"); 36 | proceedingJoinPoint.proceed(); 37 | System.out.println("World"); 38 | } 39 | 40 | @Before("@annotation(com.jacobs.aspects.LogBefore)") 41 | public void executeBefore() { 42 | System.out.println("print before method"); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/LogBefore.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by lichao on 2017/4/5. 10 | */ 11 | @Target(ElementType.METHOD) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface LogBefore { 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/LogMethod.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import org.springframework.stereotype.Component; 4 | 5 | /** 6 | * Created by lichao on 16/8/5. 7 | */ 8 | @Component 9 | public class LogMethod { 10 | @LogBefore 11 | public void sayHello(){ 12 | System.out.println("this is my Log"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/MapperProcessorAnnotation.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by lichao on 2017/8/8. 10 | */ 11 | @Retention(RetentionPolicy.CLASS) 12 | @Target(ElementType.TYPE) 13 | public @interface MapperProcessorAnnotation { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/aspects/RowMapper.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.aspects; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | /** 9 | * Created by lichao on 2017/7/30. 10 | */ 11 | @Target(ElementType.TYPE) 12 | @Retention(RetentionPolicy.RUNTIME) 13 | public @interface RowMapper { 14 | 15 | } 16 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/conditional/ConditionalOnMyProperties.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.conditional; 2 | 3 | import org.springframework.context.annotation.Conditional; 4 | 5 | import java.lang.annotation.Documented; 6 | import java.lang.annotation.ElementType; 7 | import java.lang.annotation.Retention; 8 | import java.lang.annotation.RetentionPolicy; 9 | import java.lang.annotation.Target; 10 | 11 | /** 12 | * Created by lichao on 2017/1/6. 13 | */ 14 | @Target({ElementType.TYPE, ElementType.METHOD}) 15 | @Retention(RetentionPolicy.RUNTIME) 16 | @Documented 17 | @Conditional(OnMyPropertiesCondition.class) 18 | public @interface ConditionalOnMyProperties { 19 | String name(); 20 | } 21 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/conditional/ElasticServiceCondition.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.conditional; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.apache.commons.lang.StringUtils; 5 | import org.springframework.boot.autoconfigure.condition.ConditionOutcome; 6 | import org.springframework.boot.autoconfigure.condition.SpringBootCondition; 7 | import org.springframework.context.annotation.ConditionContext; 8 | import org.springframework.core.type.AnnotatedTypeMetadata; 9 | 10 | /** 11 | * Created by lichao on 2017/4/19. 12 | */ 13 | @Slf4j 14 | public class ElasticServiceCondition extends SpringBootCondition { 15 | 16 | @Override 17 | public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, 18 | AnnotatedTypeMetadata annotatedTypeMetadata) { 19 | String properties = conditionContext.getEnvironment().getProperty("elasticsearch.clusterName"); 20 | log.info("elasticsearch property: {}", properties); 21 | return new ConditionOutcome(StringUtils.isNotBlank(properties), "elasticsearch property"); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/conditional/OnMyPropertiesCondition.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.conditional; 2 | 3 | import org.springframework.boot.autoconfigure.condition.ConditionOutcome; 4 | import org.springframework.boot.autoconfigure.condition.SpringBootCondition; 5 | import org.springframework.context.annotation.ConditionContext; 6 | import org.springframework.core.type.AnnotatedTypeMetadata; 7 | 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | /** 11 | * Created by lichao on 2017/1/6. 12 | */ 13 | @Slf4j 14 | public class OnMyPropertiesCondition extends SpringBootCondition { 15 | @Override 16 | public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, 17 | AnnotatedTypeMetadata annotatedTypeMetadata) { 18 | Object propertiesName = annotatedTypeMetadata.getAnnotationAttributes( 19 | ConditionalOnMyProperties.class.getName()) 20 | .get("name"); 21 | if (propertiesName != null) { 22 | log.info("OnMyPropertiesCondition matched"); 23 | String value = conditionContext.getEnvironment() 24 | .getProperty(propertiesName.toString()); 25 | if (value != null) { 26 | return new ConditionOutcome(true, "get properties"); 27 | } 28 | } 29 | return new ConditionOutcome(false, "none get properties"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/constants/BaseConstant.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.constants; 2 | 3 | /** 4 | * Created by lichao on 2017/3/16. 5 | */ 6 | public class BaseConstant { 7 | 8 | public static final String PROJECT_NAME = "java_learning_practice"; 9 | public static final String REDIS_NAME = "common"; 10 | public static final int BASE_HTTP_ERROR_CODE = 500; 11 | } 12 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/exception/CommonException.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.exception; 2 | 3 | /** 4 | * Created by lichao on 2017/4/11. 5 | */ 6 | public enum CommonException implements ExFactor { 7 | PARAMETER_ERROR(1, "params error"); 8 | 9 | private int errorCode; 10 | private String detail; 11 | 12 | CommonException(int errorCode, String detail) { 13 | this.errorCode = errorCode; 14 | this.detail = detail; 15 | } 16 | 17 | @Override 18 | public CommonRestException.CommonExceptionModel getExModel() { 19 | return CommonRestException.CommonExceptionModel.builder() 20 | .detailMsg(detail) 21 | .errCode(errorCode) 22 | .requestUri("") 23 | .errorMsg("") 24 | .build(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/exception/CommonRestException.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.exception; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | import javax.ws.rs.WebApplicationException; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.Getter; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * Created by lichao on 2017/4/12. 13 | */ 14 | @NoArgsConstructor 15 | public class CommonRestException extends WebApplicationException { 16 | 17 | @Getter 18 | private ExFactor exFactor; 19 | 20 | public CommonRestException(ExFactor exFactor) { 21 | this.exFactor = exFactor; 22 | } 23 | 24 | @Data 25 | @NoArgsConstructor 26 | @AllArgsConstructor 27 | @Builder 28 | public static class CommonExceptionModel { 29 | 30 | @JSONField( 31 | name = "http_code" 32 | ) 33 | int httpCode; 34 | @JSONField( 35 | name = "error_code" 36 | ) 37 | int errCode; 38 | @JSONField( 39 | name = "error_msg" 40 | ) 41 | String errorMsg; 42 | @JSONField( 43 | name = "display_msg" 44 | ) 45 | String detailMsg; 46 | @JSONField( 47 | name = "request_uri" 48 | ) 49 | String requestUri; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/exception/CommonResult.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.exception; 2 | 3 | import com.google.common.collect.Maps; 4 | import java.io.Serializable; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * Created by lichao on 2017/4/12. 10 | */ 11 | public class CommonResult implements Serializable { 12 | 13 | private Object result = ""; 14 | 15 | public Object getResult() { 16 | return this.result; 17 | } 18 | 19 | public void setResult(Object result) { 20 | this.result = result; 21 | } 22 | 23 | public CommonResult(Object result) { 24 | this.result = result; 25 | } 26 | 27 | public CommonResult() { 28 | } 29 | 30 | public static CommonResult booleanCommonResult(boolean result) { 31 | HashMap map = Maps.newHashMap(); 32 | map.put("is_success", Boolean.valueOf(result)); 33 | return new CommonResult(map); 34 | } 35 | 36 | public static CommonResult oneCommonResult(String key, Object result) { 37 | HashMap map = Maps.newHashMap(); 38 | map.put(key, result); 39 | return new CommonResult(map); 40 | } 41 | 42 | public static CommonResult mapCommonResult(Map map) { 43 | return new CommonResult(map); 44 | } 45 | } 46 | 47 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/exception/ExFactor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.exception; 2 | 3 | /** 4 | * Created by lichao on 2017/4/12. 5 | */ 6 | public interface ExFactor { 7 | 8 | CommonRestException.CommonExceptionModel getExModel(); 9 | } 10 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/exception/HBaseSystemException.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.exception; 2 | 3 | /** 4 | * Created by lichao on 2017/3/10. 5 | */ 6 | public class HBaseSystemException extends RuntimeException { 7 | 8 | /** 9 | * Constructor for UncategorizedDataAccessException. 10 | * 11 | * @param msg the detail message 12 | * @param cause the exception thrown by underlying data access API 13 | */ 14 | public HBaseSystemException(String msg, Throwable cause) { 15 | super(msg, cause); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/filters/PoweredByResponseFilter.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.filters; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.ws.rs.container.ContainerRequestContext; 6 | import javax.ws.rs.container.ContainerResponseContext; 7 | import javax.ws.rs.container.ContainerResponseFilter; 8 | 9 | /** 10 | * Created by lichao on 2016/12/16. 11 | */ 12 | public class PoweredByResponseFilter implements ContainerResponseFilter { 13 | @Override 14 | public void filter(ContainerRequestContext requestContext, 15 | ContainerResponseContext responseContext) throws IOException { 16 | // responseContext.getHeaders() 17 | // .add("X-Powered-By", "Jersey :-)"); 18 | // responseContext.setEntity(responseContext.getEntity() + "this is body"); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/AdminConfig.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | import lombok.Data; 6 | 7 | /** 8 | * Created by lichao on 2017/3/10. 9 | */ 10 | @ConfigurationProperties(prefix = "hbase.admin") 11 | @Data 12 | public class AdminConfig { 13 | private long maxFileSize = 536870912L; 14 | private boolean readOnly = false; 15 | private long memStoreFlushSize = 134217728L; 16 | private int regionReplication = 1; 17 | private boolean normalizationEnabled = false; 18 | } 19 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/HBaseOperations.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase; 2 | 3 | import com.jacobs.hbase.callback.MutatorCallback; 4 | import com.jacobs.hbase.callback.TableCallback; 5 | import com.jacobs.hbase.results.ResultsExtractor; 6 | import com.jacobs.hbase.results.RowMapper; 7 | 8 | import org.apache.hadoop.hbase.client.Scan; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * Created by lichao on 2017/3/10. 14 | */ 15 | public interface HBaseOperations { 16 | T execute(String var1, TableCallback var2); 17 | 18 | T executeBatch(String var1, MutatorCallback var2); 19 | 20 | T find(String var1, String var2, ResultsExtractor var3); 21 | 22 | T find(String var1, String var2, String var3, ResultsExtractor var4); 23 | 24 | T find(String var1, Scan var2, ResultsExtractor var3); 25 | 26 | List find(String var1, String var2, RowMapper var3); 27 | 28 | List find(String var1, String var2, String var3, RowMapper var4); 29 | 30 | List find(String var1, Scan var2, RowMapper var3); 31 | 32 | T get(String var1, String var2, RowMapper var3); 33 | 34 | T get(String var1, String var2, String var3, RowMapper var4); 35 | 36 | T get(String var1, String var2, String var3, String var4, RowMapper var5); 37 | 38 | void put(String var1, String var2, String var3, String var4, byte[] var5); 39 | 40 | void delete(String var1, String var2, String var3); 41 | 42 | void delete(String var1, String var2, String var3, String var4); 43 | 44 | void createTable(AdminConfig var1, String var2, String... var3); 45 | } 46 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/ZookeeperConfig.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | import lombok.Data; 6 | 7 | /** 8 | * Created by lichao on 2017/3/10. 9 | */ 10 | @Data 11 | @ConfigurationProperties(prefix = "hbase") 12 | public class ZookeeperConfig { 13 | private String quorum; 14 | private Integer port; 15 | private Integer maxSize = Integer.valueOf(10); 16 | } 17 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/callback/MutatorCallback.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.callback; 2 | 3 | import org.apache.hadoop.hbase.client.BufferedMutator; 4 | 5 | /** 6 | * Created by lichao on 2017/3/10. 7 | */ 8 | public interface MutatorCallback { 9 | T doInMutator(BufferedMutator var1) throws Throwable; 10 | } 11 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/callback/TableCallback.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.callback; 2 | 3 | import org.apache.hadoop.hbase.client.Table; 4 | 5 | /** 6 | * Created by lichao on 2017/3/10. 7 | */ 8 | public interface TableCallback { 9 | T doInTable(Table table) throws Throwable; 10 | } 11 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/factory/TableFactory.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.factory; 2 | 3 | import org.apache.hadoop.hbase.client.Admin; 4 | import org.apache.hadoop.hbase.client.BufferedMutator; 5 | import org.apache.hadoop.hbase.client.Table; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * Created by lichao on 2017/3/10. 11 | */ 12 | public interface TableFactory { 13 | Table createTable(byte[] var1) throws IOException; 14 | 15 | void releaseTable(Table var1) throws IOException; 16 | 17 | Admin createAdmin() throws IOException; 18 | 19 | void releaseAdmin(Admin var1) throws IOException; 20 | 21 | BufferedMutator createBufferedMutator(byte[] var1) throws IOException; 22 | 23 | void releaseBufferedMutator(BufferedMutator var1) throws IOException; 24 | } 25 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/results/PutExtension.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.results; 2 | 3 | import org.apache.hadoop.hbase.client.Put; 4 | import org.apache.hadoop.hbase.util.Bytes; 5 | 6 | import java.io.IOException; 7 | 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | /** 11 | * Created by lichao on 16/9/18. 12 | */ 13 | @Slf4j 14 | public class PutExtension extends Put { 15 | 16 | String columnFamilyName = "i"; 17 | 18 | public PutExtension(String columnFamilyName, byte[] row) { 19 | super(row); 20 | this.columnFamilyName = columnFamilyName; 21 | } 22 | 23 | public PutExtension build(String paramName, Object param) throws IOException { 24 | if (param != null) { 25 | this.addColumn(columnFamilyName.getBytes(), paramName.getBytes(), 26 | Bytes.toBytes(param.toString())); 27 | } 28 | return this; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/results/ResultsExtractor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.results; 2 | 3 | import org.apache.hadoop.hbase.client.ResultScanner; 4 | 5 | /** 6 | * Created by lichao on 2017/3/10. 7 | */ 8 | public interface ResultsExtractor { 9 | T extractData(ResultScanner var1) throws Exception; 10 | } 11 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/results/RowMapper.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.results; 2 | 3 | import org.apache.hadoop.hbase.client.Result; 4 | 5 | /** 6 | * Created by lichao on 2017/3/10. 7 | */ 8 | public interface RowMapper { 9 | T mapRow(Result var1, int var2) throws Exception; 10 | } 11 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hbase/results/RowMapperResultsExtractor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hbase.results; 2 | 3 | import org.apache.hadoop.hbase.client.Result; 4 | import org.apache.hadoop.hbase.client.ResultScanner; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Iterator; 8 | import java.util.List; 9 | 10 | /** 11 | * Created by lichao on 2017/3/10. 12 | */ 13 | public class RowMapperResultsExtractor implements ResultsExtractor> { 14 | 15 | private final RowMapper rowMapper; 16 | 17 | public RowMapperResultsExtractor(RowMapper rowMapper) { 18 | this.rowMapper = rowMapper; 19 | } 20 | 21 | @Override 22 | public List extractData(ResultScanner results) throws Exception { 23 | ArrayList rs = new ArrayList(); 24 | int rowNum = 0; 25 | Iterator iterator = results.iterator(); 26 | 27 | while (iterator.hasNext()) { 28 | Result result = (Result) iterator.next(); 29 | rs.add(this.rowMapper.mapRow(result, rowNum++)); 30 | } 31 | 32 | return rs; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/hive/HiveJdbcTemplate.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.hive; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.springframework.jdbc.core.JdbcTemplate; 6 | 7 | /** 8 | * @author lichao 9 | * Created on 2019-06-20 10 | */ 11 | public class HiveJdbcTemplate extends JdbcTemplate { 12 | 13 | public HiveJdbcTemplate(DataSource dataSource) { 14 | super(dataSource); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/CommonExceptionFactor.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey; 2 | 3 | import com.jacobs.exception.CommonRestException.CommonExceptionModel; 4 | import com.jacobs.exception.ExFactor; 5 | 6 | /** 7 | * Created by lichao on 2017/4/19. 8 | */ 9 | public enum CommonExceptionFactor implements ExFactor { 10 | PARAM_ERROR(400, 4000001, "Parameter error!", ""), 11 | PARAM_MISSING(400, 4000002, "Parameter missing!", ""), 12 | URL_NOT_FOUND(404, 4040000, "Url not found!", ""), 13 | HTTP_METHOD_NOT_ALLOWED(405, 4050001, "Http method not allow!", ""), 14 | INTERNAL_ERROR(500, 5000001, "Service internal error!", ""), 15 | IS_NOT_INTERNAL_IP(403, 4030006, "is not internal ip!", ""), 16 | ACCESS_TOKEN_AUTH_FAILD(403, 4030004, "access_token is wrong!", ""), 17 | ACCESS_TOKEN_IS_EXPIRE(403, 4030003, "access_token is expire!", ""), 18 | USER_IS_BLOCKED(403, 4030005, "user is blocked!", ""), 19 | NO_ROLES(403, 4030007, "no roles!", ""), 20 | APP_NO_ROLES(403, 4030011, "app no roles", ""); 21 | 22 | int httpCode; 23 | int errCode; 24 | String errorMsg; 25 | String detailMsg; 26 | 27 | CommonExceptionFactor(int httpCode, int errCode, String errorMsg, String detailMsg) { 28 | this.httpCode = httpCode; 29 | this.errCode = errCode; 30 | this.errorMsg = errorMsg; 31 | this.detailMsg = detailMsg; 32 | } 33 | 34 | @Override 35 | public CommonExceptionModel getExModel() { 36 | CommonExceptionModel model = new CommonExceptionModel(); 37 | model.setHttpCode(this.httpCode); 38 | model.setErrCode(this.errCode); 39 | model.setErrorMsg(this.errorMsg); 40 | model.setDetailMsg(this.detailMsg); 41 | return model; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/EnableJerseyConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Inherited; 6 | import java.lang.annotation.Retention; 7 | import java.lang.annotation.RetentionPolicy; 8 | import java.lang.annotation.Target; 9 | 10 | /** 11 | * Created by lichao on 2017/4/19. 12 | */ 13 | @Target({ElementType.TYPE}) 14 | @Retention(RetentionPolicy.RUNTIME) 15 | @Documented 16 | @Inherited 17 | public @interface EnableJerseyConfiguration { 18 | 19 | String scanPackage(); 20 | 21 | String applicationPath(); 22 | } 23 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/JerseyConfig.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey; 2 | 3 | import com.jacobs.exception.CommonExceptionMapper; 4 | import com.jacobs.exception.CommonValidationMapper; 5 | import com.jacobs.filters.PoweredByResponseFilter; 6 | import com.jacobs.resource.TestResource; 7 | 8 | import org.glassfish.jersey.server.ResourceConfig; 9 | 10 | /** 11 | * Created by lichao on 16/8/21. 12 | */ 13 | public class JerseyConfig extends ResourceConfig { 14 | 15 | public JerseyConfig() { 16 | register(TestResource.class)//resource样例 17 | .register(PoweredByResponseFilter.class)//请求拦截样例 18 | //.register(AuthorizationRequestFilter.class)//权限验证 19 | .register(CommonValidationMapper.class) 20 | .register(CommonExceptionMapper.class);//参数错误处理 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/params/FloatRange.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey.params; 2 | 3 | import java.text.DecimalFormat; 4 | 5 | /** 6 | * Created by lichao on 2017/4/19. 7 | */ 8 | public class FloatRange implements ParamRange { 9 | 10 | float min = 1.4E-45F; 11 | float max = 3.4028235E38F; 12 | 13 | public FloatRange() { 14 | } 15 | 16 | public FloatRange(String range) { 17 | String[] arr = range.split("~"); 18 | this.min = Float.parseFloat(arr[0]); 19 | this.max = Float.parseFloat(arr[1]); 20 | if (this.max < this.min) { 21 | this.max = 3.4028235E38F; 22 | } 23 | 24 | } 25 | 26 | public FloatRange(float min, float max) { 27 | this.min = min; 28 | this.max = max; 29 | if (this.max < this.min) { 30 | this.max = 3.4028235E38F; 31 | } 32 | 33 | } 34 | 35 | public boolean isInRange(Float value) { 36 | float v = value.floatValue(); 37 | return v >= this.min && v <= this.max; 38 | } 39 | 40 | public String getEnumRangeDesc() { 41 | return ""; 42 | } 43 | 44 | public String getRegExpDesc() { 45 | return ""; 46 | } 47 | 48 | public String getBaseSample() { 49 | float d = this.getRandomValue(); 50 | DecimalFormat nf = new DecimalFormat("######.000"); 51 | return nf.format((double) d); 52 | } 53 | 54 | public float getRandomValue() { 55 | int i = rdm.nextInt(100); 56 | 57 | float d; 58 | for (d = this.min + (float) i; !this.isInRange(Float.valueOf(d)); d = this.min + (float) i) { 59 | i = rdm.nextInt(100); 60 | } 61 | 62 | return d; 63 | } 64 | 65 | public String getDesc() { 66 | return this.min + "~" + this.max; 67 | } 68 | 69 | public boolean isCompatible(Class type) { 70 | return type == Float.TYPE || type == Float.class; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/params/IntRange.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey.params; 2 | 3 | /** 4 | * Created by lichao on 2017/4/19. 5 | */ 6 | public class IntRange implements ParamRange { 7 | 8 | int min = -2147483648; 9 | int max = 2147483647; 10 | 11 | public IntRange() { 12 | } 13 | 14 | public IntRange(String range) { 15 | String[] arr = range.split("~"); 16 | this.min = Integer.parseInt(arr[0]); 17 | this.max = Integer.parseInt(arr[1]); 18 | if (this.max < this.min) { 19 | this.max = 2147483647; 20 | } 21 | 22 | } 23 | 24 | public IntRange(int min, int max) { 25 | this.min = min; 26 | this.max = max; 27 | if (this.max < this.min) { 28 | this.max = 2147483647; 29 | } 30 | 31 | } 32 | 33 | public boolean isInRange(Integer value) { 34 | int v = value.intValue(); 35 | return v >= this.min && v <= this.max; 36 | } 37 | 38 | public String getBaseSample() { 39 | int d = this.getRandomValue(); 40 | return d + ""; 41 | } 42 | 43 | public int getRandomValue() { 44 | int d; 45 | for (d = rdm.nextInt(this.max + 1); !this.isInRange(Integer.valueOf(d)); 46 | d = rdm.nextInt(this.max + 1)) { 47 | ; 48 | } 49 | 50 | return d; 51 | } 52 | 53 | public String getDesc() { 54 | return this.min + "~" + this.max; 55 | } 56 | 57 | public boolean isCompatible(Class type) { 58 | return type == Integer.TYPE || type == Integer.class; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/params/LongRange.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey.params; 2 | 3 | /** 4 | * Created by lichao on 2017/4/19. 5 | */ 6 | public class LongRange implements ParamRange { 7 | 8 | long min = -9223372036854775808L; 9 | long max = 9223372036854775807L; 10 | 11 | public LongRange() { 12 | } 13 | 14 | public LongRange(String range) { 15 | String[] arr = range.split("~"); 16 | this.min = Long.parseLong(arr[0]); 17 | this.max = Long.parseLong(arr[1]); 18 | if (this.max < this.min) { 19 | this.max = 9223372036854775807L; 20 | } 21 | 22 | } 23 | 24 | public LongRange(long min, long max) { 25 | this.min = min; 26 | this.max = max; 27 | if (this.max < this.min) { 28 | this.max = 2147483647L; 29 | } 30 | 31 | } 32 | 33 | public boolean isInRange(Long value) { 34 | long v = value.longValue(); 35 | return v >= this.min && v <= this.max; 36 | } 37 | 38 | public String getBaseSample() { 39 | long d = this.getRandomValue(); 40 | return String.valueOf(d); 41 | } 42 | 43 | public long getRandomValue() { 44 | int i = rdm.nextInt(100); 45 | 46 | long d; 47 | for (d = this.min + (long) i; !this.isInRange(Long.valueOf(d)); d = this.min + (long) i) { 48 | i = rdm.nextInt(100); 49 | } 50 | 51 | return d; 52 | } 53 | 54 | public String getDesc() { 55 | return this.min + "~" + this.max; 56 | } 57 | 58 | public boolean isCompatible(Class type) { 59 | return type == Long.TYPE || type == Long.class; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/params/ParamRange.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey.params; 2 | 3 | import java.util.Random; 4 | 5 | /** 6 | * Created by lichao on 2017/4/19. 7 | */ 8 | public interface ParamRange { 9 | 10 | Random rdm = new Random(); 11 | 12 | boolean isInRange(T var1); 13 | 14 | String getDesc(); 15 | 16 | String getBaseSample(); 17 | 18 | boolean isCompatible(Class var1); 19 | } 20 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/jersey/params/RangeFactory.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jersey.params; 2 | 3 | import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils; 4 | 5 | /** 6 | * Created by lichao on 2017/4/19. 7 | */ 8 | public class RangeFactory { 9 | 10 | private static String EMAIL_REGX = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 11 | public static final String MOBILE_REGX = "^(1(([35][0-9])|(47)|[8][0-9]))\\d{8}$"; 12 | 13 | public RangeFactory() { 14 | } 15 | 16 | public static ParamRange getRangeInstance(String range) { 17 | if (StringUtils.isBlank(range)) { 18 | return null; 19 | } else { 20 | String[] arr = range.split(":", 2); 21 | if (arr.length != 2) { 22 | throw new IllegalArgumentException("invalid range define:" + range); 23 | } else { 24 | Object result = null; 25 | if (arr[0].equals("int")) { 26 | result = new IntRange(arr[1].trim()); 27 | } else if (arr[0].equals("long")) { 28 | result = new LongRange(arr[1].trim()); 29 | } else if (arr[0].equals("float")) { 30 | result = new FloatRange(arr[1].trim()); 31 | } else if (arr[0].equals("double")) { 32 | result = new DoubleRange(arr[1].trim()); 33 | } 34 | 35 | return (ParamRange) result; 36 | } 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | String test = "spec:join_int[100~10000]"; 42 | ParamRange paramRange = getRangeInstance(test); 43 | System.out.println(paramRange); 44 | System.out.println(paramRange.isInRange("1000,1,2345")); 45 | System.out.println(paramRange.isInRange("1000,2001,2345")); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/lock/Watcher.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.lock; 2 | 3 | /** 4 | * @author lichao 5 | * @date 2019/03/28 6 | */ 7 | public interface Watcher { 8 | 9 | void onLock(String lockPath, String client); 10 | 11 | void onUnlock(String lockPath, String client); 12 | } 13 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/lock/ZkConfig.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.lock; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Data 8 | //@Component 9 | //@ConfigurationProperties(prefix = "curator") 10 | public class ZkConfig { 11 | 12 | private int retryCount; 13 | 14 | private int elapsedTimeMs; 15 | 16 | private String connectString; 17 | 18 | private int sessionTimeoutMs; 19 | 20 | private int connectionTimeoutMs; 21 | } 22 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/logger/LogggerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.logger; 2 | 3 | import org.springframework.context.ApplicationContextInitializer; 4 | import org.springframework.context.ConfigurableApplicationContext; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.core.Ordered; 7 | 8 | /** 9 | * Created by lichao on 2017/3/16. 10 | */ 11 | @Configuration 12 | public class LogggerInitializer 13 | implements ApplicationContextInitializer, Ordered { 14 | 15 | private int order = Ordered.HIGHEST_PRECEDENCE + 100; 16 | 17 | @Override 18 | public void initialize(ConfigurableApplicationContext configurableApplicationContext) { 19 | try { 20 | MyLogLayOut.PROJECT_NAME = configurableApplicationContext.getEnvironment() 21 | .getProperty("spring.application.name"); 22 | } catch (Exception ex) { 23 | 24 | } 25 | } 26 | 27 | @Override 28 | public int getOrder() { 29 | return order; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/Address.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import java.util.Arrays; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.NoArgsConstructor; 7 | 8 | /** 9 | * Created by lichao on 16/7/20. 10 | */ 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | @Builder 14 | public class Address { 15 | 16 | private Long id; 17 | private String province; 18 | private String city; 19 | 20 | public static T[] minmax(T... a) { 21 | 22 | Object[] mm = new Object[2]; 23 | mm[0] = a[0]; 24 | mm[1] = a[1]; 25 | 26 | return (T[]) mm; 27 | } 28 | 29 | public static void main(String[] args) { 30 | Arrays.stream(minmax(1, 2)).forEach(System.out::print); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/MongoUser.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * Created by lichao on 2017/4/18. 7 | */ 8 | @Data 9 | public class MongoUser { 10 | 11 | private String from; 12 | private String to; 13 | private long identify; 14 | private long timestamp; 15 | private int count; 16 | } 17 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/PageableResponse.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | import java.util.List; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * Created by lichao on 2017/9/23. 11 | */ 12 | @NoArgsConstructor 13 | @AllArgsConstructor 14 | @Builder 15 | public class PageableResponse { 16 | 17 | List results; 18 | @JSONField(name = "total_pages") 19 | long totalPages; 20 | @JSONField(name = "total_elements") 21 | long totalElements; 22 | } 23 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/TestCase.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import com.alibaba.fastjson.JSON; 4 | import com.jacobs.exception.CommonException; 5 | import com.jacobs.exception.CommonRestException; 6 | import com.jacobs.jersey.ParamDesc; 7 | import java.util.Map; 8 | import javax.ws.rs.FormParam; 9 | import lombok.AllArgsConstructor; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | import lombok.NoArgsConstructor; 13 | 14 | /** 15 | * Created by lichao on 2017/4/20. 16 | */ 17 | @Data 18 | @Builder 19 | @AllArgsConstructor 20 | @NoArgsConstructor 21 | public class TestCase { 22 | 23 | @FormParam("key") 24 | @ParamDesc(isRequired = true, 25 | desc = "test_case对应的key") 26 | String key; 27 | 28 | @FormParam("value") 29 | @ParamDesc(isRequired = true, 30 | desc = "对应的值") 31 | String value; 32 | 33 | @FormParam("description") 34 | @ParamDesc(isRequired = false, 35 | desc = "当前testCase的描述") 36 | String description; 37 | 38 | @FormParam("anonymous") 39 | @ParamDesc(isRequired = false, 40 | desc = "是否需要登陆") 41 | boolean anonymous; 42 | 43 | @ParamDesc(isRequired = false, 44 | desc = "需要满足的条件") 45 | Map conditions; 46 | 47 | @FormParam("conditions") 48 | public void generateConditions(String param) { 49 | try { 50 | Map conditions = JSON.parseObject(param.toString(), Map.class); 51 | this.conditions = conditions; 52 | } catch (Exception ex) { 53 | //直接抛给上层,由jersey或serviceExceptionHandler捕获 54 | throw new CommonRestException(CommonException.PARAMETER_ERROR); 55 | } 56 | } 57 | } 58 | 59 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/User.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import com.alibaba.fastjson.annotation.JSONField; 4 | 5 | import org.springframework.beans.BeanUtils; 6 | 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | /** 11 | * Created by lichao on 16/7/20. 12 | */ 13 | @Data 14 | @NoArgsConstructor 15 | public class User { 16 | private Long id; 17 | @JSONField(name = "age") 18 | private int age; 19 | @JSONField(name = "user_name") 20 | private String userName; 21 | private String firstName; 22 | private String lastName; 23 | 24 | @Override 25 | public User clone() throws CloneNotSupportedException { 26 | User user = new User(); 27 | BeanUtils.copyProperties(this, user); 28 | return user; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/UserPropertyTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import com.jacobs.aspects.MapperProcessorAnnotation; 4 | import lombok.Data; 5 | 6 | /** 7 | * Created by lichao on 2017/4/7. 8 | */ 9 | @MapperProcessorAnnotation 10 | @Data 11 | public class UserPropertyTest { 12 | 13 | private String name; 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/WeixiaobaoUploadInfo.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module; 2 | 3 | import com.jacobs.aspects.MapperProcessorAnnotation; 4 | import lombok.Data; 5 | 6 | /** 7 | * Created by lichao on 2017/6/28. 8 | */ 9 | @Data 10 | @MapperProcessorAnnotation 11 | public class WeixiaobaoUploadInfo { 12 | 13 | private String deviceId; 14 | private String deviceType; 15 | private String eventType; 16 | private String eventDate; 17 | } 18 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/messagecloud/CommonResponse.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module.messagecloud; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author lichao 7 | * @date 2018/05/14 8 | */ 9 | @Data 10 | public class CommonResponse { 11 | private int code;//状态码,success: 0,failure: (自定义: 如 httpcode+错误枚举值) 12 | private String msg;//目前只用在开发环境供开发识别,之后不再客户端展示 13 | private String data;//success状态存在,表示返回的数据 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/messagecloud/Product.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module.messagecloud; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author lichao 7 | * @date 2018/05/13 8 | */ 9 | @Data 10 | public class Product { 11 | private String name;//产品线名称 12 | private String description;//产品线描述 13 | private long createAt;//创建时间: 1526201521 14 | private long updateAt;//更新时间: 1526201521 15 | } 16 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/module/messagecloud/Topic.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.module.messagecloud; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.util.List; 9 | 10 | /** 11 | * @author lichao 12 | * @date 2018/05/13 13 | */ 14 | @Builder 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | @Data 18 | public class Topic { 19 | private String topicKey;//topicKey 20 | private int messageType;//消息类型 {"0":"普通消息","1":"多机房分发消息"} 21 | private List instanceLocations;//机房 ["TC","YF","ALI_YUN"] 22 | private String producerKey;//生产者appkey 23 | private String consumerKey;//消费者appkey 24 | private int initialQPS;//初始qps 25 | private String description;//topic描述 26 | private String bcpId;//钱包Id 27 | private long createAt;//创建时间: 1526201521 28 | private long updateAt;//更新时间: 1526201521 29 | } -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/resource/TestResource.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.resource; 2 | 3 | /** 4 | * Created by lichao on 16/8/31. 5 | */ 6 | //@Path("/hello") 7 | public class TestResource { 8 | // @Autowired 9 | // ElasticSearchService elasticSearchService; 10 | // 11 | // 12 | // @Path("message") 13 | // @GET 14 | // @Produces(MediaType.APPLICATION_JSON) 15 | // public List getMessage() { 16 | // List users = new ArrayList<>(); 17 | // User user1 = new User(); 18 | // user1.setFirstName("li"); 19 | // user1.setLastName("chao"); 20 | // user1.setId(1l); 21 | // users.add(user1); 22 | // User user2 = new User(); 23 | // user2.setFirstName("wang"); 24 | // user2.setLastName("lu"); 25 | // user2.setId(2l); 26 | // users.add(user2); 27 | // return users; 28 | // } 29 | // 30 | // @Path("elastic") 31 | // @GET 32 | // @Produces(MediaType.APPLICATION_JSON) 33 | // public Object testElastic( 34 | // @ParamDesc(isRequired = true,range = "str:0~255", desc = "test key") 35 | // @QueryParam("test_key") 36 | // String testStr, 37 | // @ParamDesc(isRequired = true, desc = "test value") 38 | // @QueryParam("test_value") 39 | // String value 40 | // ) { 41 | // return elasticSearchService.getTestReuslt(); 42 | // } 43 | // 44 | // @Path("test_case") 45 | // @POST 46 | // @Produces(MediaType.APPLICATION_JSON) 47 | // public TestCase getTestCase( 48 | // @BeanParam TestCase testCase 49 | // ) { 50 | // 51 | // return TestCase.builder().build(); 52 | // } 53 | } 54 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.service; 2 | 3 | import com.jacobs.module.User; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * Created by lichao on 16/7/20. 8 | */ 9 | @Component 10 | public class DemoService { 11 | 12 | public boolean insertUserName(User user) { 13 | // StringCommand.getJedis(BaseConstant.REDIS_NAME) 14 | // .setWithExpire("username", 100, user.getFirstName()); 15 | // return true; 16 | return false; 17 | } 18 | 19 | public String getUserNameForTest() { 20 | return "test"; 21 | } 22 | 23 | public String getUserNameFromCache() { 24 | // try { 25 | // return StringCommand.getJedis(BaseConstant.REDIS_NAME) 26 | // .get("username"); 27 | // } catch (Exception ex) { 28 | // return null; 29 | // } 30 | return null; 31 | } 32 | 33 | // @SuppressWarnings("uncheked") 34 | // public PageableResponse getPageableResponse() { 35 | // return PageableResponse 36 | // .builder() 37 | // .results(Lists.newArrayList()) 38 | // .totalElements(0) 39 | // .totalPages(0) 40 | // .build(); 41 | // } 42 | } 43 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/service/ElasticSearchService.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.service; 2 | 3 | import com.jacobs.conditional.ElasticServiceCondition; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | import org.elasticsearch.action.search.SearchResponse; 7 | import org.elasticsearch.client.Client; 8 | import org.elasticsearch.index.query.QueryBuilder; 9 | import org.elasticsearch.index.query.QueryBuilders; 10 | import org.elasticsearch.search.SearchHit; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.context.annotation.Conditional; 13 | import org.springframework.stereotype.Component; 14 | 15 | /** 16 | * Created by lichao on 2017/2/17. 17 | */ 18 | //@Component 19 | //@Conditional({ElasticServiceCondition.class}) 20 | public class ElasticSearchService { 21 | 22 | @Autowired 23 | private Client client; 24 | 25 | private static final String indexName = "megacorp"; 26 | private static final String typeName = "employee"; 27 | 28 | public Object getTestReuslt() { 29 | QueryBuilder query = QueryBuilders.termQuery("about", "like"); 30 | SearchResponse searchResponse = client.prepareSearch(indexName) 31 | .setTypes(typeName) 32 | .setQuery(query) 33 | .setSize(10) 34 | .get(); 35 | 36 | return Stream.of(searchResponse.getHits() 37 | .getHits()) 38 | .map(SearchHit::getSourceAsString) 39 | .collect(Collectors.toList()); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /core-web/src/main/java/com/jacobs/task/Task.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.task; 2 | 3 | import java.util.concurrent.Future; 4 | import org.springframework.scheduling.annotation.Async; 5 | import org.springframework.scheduling.annotation.AsyncResult; 6 | import org.springframework.stereotype.Component; 7 | 8 | /** 9 | * Created by lichao on 16/8/9. 10 | */ 11 | @Component 12 | public class Task { 13 | 14 | @Async 15 | public Future doTaskOne() throws Exception { 16 | System.out.println("开始做任务一"); 17 | long start = System.currentTimeMillis(); 18 | Thread.sleep(10000); 19 | long end = System.currentTimeMillis(); 20 | System.out.println("完成任务一,耗时:" + (end - start) + "毫秒"); 21 | return new AsyncResult<>("任务一完成"); 22 | } 23 | 24 | @Async 25 | public Future doTaskTwo() throws Exception { 26 | System.out.println("开始做任务二"); 27 | long start = System.currentTimeMillis(); 28 | Thread.sleep(10000); 29 | long end = System.currentTimeMillis(); 30 | System.out.println("完成任务二,耗时:" + (end - start) + "毫秒"); 31 | return new AsyncResult<>("任务二完成"); 32 | } 33 | 34 | @Async 35 | public Future doTaskThree() throws Exception { 36 | System.out.println("开始做任务三"); 37 | long start = System.currentTimeMillis(); 38 | Thread.sleep(10000); 39 | long end = System.currentTimeMillis(); 40 | System.out.println("完成任务三,耗时:" + (end - start) + "毫秒"); 41 | return new AsyncResult<>("任务三完成"); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core-web/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | spring: 2 | profiles: 3 | active: test -------------------------------------------------------------------------------- /core-web/src/main/resources/configs.properties: -------------------------------------------------------------------------------- 1 | test.name=jacobs 2 | kafka.topics: ticauto_log,log-watch-upload -------------------------------------------------------------------------------- /core-web/src/main/resources/hbase-site.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | hbase.zookeeper.quorum 4 | localhost 5 | 6 | 7 | zookeeper.znode.parent 8 | /hbase 9 | 10 | 11 | hbase.zookeeper.property.clientPort 12 | 2181 13 | 14 | 15 | hbase.client.write.buffer 16 | 5242880 17 | 18 | 19 | -------------------------------------------------------------------------------- /core-web/src/main/resources/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | org.springframework.boot.actuate.autoconfigure.EndpointAutoConfiguration -------------------------------------------------------------------------------- /core-web/src/test/java/com/jacobs/GraphiteData.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import java.util.List; 4 | 5 | import com.google.gson.annotations.SerializedName; 6 | 7 | import lombok.Data; 8 | 9 | @Data 10 | public class GraphiteData { 11 | String target; 12 | @SerializedName("datapoints") 13 | List> dataPoints; 14 | } 15 | -------------------------------------------------------------------------------- /core-web/src/test/java/com/jacobs/MockitoTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import static org.mockito.Mockito.mock; 4 | import static org.mockito.Mockito.verify; 5 | import static org.mockito.Mockito.when; 6 | 7 | import com.jacobs.module.Address; 8 | import com.google.common.reflect.TypeToken; 9 | import com.google.gson.Gson; 10 | import java.lang.reflect.Type; 11 | import java.util.LinkedList; 12 | import java.util.List; 13 | import org.junit.Test; 14 | 15 | /** 16 | * Created by lichao on 2017/5/5. 17 | */ 18 | public class MockitoTest { 19 | 20 | @Test 21 | public void testGson() { 22 | String jsonString = "[{\"id\":1,\"province\":\"Beijing\",\"city\":\"Beijing\"}]"; 23 | Type type = new TypeToken>() { 24 | }.getType(); 25 | List
beanOnes = new Gson().fromJson(jsonString, type); 26 | System.out.println(beanOnes); 27 | } 28 | 29 | @Test 30 | public void ListTest() { 31 | List mockedList = mock(List.class); 32 | 33 | // using mock object - it does not throw any "unexpected interaction" exception 34 | mockedList.add("one"); 35 | mockedList.clear(); 36 | 37 | // selective, explicit, highly readable verification 38 | verify(mockedList).add("one"); 39 | verify(mockedList).clear(); 40 | } 41 | 42 | @Test 43 | public void stubMethod() { 44 | // you can mock concrete classes, not only interfaces 45 | LinkedList mockedList = mock(LinkedList.class); 46 | 47 | // stubbing appears before the actual execution 48 | when(mockedList.get(0)).thenReturn("first"); 49 | 50 | // the following prints "first" 51 | System.out.println(mockedList.get(0)); 52 | verify(mockedList).get(0); 53 | 54 | // the following prints "null" because get(999) was not stubbed 55 | System.out.println(mockedList.get(999)); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /core-web/src/test/java/com/jacobs/PaloFeConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import com.jacobs.models.Config; 4 | import java.io.FileReader; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.reflect.Field; 8 | import java.util.Properties; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | /** 13 | * @author lichao 14 | * @date 2018/11/17 15 | */ 16 | public class PaloFeConfigTest { 17 | 18 | @Retention(RetentionPolicy.RUNTIME) 19 | public static @interface ConfField { 20 | 21 | String value() default ""; 22 | } 23 | 24 | public static Properties props = new Properties(); 25 | 26 | public static void main(String[] args) throws Exception { 27 | Config config = new Config(); 28 | config.init("/Users/lichao15/Downloads/palo-0.8.2-release-20180824/fe/conf/fe.conf"); 29 | System.out.println(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /core-web/src/test/java/com/jacobs/Student.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | /** 8 | * Created by lichao on 2017/10/16. 9 | */ 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class Student { 14 | 15 | String className; 16 | } 17 | -------------------------------------------------------------------------------- /core-web/src/test/java/com/jacobs/User.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import com.google.gson.annotations.SerializedName; 4 | import java.io.Serializable; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | /** 11 | * Created by lichao on 2017/7/6. 12 | */ 13 | @Data 14 | @NoArgsConstructor 15 | @AllArgsConstructor 16 | @Builder 17 | public class User implements Serializable { 18 | 19 | Integer id; 20 | String name; 21 | String email; 22 | @SerializedName("passwd") 23 | String password; 24 | String eid; 25 | String epasswd; 26 | Integer major; 27 | Integer isRegistered; 28 | } -------------------------------------------------------------------------------- /docs/优秀博文汇总.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/docs/优秀博文汇总.pdf -------------------------------------------------------------------------------- /docs/算法相关汇总.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lichaojacobs/java_learning_practice/acf92ace46588f2f07fbe7ff89305e70bf0df32f/docs/算法相关汇总.pdf -------------------------------------------------------------------------------- /flink-demos/src/main/scala/com/jacobs/jobs/realtime/utils/ParquetWriters.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.jobs.realtime.utils; 2 | 3 | import java.io.IOException; 4 | import org.apache.avro.Schema; 5 | import org.apache.avro.generic.GenericData; 6 | import org.apache.avro.reflect.ReflectData; 7 | import org.apache.flink.formats.parquet.ParquetBuilder; 8 | import org.apache.flink.formats.parquet.ParquetWriterFactory; 9 | import org.apache.parquet.avro.AvroParquetWriter; 10 | import org.apache.parquet.hadoop.ParquetWriter; 11 | import org.apache.parquet.hadoop.metadata.CompressionCodecName; 12 | import org.apache.parquet.io.OutputFile; 13 | 14 | /** 15 | * @author lichao 16 | * @date 2018/11/25 17 | */ 18 | public class ParquetWriters { 19 | 20 | private static final CompressionCodecName DEFAULT_CODEC_NAME = CompressionCodecName.SNAPPY; 21 | 22 | public static ParquetWriterFactory forReflectRecord(Class type) { 23 | return forReflectRecord(type, DEFAULT_CODEC_NAME); 24 | } 25 | 26 | 27 | public static ParquetWriterFactory forReflectRecord(Class type, CompressionCodecName codecName) { 28 | final String schemaString = ReflectData.get().getSchema(type).toString(); 29 | final ParquetBuilder builder = (out) -> createAvroParquetWriter(schemaString, ReflectData.get(), codecName, out); 30 | return new ParquetWriterFactory<>(builder); 31 | } 32 | 33 | private static ParquetWriter createAvroParquetWriter(String schemaString, GenericData dataModel, CompressionCodecName codecName, 34 | OutputFile out) throws IOException { 35 | 36 | final Schema schema = new Schema.Parser().parse(schemaString); 37 | return AvroParquetWriter.builder(out).withSchema(schema).withDataModel(dataModel).withCompressionCodec(codecName).build(); 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /flink-demos/src/main/scala/com/jacobs/jobs/realtime/wordcount/WindowWordCount.scala: -------------------------------------------------------------------------------- 1 | package com.jacobs.jobs.realtime.wordcount 2 | 3 | import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment 4 | import org.apache.flink.streaming.api.windowing.time.Time 5 | import org.apache.flink.streaming.api.scala._ 6 | 7 | 8 | /** 9 | * @author lichao 10 | */ 11 | object WindowWordCount { 12 | def main(args: Array[String]): Unit = { 13 | val env = StreamExecutionEnvironment.getExecutionEnvironment 14 | val text = env.socketTextStream("localhost", 9999) 15 | val counts = text.flatMap( 16 | _.toLowerCase.split("\\W+") filter { 17 | _.nonEmpty 18 | } 19 | ) 20 | .map { 21 | (_, 1) 22 | } 23 | .keyBy(0) 24 | .timeWindow(Time.seconds(5)) 25 | .sum(1) 26 | 27 | counts.print() 28 | 29 | env.execute("Window Stream WordCount") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /netty-learning/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | java_learning_practice 7 | com.jacobs 8 | 1.0.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | netty-learning 13 | pom 14 | 15 | 16 | 17 | 18 | io.netty 19 | netty-all 20 | 4.1.42.Final 21 | 22 | 23 | com.google.protobuf 24 | protobuf-java 25 | 3.3.1 26 | 27 | 28 | com.google.protobuf 29 | protobuf-java-util 30 | 3.3.1 31 | 32 | 33 | org.apache.logging.log4j 34 | log4j-core 35 | 36 | 37 | org.apache.logging.log4j 38 | log4j-api 39 | 40 | 41 | org.slf4j 42 | slf4j-log4j12 43 | LATEST 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/aiotimeserver1/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.aiotimeserver1; 2 | 3 | /** 4 | * Created by lichao on 2017/1/28. 5 | */ 6 | public class TimeClient { 7 | public static void main(String[] args) { 8 | int port = 8080; 9 | if (args != null && args.length > 0) { 10 | try { 11 | port = Integer.valueOf(args[0]); 12 | } catch (Exception ex) { 13 | 14 | } 15 | } 16 | 17 | new Thread(new AsyncTimeClientHandler("127.0.0.1", port), "AIO TimeClient-001").start(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/aiotimeserver1/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.aiotimeserver1; 2 | 3 | import java.io.IOException; 4 | 5 | /** 6 | * Created by lichao on 2017/1/28. 7 | */ 8 | public class TimeServer { 9 | public static void main(String[] args) throws IOException { 10 | int port = 8080; 11 | new Thread(new AsyncTimeServerHandler("127.0.0.1", port), 12 | "AIO-AsyncTimeServerHandler-001").start(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/bio/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.bio; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.io.PrintWriter; 7 | import java.net.InetAddress; 8 | import java.net.Socket; 9 | 10 | /** 11 | * Created by lichao on 2016/11/5. 12 | */ 13 | public class TimeClient { 14 | public static void main(String[] args) { 15 | int port = 8080; 16 | if (args != null && args.length > 0) { 17 | try { 18 | port = Integer.valueOf(args[0]); 19 | } catch (NumberFormatException e) { 20 | // 采用默认值 21 | } 22 | } 23 | Socket socket = null; 24 | BufferedReader in = null; 25 | PrintWriter out = null; 26 | try { 27 | socket = new Socket(InetAddress.getLocalHost().getHostAddress(), port); 28 | in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 29 | out = new PrintWriter(socket.getOutputStream(), true); 30 | out.println("QUERY TIME ORDER"); 31 | System.out.println("Send order 2 server succeed."); 32 | String resp = in.readLine(); 33 | System.out.println("Now is : " + resp); 34 | } catch (Exception e) { 35 | //不需要处理 36 | } finally { 37 | if (out != null) { 38 | out.close(); 39 | } 40 | if (in != null) { 41 | try { 42 | in.close(); 43 | } catch (IOException e) { 44 | e.printStackTrace(); 45 | } 46 | } 47 | if (socket != null) { 48 | try { 49 | socket.close(); 50 | } catch (IOException e) { 51 | e.printStackTrace(); 52 | } 53 | } 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/bio/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.bio; 2 | 3 | import java.io.IOException; 4 | import java.net.InetAddress; 5 | import java.net.ServerSocket; 6 | import java.net.Socket; 7 | 8 | /** 9 | * Created by lichao on 2016/11/5. 10 | */ 11 | public class TimeServer { 12 | 13 | public static void main(String[] args) throws IOException { 14 | int port = 8080; 15 | if (args != null && args.length > 0) { 16 | 17 | } 18 | ServerSocket serverSocket = null; 19 | try { 20 | serverSocket = new ServerSocket(port, 20, InetAddress.getLocalHost()); 21 | System.out.println("The time server is start in port : " + port); 22 | while (true) { 23 | Socket socket = serverSocket.accept(); 24 | //考虑到多请求情况,每个请求分配一个thread 25 | new Thread(new TimeServerHandler(socket)).start(); 26 | } 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } finally { 30 | if (serverSocket != null) { 31 | System.out.println("The time server close"); 32 | serverSocket.close(); 33 | serverSocket = null; 34 | } 35 | 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/client/EchoClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.client; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandler; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | import io.netty.util.CharsetUtil; 9 | 10 | /** 11 | * Created by lichao on 16/9/24. 12 | */ 13 | @ChannelHandler.Sharable 14 | public class EchoClientHandler extends SimpleChannelInboundHandler { 15 | 16 | @Override 17 | public void channelActive(ChannelHandlerContext ctx) { 18 | ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", //2 19 | CharsetUtil.UTF_8)); 20 | } 21 | 22 | @Override 23 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { //4 24 | cause.printStackTrace(); 25 | ctx.close(); 26 | } 27 | 28 | //这种方法会在接收到数据时被调用。注意,由服务器所发送的消息可以以块的形式被接收。 29 | // 即,当服务器发送 5 个字节是不是保证所有的 5 个字节会立刻收到 - 即使是只有 5 个字节,channelRead0() 方法可被调用两次, 30 | // 第一次用一个ByteBuf(Netty的字节容器)装载3个字节和第二次一个 ByteBuf 装载 2 个字节。 31 | // 唯一要保证的是,该字节将按照它们发送的顺序分别被接收。 (注意,这是真实的,只有面向流的协议如TCP) 32 | @Override 33 | protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) 34 | throws Exception { 35 | System.out.println("Client received: " + byteBuf.toString(CharsetUtil.UTF_8)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/http_helloworld/HttpHelloWorldServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.http_helloworld; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | import io.netty.channel.ChannelPipeline; 5 | import io.netty.channel.socket.SocketChannel; 6 | import io.netty.handler.codec.http.HttpServerCodec; 7 | import io.netty.handler.codec.http.HttpServerExpectContinueHandler; 8 | import io.netty.handler.ssl.SslContext; 9 | 10 | public class HttpHelloWorldServerInitializer extends ChannelInitializer { 11 | 12 | private final SslContext sslCtx; 13 | 14 | public HttpHelloWorldServerInitializer(SslContext sslCtx) { 15 | this.sslCtx = sslCtx; 16 | } 17 | 18 | @Override 19 | public void initChannel(SocketChannel ch) { 20 | ChannelPipeline p = ch.pipeline(); 21 | if (sslCtx != null) { 22 | p.addLast(sslCtx.newHandler(ch.alloc())); 23 | } 24 | p.addLast(new HttpServerCodec()); 25 | p.addLast(new HttpServerExpectContinueHandler()); 26 | p.addLast(new HttpHelloWorldServerHandler()); 27 | } 28 | } -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/server/ServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.server; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelFutureListener; 6 | import io.netty.channel.ChannelHandler; 7 | import io.netty.channel.ChannelHandlerContext; 8 | import io.netty.channel.ChannelInboundHandlerAdapter; 9 | import io.netty.util.CharsetUtil; 10 | 11 | /** 12 | * Created by lichao on 16/9/23. 13 | */ 14 | @ChannelHandler.Sharable 15 | public class ServerHandler extends ChannelInboundHandlerAdapter { 16 | @Override 17 | public void channelRead(ChannelHandlerContext ctx, Object msg) { 18 | ByteBuf in = (ByteBuf) msg; 19 | System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); //2 20 | ctx.write(in); //3 21 | } 22 | 23 | @Override 24 | public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { 25 | ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4 26 | .addListener(ChannelFutureListener.CLOSE); 27 | } 28 | 29 | @Override 30 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { 31 | cause.printStackTrace(); //5 32 | ctx.close(); //6 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/subscribe/SubReqServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.subscribe; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelOption; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.SocketChannel; 9 | import io.netty.channel.socket.nio.NioServerSocketChannel; 10 | import io.netty.handler.logging.LogLevel; 11 | import io.netty.handler.logging.LoggingHandler; 12 | 13 | /** 14 | * Created by lichao on 2017/9/12. 15 | */ 16 | public class SubReqServer { 17 | 18 | public void bind(int port) throws Exception { 19 | //配置服务端NIO线程组 20 | 21 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 22 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 23 | 24 | try { 25 | ServerBootstrap b = new ServerBootstrap(); 26 | b.group(bossGroup, workerGroup) 27 | .channel(NioServerSocketChannel.class) 28 | .option(ChannelOption.SO_BACKLOG, 100) 29 | .handler(new LoggingHandler(LogLevel.INFO)) 30 | .childHandler(new ChannelInitializer() { 31 | @Override 32 | 33 | protected void initChannel(SocketChannel channel) throws Exception { 34 | /*channel.pipeline().addLast(new ProtobufVarint32FrameDecoder()) 35 | .addLast(new ProtobufDecoder(SubscribeReq))*/ 36 | } 37 | }); 38 | 39 | } finally { 40 | //优雅退出,释放线程资源 41 | bossGroup.shutdownGracefully(); 42 | workerGroup.shutdownGracefully(); 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/timeserver1/TimeClient.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.timeserver1; 2 | 3 | /** 4 | * Created by lichao on 2017/1/28. 5 | */ 6 | public class TimeClient { 7 | public static void main(String[] args) { 8 | int port = 8080; 9 | if (args != null && args.length > 0) { 10 | try { 11 | port = Integer.valueOf(args[0]); 12 | } catch (Exception ex) { 13 | 14 | } 15 | } 16 | 17 | new Thread(new TimeClientHandle("127.0.0.1", port), "TimeClient-001").start(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/timeserver1/TimeServer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.timeserver1; 2 | 3 | /** 4 | * Created by lichao on 2017/1/26. 5 | */ 6 | public class TimeServer { 7 | public static void main(String[] args) { 8 | int port = 8080; 9 | if (args != null && args.length > 0) { 10 | try { 11 | port = Integer.valueOf(args[0]); 12 | } catch (Exception ex) { 13 | 14 | } 15 | 16 | } 17 | 18 | new Thread(new MutiplexerTimeServer("127.0.0.1",port), "MULTIPLEXERTIMERSERVER-001").start(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/websocketx/benchmarkserver/WebSocketServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.websocketx.benchmarkserver; 2 | 3 | /** 4 | * Created by lichao on 2017/9/12. 5 | */ 6 | 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelPipeline; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.handler.codec.http.HttpObjectAggregator; 11 | import io.netty.handler.codec.http.HttpServerCodec; 12 | import io.netty.handler.ssl.SslContext; 13 | 14 | /** 15 | */ 16 | public class WebSocketServerInitializer extends ChannelInitializer { 17 | 18 | private final SslContext sslCtx; 19 | 20 | public WebSocketServerInitializer(SslContext sslCtx) { 21 | this.sslCtx = sslCtx; 22 | } 23 | 24 | @Override 25 | public void initChannel(SocketChannel ch) throws Exception { 26 | ChannelPipeline pipeline = ch.pipeline(); 27 | if (sslCtx != null) { 28 | pipeline.addLast(sslCtx.newHandler(ch.alloc())); 29 | } 30 | pipeline.addLast(new HttpServerCodec()); 31 | pipeline.addLast(new HttpObjectAggregator(65536)); 32 | pipeline.addLast(new WebSocketServerHandler()); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /netty-learning/src/main/java/com/jacobs/netty/websocketx/server/WebSocketServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.netty.websocketx.server; 2 | 3 | /** 4 | * Created by lichao on 2017/9/12. 5 | */ 6 | 7 | import io.netty.channel.ChannelInitializer; 8 | import io.netty.channel.ChannelPipeline; 9 | import io.netty.channel.socket.SocketChannel; 10 | import io.netty.handler.codec.http.HttpObjectAggregator; 11 | import io.netty.handler.codec.http.HttpServerCodec; 12 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 13 | import io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler; 14 | import io.netty.handler.ssl.SslContext; 15 | 16 | /** 17 | */ 18 | public class WebSocketServerInitializer extends ChannelInitializer { 19 | 20 | private static final String WEBSOCKET_PATH = "/websocket"; 21 | 22 | private final SslContext sslCtx; 23 | 24 | public WebSocketServerInitializer(SslContext sslCtx) { 25 | this.sslCtx = sslCtx; 26 | } 27 | 28 | @Override 29 | public void initChannel(SocketChannel ch) throws Exception { 30 | ChannelPipeline pipeline = ch.pipeline(); 31 | if (sslCtx != null) { 32 | pipeline.addLast(sslCtx.newHandler(ch.alloc())); 33 | } 34 | pipeline.addLast(new HttpServerCodec()); 35 | pipeline.addLast(new HttpObjectAggregator(65536)); 36 | pipeline.addLast(new WebSocketServerCompressionHandler()); 37 | pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PATH, null, true)); 38 | pipeline.addLast(new WebSocketIndexPageHandler(WEBSOCKET_PATH)); 39 | pipeline.addLast(new WebSocketFrameHandler()); 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/SpringWebFluxApplication.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.web.reactive.config.EnableWebFlux; 8 | 9 | import com.jacobs.webflux.config.EventLoopNettyCustomizer; 10 | 11 | /** 12 | * @author lichao 13 | * @date 2017/11/9 14 | */ 15 | @EnableWebFlux 16 | @SpringBootApplication 17 | public class SpringWebFluxApplication { 18 | 19 | public static void main(String[] args) { 20 | SpringApplication.run(SpringWebFluxApplication.class, args); 21 | } 22 | 23 | @Bean 24 | public NettyReactiveWebServerFactory nettyReactiveWebServerFactory() { 25 | NettyReactiveWebServerFactory webServerFactory = new NettyReactiveWebServerFactory(); 26 | webServerFactory.addServerCustomizers(new EventLoopNettyCustomizer()); 27 | return webServerFactory; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/config/EventLoopNettyCustomizer.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux.config; 2 | 3 | import io.netty.channel.EventLoopGroup; 4 | import io.netty.channel.nio.NioEventLoopGroup; 5 | import io.netty.channel.socket.nio.NioServerSocketChannel; 6 | import org.springframework.boot.web.embedded.netty.NettyServerCustomizer; 7 | import reactor.netty.http.server.HttpServer; 8 | 9 | public class EventLoopNettyCustomizer implements NettyServerCustomizer { 10 | 11 | @Override 12 | public HttpServer apply(HttpServer httpServer) { 13 | EventLoopGroup parentGroup = new NioEventLoopGroup(); 14 | EventLoopGroup childGroup = new NioEventLoopGroup(); 15 | return httpServer.tcpConfiguration( 16 | tcpServer -> tcpServer.bootstrap(serverBootstrap -> serverBootstrap 17 | .group(parentGroup, childGroup).channel(NioServerSocketChannel.class))); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/config/RoutingConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux.config; 2 | 3 | import static org.springframework.http.MediaType.APPLICATION_JSON; 4 | import static org.springframework.web.reactive.function.server.RequestPredicates.DELETE; 5 | import static org.springframework.web.reactive.function.server.RequestPredicates.GET; 6 | import static org.springframework.web.reactive.function.server.RequestPredicates.accept; 7 | import static org.springframework.web.reactive.function.server.RouterFunctions.route; 8 | 9 | import com.jacobs.webflux.handler.UserHandler; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | import org.springframework.web.reactive.function.server.RouterFunction; 13 | import org.springframework.web.reactive.function.server.ServerResponse; 14 | 15 | /** 16 | * @author lichao 17 | * @date 2017/11/9 18 | */ 19 | @Configuration 20 | public class RoutingConfiguration { 21 | 22 | @Bean 23 | public RouterFunction routerFunction(UserHandler userHandler) { 24 | 25 | return route(GET("/users").and(accept(APPLICATION_JSON)), userHandler::listUsers) 26 | .andRoute(GET("/user/{id}").and(accept(APPLICATION_JSON)), 27 | userHandler::getUserById) 28 | .andRoute(GET("/watchUsers").and(accept(APPLICATION_JSON)), 29 | userHandler::getNearByWatchUsers) 30 | .andRoute(DELETE("/{user}").and(accept(APPLICATION_JSON)), userHandler::deleteUser); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/controller/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux.controller; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | /** 7 | * @author lichao 8 | * @date 2017/11/9 9 | */ 10 | @RestController 11 | public class HelloController { 12 | 13 | @GetMapping("/hello") 14 | public String handle() { 15 | return "Hello WebFlux"; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/model/NearByUserModel.java: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Mobvoi Inc. All Rights Reserved. 2 | 3 | package com.jacobs.webflux.model; 4 | 5 | import com.google.gson.annotations.SerializedName; 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * Created by lichao on 2017/4/14. 13 | */ 14 | @Data 15 | @NoArgsConstructor 16 | @AllArgsConstructor 17 | @Builder 18 | public class NearByUserModel { 19 | 20 | @SerializedName("watch_device_id") 21 | private String watchDeviceId; 22 | private String wwid; 23 | private String nickname; 24 | @SerializedName("img_url") 25 | private String imgUrl; 26 | private int distance; 27 | private int steps; 28 | private boolean liked; 29 | private int rank; 30 | @SerializedName("is_tic_mon") 31 | private boolean isTicMon; 32 | @SerializedName("is_tic_mon_clicked") 33 | private boolean isTicMonClicked; 34 | private int level; 35 | } 36 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/model/NearByUserResponse.java: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Mobvoi Inc. All Rights Reserved. 2 | 3 | package com.jacobs.webflux.model; 4 | 5 | import com.google.gson.annotations.SerializedName; 6 | import java.util.List; 7 | import lombok.AllArgsConstructor; 8 | import lombok.Builder; 9 | import lombok.Data; 10 | import lombok.NoArgsConstructor; 11 | 12 | /** 13 | * Created by lichao on 2017/4/14. 14 | */ 15 | @Data 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | @Builder 19 | public class NearByUserResponse { 20 | 21 | private int status; 22 | private int rank; 23 | private int code; 24 | private int steps; 25 | @SerializedName("privacy_state") 26 | private boolean privacyState; 27 | @SerializedName("watch_device_id") 28 | private String watchDeviceId; 29 | private List data; 30 | @SerializedName("num_likes") 31 | private int numLikes; 32 | private String nickname; 33 | @SerializedName("img_url") 34 | private String imgUrl; 35 | } 36 | -------------------------------------------------------------------------------- /spring-webflux/src/main/java/com/jacobs/webflux/model/User.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux.model; 2 | 3 | import java.io.Serializable; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * Created by lichao on 2017/7/6. 11 | */ 12 | @Data 13 | @NoArgsConstructor 14 | @AllArgsConstructor 15 | @Builder 16 | public class User implements Serializable { 17 | 18 | Integer id; 19 | String name; 20 | String email; 21 | String password; 22 | String eid; 23 | String epasswd; 24 | Integer major; 25 | Integer isRegistered; 26 | 27 | public User(int id, String name, String email) { 28 | this.id = id; 29 | this.name = name; 30 | this.email = email; 31 | } 32 | } -------------------------------------------------------------------------------- /spring-webflux/src/main/resources/application.yaml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8888 3 | spring: 4 | profiles: 5 | active: dev 6 | 7 | mysql: 8 | common: 9 | userName: root 10 | passWord: lichao0903 11 | decrypt: false 12 | masterUrl: jdbc:mysql://127.0.0.1:3306/kmap?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false 13 | bussiness: 14 | userName: root 15 | passWord: lichao0903 16 | decrypt: false 17 | masterUrl: jdbc:mysql://127.0.0.1:3306/kmap?useUnicode=true&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false 18 | -------------------------------------------------------------------------------- /spring-webflux/src/test/java/com/jacobs/webflux/SpringWebfluxApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.jacobs.webflux; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringWebfluxApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/Compose.kt: -------------------------------------------------------------------------------- 1 | package com.jacobs.kotlin_inaction 2 | 3 | /** 4 | * Created by lichao on 2017/5/26. 5 | */ 6 | 7 | fun main(args: Array) { 8 | val oddLength = compose(::isOdd, ::length) 9 | val strings = listOf("a", "ab", "abc") 10 | println(strings.filter(oddLength)) 11 | } 12 | 13 | fun length(s: String) = s.length 14 | 15 | fun compose(f: (B) -> C, g: (A) -> B): (A) -> C { 16 | return { x -> f(g(x)) } 17 | } -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/Dataclasses.kt: -------------------------------------------------------------------------------- 1 | package com.jacobs.kotlin_inaction 2 | 3 | /** 4 | * Created by lichao on 2017/5/26. 5 | */ 6 | data class User(val name: String, val id: Int) 7 | 8 | fun getUser(): User { 9 | return User("Alex", 1) 10 | } 11 | 12 | fun main(args: Array) { 13 | val user = getUser() 14 | println("name = ${user.name}, id = ${user.id}") 15 | 16 | // or 17 | 18 | val (name, id) = getUser() 19 | println("name = $name, id = $id") 20 | 21 | // or 22 | 23 | println("name = ${getUser().component1()}, id = ${getUser().component2()}") 24 | } 25 | -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/Delegate.kt: -------------------------------------------------------------------------------- 1 | package com.jacobs.kotlin_inaction 2 | 3 | /** 4 | * Created by lichao on 2017/5/26. 5 | */ 6 | import kotlin.reflect.KProperty 7 | 8 | class Example { 9 | var p: String by Delegate() 10 | 11 | override fun toString() = "Example Class" 12 | } 13 | 14 | class Delegate { 15 | operator fun getValue(thisRef: Any?, prop: KProperty<*>): String { 16 | return "$thisRef, thank you for delegating '${prop.name}' to me!" 17 | } 18 | 19 | operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: String) { 20 | println("$value has been assigned to ${prop.name} in $thisRef") 21 | } 22 | } 23 | 24 | fun main() { 25 | val e = Example() 26 | println(e.p) 27 | e.p = "NEW" 28 | } -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/EnumDemo.kt: -------------------------------------------------------------------------------- 1 | package com.jacobs.kotlin_inaction 2 | 3 | /** 4 | * @author lichao 5 | * Created on 2019-06-08 6 | */ 7 | 8 | enum class Color1 { 9 | RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO 10 | } 11 | 12 | enum class Color2(val r: Int, val g: Int, val b: Int) { 13 | RED(255, 0, 0), 14 | ORANGE(0, 255, 255), 15 | YELLOW(255, 255, 0), 16 | GREEN(0, 255, 0), 17 | BLUE(0, 0, 255), 18 | INDIGO(75, 0, 130), VIOLET(238, 130, 238); 19 | 20 | fun rgb() = (r * 256 + g) * 256 + b 21 | } -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/IteratorDemo.kt: -------------------------------------------------------------------------------- 1 | package com.jacobs.kotlin_inaction 2 | 3 | import java.util.* 4 | 5 | /** 6 | * @author lichao 7 | * Created on 2019-06-08 8 | */ 9 | 10 | fun testForLoop() { 11 | val binaryReps = TreeMap() 12 | // Iterates over the characters from A to F using a range of characters 13 | for (c in 'A'..'F') { 14 | val binary = Integer.toBinaryString(c.toInt()) 15 | binaryReps[c] = binary 16 | } 17 | 18 | for ((letter, binary) in binaryReps) { 19 | println("$letter = $binary") 20 | } 21 | 22 | for (i in 100 downTo 1 step 2) { 23 | print(fizzBuzz(i)) 24 | } 25 | 26 | // 在遍历时,同时拿到遍历的index 27 | val list = arrayListOf("10", "11", "10001") 28 | for ((index, element) in list.withIndex()) { 29 | println("$index : $element") 30 | } 31 | } 32 | 33 | //通过 in 来判断元素是否在collection 范围里面 34 | //底层实际转换为a <= c && c <= z 35 | fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z' 36 | 37 | fun isNotDigit(c: Char) = c !in '0'..'9' 38 | 39 | fun main() { 40 | testForLoop() 41 | println(isLetter('q')) 42 | println(isNotDigit('x')) 43 | println(recognize('8')) 44 | } -------------------------------------------------------------------------------- /utils/src/main/java/com/jacobs/kotlin_inaction/ex1.kt: -------------------------------------------------------------------------------- 1 | package inaction 2 | 3 | /** 4 | * Created by lichao on 2017/5/26. 5 | */ 6 | 7 | data class Person(val name: String, val age: Int? = null) 8 | 9 | fun main() { 10 | val persons = listOf(Person("Alice"), Person("Bob", age = 29)) 11 | print(persons) 12 | } -------------------------------------------------------------------------------- /utils/src/test/java/com/jacobs/AppTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | import junit.framework.Test; 4 | import junit.framework.TestCase; 5 | import junit.framework.TestSuite; 6 | 7 | /** 8 | * Unit test for simple App. 9 | */ 10 | public class AppTest 11 | extends TestCase 12 | { 13 | /** 14 | * Create the test case 15 | * 16 | * @param testName name of the test case 17 | */ 18 | public AppTest( String testName ) 19 | { 20 | super( testName ); 21 | } 22 | 23 | /** 24 | * @return the suite of tests being tested 25 | */ 26 | public static Test suite() 27 | { 28 | return new TestSuite( AppTest.class ); 29 | } 30 | 31 | /** 32 | * Rigourous Test :-) 33 | */ 34 | public void testApp() 35 | { 36 | assertTrue( true ); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /utils/src/test/java/com/jacobs/UtilTest.java: -------------------------------------------------------------------------------- 1 | package com.jacobs; 2 | 3 | 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.concurrent.Future; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import okhttp3.Credentials; 10 | 11 | import org.junit.Test; 12 | 13 | /** 14 | * Created by lichao on 2017/4/12. 15 | */ 16 | public class UtilTest { 17 | 18 | private com.jacobs.CommonHttpUtil commonHttpUtil = com.jacobs.CommonHttpUtil.builder().build(); 19 | private SimpleDateFormat simpleDateTime = new SimpleDateFormat("yyyy/MM/dd"); 20 | 21 | public static void main(String[] args) { 22 | System.out.println(Credentials.basic("root", "root")); 23 | } 24 | 25 | @Test 26 | public void testGetMethod() { 27 | try { 28 | //System.out.println(commonHttpUtil.get("http://visual-be/data").send().tryString()); 29 | Future responseFuture = commonHttpUtil.get("http://visual-be/data") 30 | .async(); 31 | com.jacobs.CommonHttpUtil.HttpResponse response = responseFuture.get(1000, TimeUnit.MILLISECONDS); 32 | response.setJson(true); 33 | System.out.println(response.tryJson()); 34 | 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } 38 | } 39 | 40 | @Test 41 | public void regTest() { 42 | System.out.println(simpleDateTime.format(Calendar.getInstance().getTime())); 43 | } 44 | } 45 | --------------------------------------------------------------------------------