fixed conflict

This commit is contained in:
universefeeler 2019-01-04 22:34:58 +08:00
commit 0a5f627808
675 changed files with 76463 additions and 23683 deletions

16
.editorconfig Normal file
View File

@ -0,0 +1,16 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[{package.json,.travis.yml}]
indent_size = 2

View File

@ -18,5 +18,5 @@ Follow this checklist to help us incorporate your contribution quickly and easil
* [ ] Format the pull request title like `[ISSUE #123] Fix UnknownException when host config not exist`. Each commit in the pull request should have a meaningful subject line and body.
* [ ] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
* [ ] Write necessary unit-test to verify your logic correction, more mock a little better when cross module dependency exist. If the new feature or significant change is committed, please remember to add integration-test in [test module](https://github.com/alibaba/nacos/tree/master/test).
* [ ] Run `mvn -B clean apache-rat:check findbugs:findbugs` to make sure basic checks pass. Run `mvn clean install -DskipITs` to make sure unit-test pass. Run `mvn clean test-compile failsafe:integration-test` to make sure integration-test pass.
* [ ] Run `mvn -B clean package apache-rat:check findbugs:findbugs -Dmaven.test.skip=true` to make sure basic checks pass. Run `mvn clean install -DskipITs` to make sure unit-test pass. Run `mvn clean test-compile failsafe:integration-test` to make sure integration-test pass.

3
.gitignore vendored
View File

@ -5,8 +5,11 @@
target
.project
.idea
.vscode
.DS_Store
.factorypath
/logs
*.iml
node_modules
test/derby.log
derby.log

View File

@ -4,6 +4,7 @@ notifications:
- xchaos8@126.com
- nacos_dev@linux.alibaba.com
- dev-nacos@googlegroups.com
- mw_configcenter@list.alibaba-inc.com
on_success: change
on_failure: always
@ -24,7 +25,9 @@ before_install:
- if [ "$TRAVIS_OS_NAME" == "linux" ]; then jdk_switcher use "$CUSTOM_JDK"; fi
script:
- mvn -B clean package apache-rat:check findbugs:findbugs -Dmaven.test.skip=true
- mvn -Prelease-nacos clean install -U
- mvn clean package -Pit-test
after_success:
- mvn clean install -Pit-test
- mvn clean package -Pit-test
- mvn sonar:sonar -Psonar-apache

View File

@ -1,3 +1,108 @@
## 0.7.0(Dec, 2018)
* [ #461 ] Registration failed when instance port is set to 0
* [ #455 ] The console can't change the change code
* [ #447 ] 集群模式server挂掉一台后提供方注册失败
* [ #445 ] 0.6.1控制台创建配置发布提交时,提示信息有问题
* [ #442 ] Typos in class names and variables.
* [ #413 ] The console has some uncaught exceptions
* [ #395 ] nacos surport mysql in the case of stand-alone mode
* [ #393 ] Support operation of selector on console
* [ #365 ] NodeJs SDK support
* [ #362 ] The metadata will lost when online or offline instance through web ui
* [ #187 ] Provide Label ability for Naming Service into NACOS for complex multi-DC scenario.
## 0.6.1(Dec, 2018)
* [#421] NamingService's serivce name can't use colon(:) in Windows
* [#432] When packing nacos-core, ${user.home} is replaced in the logback configuration file (nacos.xml)
## 0.6.0(Dec, 2018)
* [#388] Cluster name should be provided in the Instance
* [#377] Clean up messy code in Naming module
* [#369] Support instance list persisted on disk
* [#366] findbugs-maven-plugin version
* [#362] The metadata will lost when online or offline instance through web ui
* [#352] Refactoring internationalization Nacos console
* [#278] Nacos docker img
* [#243] optimize the efficiency of integration testing, its taking too long now
## 0.5.0(Nov, 2018)
* [#148] Naming write performace.
* [#175] Support deregistering instance automatically.
* [#176] Naming client query instance method should bypass local cache at client start.
* [#177] Console supports registering new empty service and delete empty service.
* [#181] NPE when adding a instance if no leader in the raft cluster.
* [#193] Configure host domain name cause nacos server cluster is unavailable.
* [#209] Disable service and cluster level customization in client registerInstance method.
* [#214] Please support Java 11.
* [#222] print more nacos server start status info in start.log.
* [#231] Refactoring: Parsing the Nacos home directory and the cluster.conf file.
* [#246] "mvn -B clean apache-rat:check findbugs:findbugs" did not work as expected.
* [#251] Console Editor Optimization.
* [#254] DataId and group are required in historical version and listener query.
* [#256] Whether the service discovery data needs to add a newline link symbol.
* [#257] Listening query switching query dimension data is not refreshed.
* [#258] Remove the Balloon of DataId/Group.
* [#259] Listening query paging size problem.
* [#272] "#it is ip" is also parsed into an instance IP.
* [#275] nacos coredns plugin to support DNS.
* [#281] We should lint the console code.
* [#302] Maven build project supports java 11.
* [#316] In stand alone mode, Nacos still checks the cluster.conf.
## 0.4.0(Nov 7, 2018)
* [#216] Fix tenant dir problem
* [#197] Service update ignored some properties
* [#190] Client beat lose weight info and metadata info
* [#188] Console delete data cannot be updated in time
* [#179] Listening query fail when namespace is not blank
* [#157] Lack information in readme.md to describe the related project repositories for Nacos echosystem
* [#144] There have a error and something are not clear
* [#106] Snapshot file create error
* [#92] Eliminate warnings, refactor code, show start.log detail
## 0.3.0(Oct 26, 2018)
* [#171] UI debug errors
* [#156] Web UI 404 problem
* [#155] use local resource
* [#145] nacos-example not found :org.apache.logging.log4j.core.Logger
* [#142] UI console show Group
* [#149] Fix naming client beat process failed bug.
* [#150] Fix naming service registration hangs bug.
## 0.3.0-RC1(Oct 19, 2018)
* [#33] Support console for config management.
* [#51] Support console for naming service.
* [#121] Fix get instance method hanging bug.
* [#138] Add a flag to indicate if instance is offline.
* [#130] Fix health check disabled if machine has one CPU core bug.
* [#139] Fix still get instance with zero weight bug.
* [#128] Fix console layout bug.
## 0.2.1-release(Sept 28, 2018)
* FIx deregister last instance failed error.
* Fix url pattern error.
* Fully integrate with and seamlessly support Spring framework, Spring Boot and Spring Cloud
* Separate nacos-api from nacos client implementation
* Support high available cluster mode
* Fix cluster node health check abnormality
* Fix stand-alone mode gets the change history list exception
* Fix Pulling does not exist configuration print io exception
* Optimized log framework
* Service Discovery: Client support getting server status.
* Service Discovery: Client support get all service names of server.
* Service Discovery: Client support get all subscribed services.
## 0.2.0 (Sept 17, 2018)
#### FEATURES:

73
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,73 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
education, socio-economic status, nationality, personal appearance, race,
religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at users-nacos@googlegroups.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org

View File

@ -1,31 +1,124 @@
## How To Contribute
# Contributing to Nacos
We are always very happy to have contributions, whether for trivial cleanups or big new features.
We want to have high quality, well documented codes for each programming language.
Welcome to Nacos! This document is a guideline about how to contribute to Nacos.
Nor is code the only way to contribute to the project. We strongly value documentation, integration with other project, and gladly accept improvements for these aspects.
If you find something incorrect or missing, please leave comments / suggestions.
## Contributing code
## Before you get started
To submit a change for inclusion, please do the following:
### Code of Conduct
#### If the change is non-trivial please include some unit tests that cover the new functionality.
#### If you are introducing a completely new feature or API it is a good idea to start a wiki and get consensus on the basic design first.
#### It is our job to follow up on patches in a timely fashion. Nag us if we aren't doing our job (sometimes we drop things).
Please make sure to read and observe our [Code of Conduct](./CODE_OF_CONDUCT.md).
## Becoming a Committer
## Contributing
We are always interested in adding new contributors. What we look for are series of contributions, good taste and ongoing interest in the project. If you are interested in becoming a committer, please let one of the existing committers know and they can help you walk through the process.
Nacos welcome new participants of any role, including user, contributor, committer and PMC.
Nowadays,we have several important contribution points:
#### Wiki & JavaDoc
#### Nacos Console
#### Nacos SDK(C++\.Net\Php\Python\Go\Node.js)
![](http://acm-public.oss-cn-hangzhou.aliyuncs.com/contributor_definition.png)
##### Prerequisite
If you want to contribute the above listing points, you must abide our some prerequisites:
###### Readability - API must have Javadoc,some very important methods also must have javadoc
###### Testability - 80% above unit test coverage about main process
###### Maintainability - Comply with our [PMD spec](style/codeStyle.xml), and at least 3 month update frequency
###### Deployability - We encourage you to deploy into [maven repository](http://search.maven.org/)
We encourage new comers actively join in Nacos projects and involving from user role to committer role, and even PMC role. In order to accomplish this, new comers needs to actively contribute in Nacos project. The following paragraph introduce how to contribute in Nacos way.
#### Open / pickup an issue for preparation
If you find a typo in document, find a bug in code, or want new features, or want to give suggestions, you can [open an issue on GitHub](https://github.com/alibaba/Nacos/issues/new) to report it.
If you just want to contribute directly you can choose the issue below.
- [Contribution Welcome](https://github.com/alibaba/nacos/labels/contribution%20welcome): Heavily needed issue, but currently short of hand.
- [good first issue](https://github.com/alibaba/nacos/labels/good%20first%20issue): Good for newcomers, new comer can pickup one for warm-up.
We strongly value documentation and integration with other projects such as Spring Cloud, Kubernetes, Dubbo, etc. We are very glad to work on any issue for these aspects.
Please note that any PR must be associated with a valid issue. Otherwise the PR will be rejected.
#### Begin your contribute
Now if you want to contribute, please create a new pull request.
We use the `develop` branch as the development branch, which indicates that this is a unstable branch.
Further more, our branching model complies to [https://nvie.com/posts/a-successful-git-branching-model/](https://nvie.com/posts/a-successful-git-branching-model/). We strongly suggest new comers walk through the above article before creating PR.
Now, if you are ready to create PR, here is the workflow for contributors:
1. Fork to your own
2. Clone fork to local repository
3. Create a new branch and work on it
4. Keep your branch in sync
5. Commit your changes (make sure your commit message concise)
6. Push your commits to your forked repository
7. Create a pull request to **develop** branch.
When creating pull request:
1. Please follow [the pull request template](./.github/PULL_REQUEST_TEMPLATE.md).
2. Please create the request to **develop** branch.
3. Please make sure the PR has a corresponding issue.
4. If your PR contains large changes, e.g. component refactor or new components, please write detailed documents about its design and usage.
5. Note that a single PR should not be too large. If heavy changes are required, it's better to separate the changes to a few individual PRs.
6. After creating a PR, one or more reviewers will be assigned to the pull request.
7. Before merging a PR, squash any fix review feedback, typo, merged, and rebased sorts of commits. The final commit message should be clear and concise.
If your PR contains large changes, e.g. component refactor or new components, please write detailed documents about its design and usage.
### Code review guidance
Committers will rotate reviewing the code to make sure all the PR will be reviewed timely and by at least one committer before merge. If we aren't doing our job (sometimes we drop things). And as always, we welcome volunteers for code review.
Some principles:
- Readability - Important code should be well-documented. API should have Javadoc. Code style should be complied with the existing one.
- Elegance: New functions, classes or components should be well designed.
- Testability - 80% of the new code should be covered by unit test cases.
- Maintainability - Comply with our [PMD spec](style/codeStyle.xml), and 3-month-frequency update should be maintained at least.
### Now how about try become a committer?
Generally speaking, contribute 8 non-trivial patches and get at least three different people to review them (you'll need three people to support you). Then ask someone to nominate you. You're demonstrating your:
- at least 8 PR and the associated issues to the project,
- ability to collaborate with the team,
- understanding of the projects' code base and coding style, and
- ability to write good code (last but certainly not least)
A current committer nominates you by slacking the team on the Nacos issue with label "nomination"
- your first and last name
- a link to your Git profile
- an explanation of why you should be a committer,
- Elaborate the top 3 PR and the associated issues the nominator has worked with you that can demonstrate your ability.
Two other committer need to second your nomination. If no one objects in 5 working days (China), you're a committer. If anyone objects or wants more information, the committers discuss and usually come to a consensus (within the 5 working days). If issues cannot be resolved, there's a vote among current committers.
![](http://acm-public.oss-cn-hangzhou.aliyuncs.com/nomination_process.png)
In the worst case, this can drag out for two weeks. Keep contributing! Even in the rare cases where a nomination fails, the objection is usually something easy to address like "more patches" or "not enough people are familiar with this person's work."

View File

@ -1,12 +1,16 @@
## Nacos
<img src="doc/Nacos_Logo.png" width="50%" height="50%" />
# Nacos: Dynamic *Na*ming and *Co*nfiguration *S*ervice
[![Gitter](https://badges.gitter.im/alibaba/nacos.svg)](https://gitter.im/alibaba/nacos?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html)
[![Gitter](https://travis-ci.org/alibaba/nacos.svg?branch=master)](https://travis-ci.org/alibaba/nacos)
-------
<img src="doc/Nacos_Logo.png" width="50%" height="50%" />
Nacos is an easy-to-use platform designed for dynamic service discovery and configuration and service management. It helps you to build cloud native applications and microservices platform easily.
## What does it do
Nacos (official site: [http://nacos.io](http://nacos.io)) is an easy-to-use platform designed for dynamic service discovery and configuration and service management. It helps you to build cloud native applications and microservices platform easily.
Service is a first-class citizen in Nacos. Nacos supports almost all type of servicesfor example[Dubbo/gRPC service](https://nacos.io/en-us/docs/use-nacos-with-dubbo.html)、[Spring Cloud RESTFul service](https://nacos.io/en-us/docs/use-nacos-with-springcloud.html) or [Kubernetes service](https://nacos.io/en-us/docs/use-nacos-with-kubernetes.html).
@ -29,60 +33,70 @@ Nacos provides four major functions.
Nacos provides an easy-to-use service dashboard to help you manage your services metadata, configuration, kubernetes DNS, service health and metrics statistics.
### Quick Start
## Quick Start
It is super easy to get started with your first project.
1. #### Download run package
[Download](https://github.com/alibaba/nacos/releases/download/0.2.1/nacos-server-0.2.1.zip)
#### Step 1: Download the binary package
You can download the package from the [latest stable release](https://github.com/alibaba/nacos/releases).
Take release nacos-server-0.6.1.zip for example.
```
unzip nacos-server-0.2.1.zip
unzip nacos-server-0.6.1.zip
cd nacos/bin
```
2. #### Start Server
* ##### Linux/Unix/Mac
#### Step 2: Start Server
On the **Linux/Unix/Mac** platform, run the following command to start server with standalone mode:
```
Run the following command to start (standalone means non-cluster mode):
sh startup.sh -m standalone
```
* ##### Windows
On the **Windows** platform, run the following command to start server with standalone mode. Alternatively, you can also double-click the startup.cmd to run NacosServer.
```
Run the following command to start:
cmd startup.cmd
Or double-click the startup.cmd to run NacosServer.
cmd startup.cmd -m standalone
```
For more details, see [quick-start.](https://nacos.io/en-us/docs/quick-start.html)
3. #### Quick start for other open-source projects:
## Quick start for other open-source projects:
* [Quick start with Nacos command and console](https://nacos.io/en-us/docs/quick-start.html)
* [quick start with spring cloud](https://nacos.io/en-us/docs/use-nacos-with-springcloud.html)
* [Quick start with dubbo](https://nacos.io/en-us/docs/use-nacos-with-dubbo.html)
* [quick start with dubbo](https://nacos.io/en-us/docs/use-nacos-with-dubbo.html)
* [Quick start with spring cloud](https://nacos.io/en-us/docs/quick-start-spring-cloud.html)
* [quick start with kubernetes](https://nacos.io/en-us/docs/use-nacos-with-kubernetes.html)
* [Quick start with kubernetes](https://nacos.io/en-us/docs/use-nacos-with-kubernetes.html)
* [more...](https://nacos.io/)
### Documentation
## Documentation
You can view full documentation on the Nacos website:
You can view the full documentation from the [Nacos website](https://nacos.io/en-us/docs/what-is-nacos.html).
* [nacos.io](https://nacos.io/en-us/docs/what-is-nacos.html)
All the latest and long-term notice can also be found here from [Github notice issue](https://github.com/alibaba/nacos/labels/notice)
### Contact
* #### Gitter-[Nacos Gitter](https://gitter.im/alibaba/nacos)
## Contributing
* #### Weibo-[Nacos Weibo](https://weibo.com/u/6574374908)
Contributors are welcomed to join Nacos project. Please check [CONTRIBUTING](./CONTRIBUTING.md) about how to contribute to this project.
* #### Segmentfault-[Nacos Segmentfault](https://segmentfault.com/t/nacos)
## Other Related Project Repositories
* #### Mailing list-[nacos\_dev@linux.alibaba.com](mailto:nacos_dev@linux.alibaba.com).
* [nacos-spring-project](https://github.com/nacos-group/nacos-spring-project) provides the integration functionality for Spring.
* [nacos-group](https://github.com/nacos-group) is the reposity that hosts the eco tools for Nacos, such as SDK, synchronization tool, etc.
* [spring-cloud-alibaba](https://github.com/spring-cloud-incubator/spring-cloud-alibaba) provides the one-stop solution for application development over Alibaba middleware which includes Nacos.
## Contact
* [Gitter](https://gitter.im/alibaba/nacos): Nacos's IM tool for community messaging, collaboration and discovery.
* [Twitter](https://twitter.com/nacos2): Follow along for latest nacos news on Twitter.
* [Weibo](https://weibo.com/u/6574374908): Follow along for latest nacos news on Weibo (Twitter of China version).
* [Nacos Segmentfault](https://segmentfault.com/t/nacos): Get latest notice and prompt help from Segmentfault.
* Email Group:
* users-nacos@googlegroups.com: Nacos usage general discussion.
* dev-nacos@googlegroups.com: Nacos developer discussion (APIs, feature design, etc).
* commits-nacos@googlegroups.com: Commits notice, very high frequency.
* Join us from wechat. Welcome words: Nacos.
![cwex](http://acm-public.oss-cn-hangzhou.aliyuncs.com/xuc.png)

View File

@ -21,7 +21,7 @@ We might ask for further information to locate a bug. A duplicated bug report wi
# 如何提交错误报告
如果Nacos项目的任何部分存在问题或文档问题请通过[opening an issue][Nacos-issue]告诉我们。我们非常认真地对待错误和错误在产品面前没有不重要的问题。不过在创建错误报告之前请检查是否存在报告相同问题的issues。
如果Nacos项目的任何部分存在问题或文档问题请通过[opening an issue][Nacos-issue]告诉我们。我们非常认真地对待错误和缺陷在产品面前没有不重要的问题。不过在创建错误报告之前请检查是否存在报告相同问题的issues。
为了使错误报告准确且易于理解,请尝试创建以下错误报告:

View File

@ -16,7 +16,7 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.2.1</version>
<version>0.7.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -26,6 +26,18 @@
<name>nacos-api ${project.version}</name>
<url>http://maven.apache.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -36,6 +48,19 @@
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -31,7 +31,7 @@ import com.alibaba.nacos.api.naming.NamingService;
public class NacosFactory {
/**
* create config service
* Create config service
*
* @param properties init param
* @return config
@ -42,7 +42,7 @@ public class NacosFactory {
}
/**
* create config service
* Create config service
*
* @param serverAddr server list
* @return config
@ -53,7 +53,7 @@ public class NacosFactory {
}
/**
* create naming service
* Create naming service
*
* @param serverAddr server list
* @return Naming
@ -64,7 +64,7 @@ public class NacosFactory {
}
/**
* create naming service
* Create naming service
*
* @param properties init param
* @return Naming

View File

@ -38,4 +38,6 @@ public class PropertyKeyConst {
public final static String ENCODE = "encode";
public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart";
}

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*

View File

@ -13,41 +13,40 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.core;
package com.alibaba.nacos.api.cmdb.pojo;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.util.Map;
/**
* Unit test for simple App.
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
public class Entity {
private String type;
private String name;
private Map<String, String> labels;
public String getType() {
return type;
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
public void setType(String type) {
this.type = type;
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getLabels() {
return labels;
}
public void setLabels(Map<String, String> labels) {
this.labels = labels;
}
}

View File

@ -0,0 +1,50 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public class EntityEvent {
private EntityEventType type;
private String entityName;
private String entityType;
public EntityEventType getType() {
return type;
}
public void setType(EntityEventType type) {
this.type = type;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
public String getEntityType() {
return entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public enum EntityEventType {
/**
*
*/
ENTITY_ADD_OR_UPDATE,
/**
*
*/
ENTITY_REMOVE
}

View File

@ -0,0 +1,52 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
import java.util.Set;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public class Label {
private String name;
private Set<String> values;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getValues() {
return values;
}
public void setValues(Set<String> values) {
this.values = values;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.pojo;
/**
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public enum PreservedEntityTypes {
/**
* Ip
*/
ip,
/**
* Service
*/
service
}

View File

@ -0,0 +1,97 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.cmdb.spi;
import com.alibaba.nacos.api.cmdb.pojo.Entity;
import com.alibaba.nacos.api.cmdb.pojo.EntityEvent;
import com.alibaba.nacos.api.cmdb.pojo.Label;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Service to visit CMDB store
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public interface CmdbService {
/**
* Get all label names stored in CMDB
*
* @return label name set
*/
Set<String> getLabelNames();
/**
* Get all possible entity types in CMDB
*
* @return all entity types
*/
Set<String> getEntityTypes();
/**
* Get label info
*
* @param labelName label name
* @return label info
*/
Label getLabel(String labelName);
/**
* Get label value of label name of ip
*
* @param entityName entity name
* @param entityType entity type
* @param labelName target label name
* @return label value
*/
String getLabelValue(String entityName, String entityType, String labelName);
/**
* Get all label value of ip
*
* @param entityName entity name
* @param entityType entity type
* @return all label values
*/
Map<String, String> getLabelValues(String entityName, String entityType);
/**
* Dump all entities in CMDB
*
* @return all entities
*/
Map<String, Map<String, Entity>> getAllEntities();
/**
* get label change events
*
* @param timestamp start time of generated events
* @return label events
*/
List<EntityEvent> getEntityEvents(long timestamp);
/**
* Get single entity
*
* @param entityName name of entity
* @param entityType type of entity
* @return
*/
Entity getEntity(String entityName, String entityType);
}

View File

@ -85,11 +85,6 @@ public class Constants {
*/
public static final int ONCE_TIMEOUT = 2000;
/**
* millisecond
*/
public static final int CONN_TIMEOUT = 2000;
/**
* millisecond
*/
@ -110,9 +105,9 @@ public class Constants {
public static final int FLOW_CONTROL_INTERVAL = 1000;
public static final String LINE_SEPARATOR = Character.toString((char) 1);
public static final String LINE_SEPARATOR = Character.toString((char)1);
public static final String WORD_SEPARATOR = Character.toString((char) 2);
public static final String WORD_SEPARATOR = Character.toString((char)2);
public static final String LONGPULLING_LINE_SEPARATOR = "\r\n";
@ -124,4 +119,7 @@ public class Constants {
public static final String NAMING_INSTANCE_ID_SPLITTER = "#";
public static final int NAMING_INSTANCE_ID_SEG_COUNT = 4;
public static final String NAMING_HTTP_HEADER_SPILIER = "\\|";
public static final String NAMING_DEFAULT_CLUSTER_NAME = "DEFAULT";
}

View File

@ -29,7 +29,7 @@ import com.alibaba.nacos.api.exception.NacosException;
public class ConfigFactory {
/**
* create config service
* Create Config
*
* @param properties init param
* @return ConfigService
@ -47,11 +47,11 @@ public class ConfigFactory {
}
/**
* create config service
* Create Config
*
* @param serverAddr serverlist
* @return ConfigService
* @throws NacosException Exception
* @param serverAddr serverList
* @return Config
* @throws ConfigService Exception
*/
public static ConfigService createConfigService(String serverAddr) throws NacosException {
Properties properties = new Properties();

View File

@ -26,7 +26,7 @@ import com.alibaba.nacos.api.exception.NacosException;
public interface ConfigService {
/**
* get config
* Get config
*
* @param dataId dataId
* @param group group
@ -52,7 +52,7 @@ public interface ConfigService {
void addListener(String dataId, String group, Listener listener) throws NacosException;
/**
* publish config.
* Publish config.
*
* @param dataId dataId
* @param group group
@ -63,7 +63,7 @@ public interface ConfigService {
boolean publishConfig(String dataId, String group, String content) throws NacosException;
/**
* remove config
* Remove config
*
* @param dataId dataId
* @param group group
@ -73,7 +73,7 @@ public interface ConfigService {
boolean removeConfig(String dataId, String group) throws NacosException;
/**
* remove listener
* Remove listener
*
* @param dataId dataId
* @param group group
@ -82,7 +82,7 @@ public interface ConfigService {
void removeListener(String dataId, String group, Listener listener);
/**
* get server status
* Get server status
*
* @return whether health
*/

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -57,8 +56,7 @@ public @interface NacosConfigListener {
Class<? extends NacosConfigConverter> converter() default NacosConfigConverter.class;
/**
* The {@link NacosProperties} attribute, If not specified, it will use
* global Nacos Properties.
* The {@link NacosProperties} attribute, If not specified, it will use global Nacos Properties.
*
* @return the default value is {@link NacosProperties}
*/

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -24,7 +23,6 @@ import java.lang.annotation.*;
import static com.alibaba.nacos.api.common.Constants.DEFAULT_GROUP;
/**
* An annotation for Nacos configuration Properties for binding POJO as Properties Object.
*
@ -52,51 +50,46 @@ public @interface NacosConfigurationProperties {
String dataId();
/**
* It indicates the properties of current doBind bean is auto-refreshed
* when Nacos configuration is changed.
* It indicates the properties of current doBind bean is auto-refreshed when Nacos configuration is changed.
*
* @return default value is <code>false</code>
*/
boolean autoRefreshed() default false;
/**
* Flag to indicate that when binding to this object invalid fields should be ignored.
* Invalid means invalid according to the binder that is used, and usually this means
* fields of the wrong type (or that cannot be coerced into the correct type).
* Flag to indicate that when binding to this object invalid fields should be ignored. Invalid means invalid
* according to the binder that is used, and usually this means fields of the wrong type (or that cannot be coerced
* into the correct type).
*
* @return the flag value (default false)
*/
boolean ignoreInvalidFields() default false;
/**
* Flag to indicate that when binding to this object fields with periods in their
* names should be ignored.
* Flag to indicate that when binding to this object fields with periods in their names should be ignored.
*
* @return the flag value (default false)
*/
boolean ignoreNestedProperties() default false;
/**
* Flag to indicate that when binding to this object unknown fields should be ignored.
* An unknown field could be a sign of a mistake in the Properties.
* Flag to indicate that when binding to this object unknown fields should be ignored. An unknown field could be a
* sign of a mistake in the Properties.
*
* @return the flag value (default true)
*/
boolean ignoreUnknownFields() default true;
/**
* Flag to indicate that an exception should be raised if a Validator is available and
* validation fails. If it is set to false, validation errors will be swallowed. They
* will be logged, but not propagated to the caller.
* Flag to indicate that an exception should be raised if a Validator is available and validation fails. If it is
* set to false, validation errors will be swallowed. They will be logged, but not propagated to the caller.
*
* @return the flag value (default true)
*/
boolean exceptionIfInvalid() default true;
/**
* The {@link NacosProperties} attribute, If not specified, it will use
* global Nacos Properties.
* The {@link NacosProperties} attribute, If not specified, it will use global Nacos Properties.
*
* @return the default value is {@link NacosProperties}
*/

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -19,8 +18,7 @@ package com.alibaba.nacos.api.config.annotation;
import java.lang.annotation.*;
/**
* An annotation for ignore field from annotated
* {@link NacosConfigurationProperties} Properties Object.
* An annotation for ignore field from annotated {@link NacosConfigurationProperties} Properties Object.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see NacosConfigurationProperties

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -19,9 +18,8 @@ package com.alibaba.nacos.api.config.annotation;
import java.lang.annotation.*;
/**
* An annotation for Nacos Property name of Nacos Configuration to
* bind a field from annotated {@link NacosConfigurationProperties}
* Properties Object.
* An annotation for Nacos Property name of Nacos Configuration to bind a field from annotated {@link
* NacosConfigurationProperties} Properties Object.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @see NacosConfigurationProperties

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@ -41,5 +40,4 @@ public interface NacosConfigConverter<T> {
*/
T convert(String config);
}

View File

@ -22,7 +22,7 @@ package com.alibaba.nacos.api.config.filter;
*/
public interface IConfigContext {
/**
* get context param by key
* Get context param by key
*
* @param key
* @return context
@ -30,7 +30,7 @@ public interface IConfigContext {
Object getParameter(String key);
/**
* set context param
* Set context param
*
* @param key key
* @param value value

View File

@ -24,7 +24,7 @@ import com.alibaba.nacos.api.exception.NacosException;
*/
public interface IConfigFilter {
/**
* init
* Init
*
* @param filterConfig Filter Config
*/
@ -47,14 +47,14 @@ public interface IConfigFilter {
void deploy();
/**
* get order
* Get order
*
* @return order number
*/
int getOrder();
/**
* get filterName
* Get filterName
*
* @return filter name
*/

View File

@ -24,7 +24,7 @@ import com.alibaba.nacos.api.exception.NacosException;
*/
public interface IConfigFilterChain {
/**
* filter aciton
* Filter aciton
*
* @param request request
* @param response response

View File

@ -30,7 +30,7 @@ public interface IConfigResponse {
Object getParameter(String key);
/**
* get config context
* Get config context
*
* @return configContext
*/

View File

@ -30,7 +30,7 @@ public interface IFilterConfig {
String getFilterName();
/**
* get init param
* Get init param
*
* @param name
* @return param

View File

@ -26,7 +26,7 @@ import java.util.concurrent.Executor;
public abstract class AbstractListener implements Listener {
/**
* use default executor
* Use default executor
*/
@Override
public Executor getExecutor() {

View File

@ -17,7 +17,6 @@ package com.alibaba.nacos.api.config.listener;
import java.util.concurrent.Executor;
/**
* Listener for watch config
*
@ -26,15 +25,14 @@ import java.util.concurrent.Executor;
public interface Listener {
/**
* get executor for execute this receive
* Get executor for execute this receive
*
* @return Executor
*/
Executor getExecutor();
/**
* receive config info
* Receive config info
*
* @param configInfo config info
*/

View File

@ -75,7 +75,6 @@ public class NacosException extends Exception {
*/
public static final int CLIENT_OVER_THRESHOLD = -503;
/**
* server error code
* 400 403 throw exception to user
@ -107,5 +106,4 @@ public class NacosException extends Exception {
*/
public static final int OVER_THRESHOLD = 503;
}

View File

@ -31,7 +31,7 @@ public class NamingFactory {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
Constructor constructor = driverImplClass.getConstructor(String.class);
NamingService vendorImpl = (NamingService) constructor.newInstance(serverList);
NamingService vendorImpl = (NamingService)constructor.newInstance(serverList);
return vendorImpl;
} catch (Throwable e) {
throw new NacosException(-400, e.getMessage());
@ -42,7 +42,7 @@ public class NamingFactory {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
NamingService vendorImpl = (NamingService) constructor.newInstance(properties);
NamingService vendorImpl = (NamingService)constructor.newInstance(properties);
return vendorImpl;
} catch (Throwable e) {
throw new NacosException(-400, e.getMessage());

View File

@ -20,6 +20,7 @@ import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.List;
@ -189,7 +190,22 @@ public interface NamingService {
ListView<String> getServicesOfServer(int pageNo, int pageSize) throws NacosException;
/**
<<<<<<< HEAD
* get all subscribed services of current client
=======
* Get all service names from server
*
* @param pageNo page index
* @param pageSize page size
* @param selector selector to filter the resource
* @return list of service names
* @throws NacosException
*/
ListView<String> getServicesOfServer(int pageNo, int pageSize, AbstractSelector selector) throws NacosException;
/**
* Get all subscribed services of current client
>>>>>>> upstream/develop
*
* @return subscribed services
* @throws NacosException

View File

@ -15,10 +15,17 @@
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.nacos.api.common.Constants;
import org.apache.commons.lang3.StringUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author dungu.zpf
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public abstract class AbstractHealthChecker implements Cloneable {
@ -32,6 +39,14 @@ public abstract class AbstractHealthChecker implements Cloneable {
this.type = type;
}
/**
* Clone all fields of this instance to another one
*
* @return Another instance with exactly the same fields.
* @throws CloneNotSupportedException
*/
public abstract AbstractHealthChecker clone() throws CloneNotSupportedException;
public static class Http extends AbstractHealthChecker {
public static final String TYPE = "HTTP";
@ -68,6 +83,25 @@ public abstract class AbstractHealthChecker implements Cloneable {
this.headers = headers;
}
@JSONField(serialize = false)
public Map<String, String> getCustomHeaders() {
if (StringUtils.isBlank(headers)) {
return Collections.emptyMap();
}
Map<String, String> headerMap = new HashMap<String, String>(16);
for (String s : headers.split(Constants.NAMING_HTTP_HEADER_SPILIER)) {
String[] splits = s.split(":");
if (splits.length != 2) {
continue;
}
headerMap.put(StringUtils.trim(splits[0]), StringUtils.trim(splits[1]));
}
return headerMap;
}
@Override
public int hashCode() {
return Objects.hash(path, headers, expectedResponseCode);
@ -79,7 +113,7 @@ public abstract class AbstractHealthChecker implements Cloneable {
return false;
}
Http other = (Http) obj;
Http other = (Http)obj;
if (!strEquals(type, other.getType())) {
return false;
@ -93,6 +127,18 @@ public abstract class AbstractHealthChecker implements Cloneable {
}
return expectedResponseCode == other.getExpectedResponseCode();
}
@Override
public Http clone() throws CloneNotSupportedException {
Http config = new Http();
config.setPath(this.getPath());
config.setHeaders(this.getHeaders());
config.setType(this.getType());
config.setExpectedResponseCode(this.getExpectedResponseCode());
return config;
}
}
public static class Tcp extends AbstractHealthChecker {
@ -112,6 +158,12 @@ public abstract class AbstractHealthChecker implements Cloneable {
return obj instanceof Tcp;
}
public Tcp clone() throws CloneNotSupportedException {
Tcp config = new Tcp();
config.setType(this.type);
return config;
}
}
public static class Mysql extends AbstractHealthChecker {
@ -160,7 +212,7 @@ public abstract class AbstractHealthChecker implements Cloneable {
return false;
}
Mysql other = (Mysql) obj;
Mysql other = (Mysql)obj;
if (!strEquals(user, other.getUser())) {
return false;
@ -173,6 +225,17 @@ public abstract class AbstractHealthChecker implements Cloneable {
return strEquals(cmd, other.getCmd());
}
@Override
public Mysql clone() throws CloneNotSupportedException {
Mysql config = new Mysql();
config.setUser(this.getUser());
config.setPwd(this.getPwd());
config.setCmd(this.getCmd());
config.setType(this.getType());
return config;
}
}
private static boolean strEquals(String str1, String str2) {

View File

@ -19,6 +19,7 @@ import java.util.HashMap;
import java.util.Map;
/**
<<<<<<< HEAD
*
*
* @author dungu.zpf
@ -33,7 +34,7 @@ public class Cluster {
/**
* Name of cluster
*/
private String name = "";
private String name;
/**
* Health check config of this cluster
@ -55,7 +56,6 @@ public class Cluster {
*/
private boolean useIPPort4Check = true;
private Map<String, String> metadata = new HashMap<String, String>();
public Cluster() {

View File

@ -17,7 +17,6 @@ package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.nacos.api.common.Constants;
import java.util.HashMap;
import java.util.Map;
@ -55,17 +54,17 @@ public class Instance {
@JSONField(name = "valid")
private boolean healthy = true;
private boolean enabled = true;
/**
* cluster information of instance
*/
@JSONField(serialize = false)
private Cluster cluster = new Cluster();
private String clusterName;
/**
* service information of instance
* Service information of instance
*/
@JSONField(serialize = false)
private Service service;
private String serviceName;
/**
* user extended attributes
@ -80,14 +79,6 @@ public class Instance {
this.instanceId = instanceId;
}
public String serviceName() {
String[] infos = instanceId.split(Constants.NAMING_INSTANCE_ID_SPLITTER);
if (infos.length < Constants.NAMING_INSTANCE_ID_SEG_COUNT) {
return null;
}
return infos[Constants.NAMING_INSTANCE_ID_SEG_COUNT - 1];
}
public String getIp() {
return ip;
}
@ -120,20 +111,20 @@ public class Instance {
this.healthy = healthy;
}
public Cluster getCluster() {
return cluster;
public String getClusterName() {
return clusterName;
}
public void setCluster(Cluster cluster) {
this.cluster = cluster;
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public Service getService() {
return service;
public String getServiceName() {
return serviceName;
}
public void setService(Service service) {
this.service = service;
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public Map<String, String> getMetadata() {
@ -148,6 +139,14 @@ public class Instance {
this.metadata.put(key, value);
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return JSON.toJSONString(this);
@ -163,7 +162,7 @@ public class Instance {
return false;
}
Instance host = (Instance) obj;
Instance host = (Instance)obj;
return strEquals(toString(), host.toString());
}

View File

@ -15,6 +15,8 @@
*/
package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.nacos.api.selector.AbstractSelector;
import java.util.HashMap;
import java.util.Map;
@ -41,21 +43,26 @@ public class Service {
private String app;
/**
* service group which is meant to classify services into different sets.
* Service group which is meant to classify services into different sets.
*/
private String group;
/**
* health check mode.
* Health check mode.
*/
private String healthCheckMode;
/**
* Selector name of this service
*/
private AbstractSelector selector;
private Map<String, String> metadata = new HashMap<String, String>();
public Service(String name) {
this.name = name;
}
private Map<String, String> metadata = new HashMap<String, String>();
public String getName() {
return name;
}
@ -107,4 +114,12 @@ public class Service {
public void addMetadata(String key, String value) {
this.metadata.put(key, value);
}
public AbstractSelector getSelector() {
return selector;
}
public void setSelector(AbstractSelector selector) {
this.selector = selector;
}
}

View File

@ -17,6 +17,8 @@ package com.alibaba.nacos.api.naming.pojo;
import com.alibaba.fastjson.annotation.JSONField;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@ -193,6 +195,15 @@ public class ServiceInfo {
return getKey(name, clusters, env, isAllIPs());
}
@JSONField(serialize = false)
public String getKeyEncoded() {
try {
return getKey(URLEncoder.encode(name, "UTF-8"), clusters, env, isAllIPs());
} catch (UnsupportedEncodingException e) {
return getKey();
}
}
@JSONField(serialize = false)
public static String getKey(String name, String clusters, String unit) {
return getKey(name, clusters, unit, false);

View File

@ -0,0 +1,37 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.selector;
/**
* Abstract selector that only contains a type
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public abstract class AbstractSelector {
/**
* The type of this selector, each child class should announce its own unique type.
*/
private String type;
public String getType() {
return type;
}
protected void setType(String type) {
this.type = type;
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.selector;
/**
* The selector to filter resource with flexible expression.
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public class ExpressionSelector extends AbstractSelector {
/**
* Label expression of this selector.
*/
private String expression;
public ExpressionSelector() {
this.setType(SelectorType.label.name());
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.api.selector;
/**
* The types of selector accepted by Nacos
*
* @author <a href="mailto:zpf.073@gmail.com">nkorange</a>
*/
public enum SelectorType {
/**
* not match any type
*/
unknown,
/**
* not filter out any entity
*/
none,
/**
* select by label
*/
label
}

View File

@ -1,10 +1,9 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*

View File

@ -16,7 +16,8 @@
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>0.2.1</version>
<version>0.7.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -32,67 +33,46 @@
</properties>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-common</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-api</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
@ -114,11 +94,18 @@
<artifactId>jcip-annotations</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -44,8 +44,8 @@ import java.util.Properties;
/**
* Config Impl
* @author Nacos
*
* @author Nacos
*/
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
public class NacosConfigService implements ConfigService {

View File

@ -18,8 +18,7 @@ package com.alibaba.nacos.client.config.common;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId
* and groupId.
* Synthesize the form of dataId+groupId. Escapes reserved characters in dataId and groupId.
*
* @author Nacos
*/
@ -100,12 +99,11 @@ public class GroupKey {
}
}
return new String[] { dataId, group, tenant };
return new String[] {dataId, group, tenant};
}
/**
* + -> %2B
* % -> %25
* + -> %2B % -> %25
*/
static void urlEncode(String str, StringBuilder sb) {
for (int idx = 0; idx < str.length(); ++idx) {

View File

@ -24,7 +24,6 @@ import com.alibaba.nacos.api.config.filter.IConfigContext;
* Config Context
*
* @author Nacos
*
*/
public class ConfigContext implements IConfigContext {

View File

@ -28,7 +28,6 @@ import com.google.common.collect.Lists;
* Config Filter Chain Management
*
* @author Nacos
*
*/
public class ConfigFilterChainManager implements IConfigFilterChain {
@ -56,7 +55,6 @@ public class ConfigFilterChainManager implements IConfigFilterChain {
return this;
}
@Override
public void doFilter(IConfigRequest request, IConfigResponse response) throws NacosException {
new VirtualFilterChain(this.filters).doFilter(request, response);

View File

@ -25,7 +25,6 @@ import com.alibaba.nacos.api.config.filter.IConfigRequest;
* Config Request
*
* @author Nacos
*
*/
public class ConfigRequest implements IConfigRequest {
@ -34,7 +33,7 @@ public class ConfigRequest implements IConfigRequest {
private IConfigContext configContext = new ConfigContext();
public String getTenant() {
return (String) param.get("tenant");
return (String)param.get("tenant");
}
public void setTenant(String tenant) {
@ -42,7 +41,7 @@ public class ConfigRequest implements IConfigRequest {
}
public String getDataId() {
return (String) param.get("dataId");
return (String)param.get("dataId");
}
public void setDataId(String dataId) {
@ -50,7 +49,7 @@ public class ConfigRequest implements IConfigRequest {
}
public String getGroup() {
return (String) param.get("group");
return (String)param.get("group");
}
public void setGroup(String group) {
@ -58,7 +57,7 @@ public class ConfigRequest implements IConfigRequest {
}
public String getContent() {
return (String) param.get("content");
return (String)param.get("content");
}
public void setContent(String content) {

View File

@ -25,7 +25,6 @@ import com.alibaba.nacos.api.config.filter.IConfigResponse;
* Config Response
*
* @author Nacos
*
*/
public class ConfigResponse implements IConfigResponse {
@ -34,7 +33,7 @@ public class ConfigResponse implements IConfigResponse {
private IConfigContext configContext = new ConfigContext();
public String getTenant() {
return (String) param.get("tenant");
return (String)param.get("tenant");
}
public void setTenant(String tenant) {
@ -42,7 +41,7 @@ public class ConfigResponse implements IConfigResponse {
}
public String getDataId() {
return (String) param.get("dataId");
return (String)param.get("dataId");
}
public void setDataId(String dataId) {
@ -50,7 +49,7 @@ public class ConfigResponse implements IConfigResponse {
}
public String getGroup() {
return (String) param.get("group");
return (String)param.get("group");
}
public void setGroup(String group) {
@ -58,7 +57,7 @@ public class ConfigResponse implements IConfigResponse {
}
public String getContent() {
return (String) param.get("content");
return (String)param.get("content");
}
public void setContent(String content) {

View File

@ -34,7 +34,6 @@ import java.util.concurrent.CopyOnWriteArrayList;
* Listner Management
*
* @author Nacos
*
*/
public class CacheData {
@ -68,8 +67,7 @@ public class CacheData {
/**
* Add listener
*
* @param listener
* listener
* @param listener listener
*/
public void addListener(Listener listener) {
if (null == listener) {
@ -103,18 +101,18 @@ public class CacheData {
return result;
}
public long getLocalConfigInfoVersion() {
return localConfigLastModified;
}
public void setLocalConfigInfoVersion(long localConfigLastModified) {
this.localConfigLastModified = localConfigLastModified;
}
public boolean isUseLocalConfigInfo() {
return isUseLocalConfig;
}
public void setUseLocalConfigInfo(boolean useLocalConfigInfo) {
this.isUseLocalConfig = useLocalConfigInfo;
if (!useLocalConfigInfo) {
@ -147,7 +145,7 @@ public class CacheData {
if (this == obj) {
return true;
}
CacheData other = (CacheData) obj;
CacheData other = (CacheData)obj;
return dataId.equals(other.dataId) && group.equals(other.group);
}
@ -171,10 +169,10 @@ public class CacheData {
Runnable job = new Runnable() {
public void run() {
ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader appClassLoader= listener.getClass().getClassLoader();
ClassLoader appClassLoader = listener.getClass().getClassLoader();
try {
if(listener instanceof AbstractSharedListener){
AbstractSharedListener adapter = (AbstractSharedListener) listener;
if (listener instanceof AbstractSharedListener) {
AbstractSharedListener adapter = (AbstractSharedListener)listener;
adapter.fillContext(dataId, group);
log.info(name, "[notify-context] dataId={}, group={}, md5={}", dataId, group, md5);
}
@ -201,9 +199,7 @@ public class CacheData {
log.error(name, "NACOS-XXXX",
"[notify-error] dataId={}, group={}, md5={}, listener={} tx={}", dataId, group, md5,
listener, t.getCause());
}
finally
{
} finally {
Thread.currentThread().setContextClassLoader(myClassLoader);
}
}
@ -224,7 +220,8 @@ public class CacheData {
dataId, group, md5, listener, t.getCause());
}
final long finishNotify = System.currentTimeMillis();
log.info(name, "[notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",(finishNotify - startNotify), dataId ,group, md5, listener);
log.info(name, "[notify-listener] time cost={}ms in ClientWorker, dataId={}, group={}, md5={}, listener={} ",
(finishNotify - startNotify), dataId, group, md5, listener);
}
static public String getMd5String(String config) {
@ -253,7 +250,8 @@ public class CacheData {
this.md5 = getMd5String(content);
}
public CacheData(ConfigFilterChainManager configFilterChainManager, String name, String dataId, String group, String tenant) {
public CacheData(ConfigFilterChainManager configFilterChainManager, String name, String dataId, String group,
String tenant) {
if (null == dataId || null == group) {
throw new IllegalArgumentException("dataId=" + dataId + ", group=" + group);
}
@ -307,7 +305,7 @@ class ManagerListenerWrap {
if (obj == this) {
return true;
}
ManagerListenerWrap other = (ManagerListenerWrap) obj;
ManagerListenerWrap other = (ManagerListenerWrap)obj;
return listener.equals(other.listener);
}

View File

@ -46,7 +46,6 @@ import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR;
* Longpulling
*
* @author Nacos
*
*/
public class ClientWorker {
@ -128,12 +127,12 @@ public class ClientWorker {
CacheData cacheFromMap = getCache(dataId, group);
// multiple listeners on the same dataid+group and race condition,so double check again
//other listener thread beat me to set to cacheMap
if(null != cacheFromMap) {
if (null != cacheFromMap) {
cache = cacheFromMap;
//reset so that server not hang this check
cache.setInitializing(true);
} else {
int taskId = cacheMap.get().size() / (int) ParamUtil.getPerTaskConfigSize();
int taskId = cacheMap.get().size() / (int)ParamUtil.getPerTaskConfigSize();
cache.setTaskId(taskId);
}
@ -146,6 +145,7 @@ public class ClientWorker {
return cache;
}
@SuppressFBWarnings("JLM_JSR166_UTILCONCURRENT_MONITORENTER")
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) {
CacheData cache = getCache(dataId, group, tenant);
@ -184,7 +184,6 @@ public class ClientWorker {
return cacheMap.get().get(GroupKey.getKeyTenant(dataId, group, tenant));
}
public String getServerConfig(String dataId, String group, String tenant, long readTimeout)
throws NacosException {
if (StringUtils.isBlank(group)) {
@ -286,9 +285,9 @@ public class ClientWorker {
// 分任务
int listenerSize = cacheMap.get().size();
// 向上取整为批数
int longingTaskCount = (int) Math.ceil(listenerSize / ParamUtil.getPerTaskConfigSize());
int longingTaskCount = (int)Math.ceil(listenerSize / ParamUtil.getPerTaskConfigSize());
if (longingTaskCount > currentLongingTaskCount) {
for (int i = (int) currentLongingTaskCount; i < longingTaskCount; i++) {
for (int i = (int)currentLongingTaskCount; i < longingTaskCount; i++) {
// 要判断任务是否在执行 这块需要好好想想 任务列表现在是无序的变化过程可能有问题
executorService.execute(new LongPullingRunnable(i));
}
@ -521,7 +520,8 @@ public class ClientWorker {
/**
* groupKey -> cacheData
*/
AtomicReference<Map<String, CacheData>> cacheMap = new AtomicReference<Map<String, CacheData>>(new HashMap<String, CacheData>());
AtomicReference<Map<String, CacheData>> cacheMap = new AtomicReference<Map<String, CacheData>>(
new HashMap<String, CacheData>());
ServerHttpAgent agent;
ConfigFilterChainManager configFilterChainManager;
private boolean isHealthServer = true;

View File

@ -24,12 +24,10 @@ import java.util.concurrent.CopyOnWriteArrayList;
import com.alibaba.nacos.client.config.utils.LogUtils;
import com.alibaba.nacos.client.logger.Logger;
/**
* Event subscription and publishing tools.
*
* @author Nacos
*
*/
public class EventDispatcher {
@ -85,7 +83,8 @@ public class EventDispatcher {
// ========================
static final Map<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>> LISTENER_MAP = new HashMap<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>>();
static final Map<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>> LISTENER_MAP
= new HashMap<Class<? extends AbstractEvent>, CopyOnWriteArrayList<AbstractEventListener>>();
// ========================
@ -120,6 +119,7 @@ public class EventDispatcher {
/**
* 处理事件
*
* @param abstractEvent event to do
*/
abstract public void onEvent(AbstractEvent abstractEvent);

View File

@ -20,7 +20,7 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.config.utils.MD5;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.common.util.UuidUtil;
import com.alibaba.nacos.common.util.UuidUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@ -40,9 +40,8 @@ import java.util.Map;
*/
public class HttpSimpleClient {
static public HttpResult httpGet(String url, List<String> headers, List<String> paramValues,
String encoding, long readTimeoutMs, boolean isSSL) throws IOException{
String encoding, long readTimeoutMs, boolean isSSL) throws IOException {
String encodedContent = encodingParams(paramValues, encoding);
url += (null == encodedContent) ? "" : ("?" + encodedContent);
if (Limiter.isLimit(MD5.getInstance().getMD5String(
@ -54,10 +53,10 @@ public class HttpSimpleClient {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
conn.setReadTimeout((int) readTimeoutMs);
conn.setReadTimeout((int)readTimeoutMs);
List<String> newHeaders = getHeaders(url, headers, paramValues);
setHeaders(conn, newHeaders, encoding);
@ -79,7 +78,6 @@ public class HttpSimpleClient {
}
}
/**
* 发送GET请求
*/
@ -92,16 +90,11 @@ public class HttpSimpleClient {
* 发送POST请求
*
* @param url
* @param headers
* 请求Header可以为null
* @param paramValues
* 参数可以为null
* @param encoding
* URL编码使用的字符集
* @param readTimeoutMs
* 响应超时
* @param isSSL
* 是否https
* @param headers 请求Header可以为null
* @param paramValues 参数可以为null
* @param encoding URL编码使用的字符集
* @param readTimeoutMs 响应超时
* @param isSSL 是否https
* @return
* @throws IOException
*/
@ -115,10 +108,10 @@ public class HttpSimpleClient {
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 3000 ? ParamUtil.getConnectTimeout() : 3000);
conn.setReadTimeout((int) readTimeoutMs);
conn.setReadTimeout((int)readTimeoutMs);
conn.setDoOutput(true);
conn.setDoInput(true);
List<String> newHeaders = getHeaders(url, headers, paramValues);
@ -146,14 +139,10 @@ public class HttpSimpleClient {
* 发送POST请求
*
* @param url
* @param headers
* 请求Header可以为null
* @param paramValues
* 参数可以为null
* @param encoding
* URL编码使用的字符集
* @param readTimeoutMs
* 响应超时
* @param headers 请求Header可以为null
* @param paramValues 参数可以为null
* @param encoding URL编码使用的字符集
* @param readTimeoutMs 响应超时
* @return
* @throws IOException
*/
@ -162,9 +151,8 @@ public class HttpSimpleClient {
return httpPost(url, headers, paramValues, encoding, readTimeoutMs, false);
}
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues,
String encoding, long readTimeoutMs, boolean isSSL) throws IOException{
String encoding, long readTimeoutMs, boolean isSSL) throws IOException {
String encodedContent = encodingParams(paramValues, encoding);
url += (null == encodedContent) ? "" : ("?" + encodedContent);
if (Limiter.isLimit(MD5.getInstance().getMD5String(
@ -176,10 +164,10 @@ public class HttpSimpleClient {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
conn = (HttpURLConnection)new URL(url).openConnection();
conn.setRequestMethod("DELETE");
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
conn.setReadTimeout((int) readTimeoutMs);
conn.setReadTimeout((int)readTimeoutMs);
List<String> newHeaders = getHeaders(url, headers, paramValues);
setHeaders(conn, newHeaders, encoding);
@ -201,7 +189,6 @@ public class HttpSimpleClient {
}
}
static public HttpResult httpDelete(String url, List<String> headers, List<String> paramValues, String encoding,
long readTimeoutMs) throws IOException {
return httpGet(url, headers, paramValues, encoding, readTimeoutMs, false);
@ -209,7 +196,7 @@ public class HttpSimpleClient {
static private void setHeaders(HttpURLConnection conn, List<String> headers, String encoding) {
if (null != headers) {
for (Iterator<String> iter = headers.iterator(); iter.hasNext();) {
for (Iterator<String> iter = headers.iterator(); iter.hasNext(); ) {
conn.addRequestProperty(iter.next(), iter.next());
}
}
@ -230,8 +217,8 @@ public class HttpSimpleClient {
newHeaders.add("exConfigInfo");
newHeaders.add("true");
newHeaders.add("RequestId");
newHeaders.add(UuidUtil.generateUuid());
if (headers!=null) {
newHeaders.add(UuidUtils.generateUuid());
if (headers != null) {
newHeaders.addAll(headers);
}
return newHeaders;
@ -244,7 +231,7 @@ public class HttpSimpleClient {
return null;
}
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) {
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext(); ) {
sb.append(iter.next()).append("=");
sb.append(URLEncoder.encode(iter.next(), encoding));
if (iter.hasNext()) {
@ -256,7 +243,7 @@ public class HttpSimpleClient {
static public class HttpResult {
final public int code;
final public Map<String,List<String>> headers;
final public Map<String, List<String>> headers;
final public String content;
public HttpResult(int code, String content) {

View File

@ -29,7 +29,6 @@ import com.google.common.util.concurrent.RateLimiter;
* Limiter
*
* @author Nacos
*
*/
public class Limiter {

View File

@ -25,7 +25,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Local Disaster Recovery Directory Tool
*
@ -44,7 +43,7 @@ public class LocalConfigInfoProcessor {
try {
return readFile(localPath);
} catch (IOException ioe) {
log.error(serverName, "NACOS-XXXX","get failover error, " + localPath + ioe.toString());
log.error(serverName, "NACOS-XXXX", "get failover error, " + localPath + ioe.toString());
return null;
}
}
@ -64,7 +63,7 @@ public class LocalConfigInfoProcessor {
try {
return readFile(file);
} catch (IOException ioe) {
log.error(name, "NACOS-XXXX","get snapshot error, " + file + ", " + ioe.toString());
log.error(name, "NACOS-XXXX", "get snapshot error, " + file + ", " + ioe.toString());
return null;
}
}
@ -92,7 +91,6 @@ public class LocalConfigInfoProcessor {
}
}
static public void saveSnapshot(String envName, String dataId, String group, String tenant, String config) {
if (!SnapShotSwitch.getIsSnapShot()) {
return;
@ -102,14 +100,18 @@ public class LocalConfigInfoProcessor {
try {
IOUtils.delete(file);
} catch (IOException ioe) {
log.error(envName, "NACOS-XXXX","delete snapshot error, " + file + ", " + ioe.toString());
log.error(envName, "NACOS-XXXX", "delete snapshot error, " + file + ", " + ioe.toString());
}
} else {
try {
boolean isMdOk = file.getParentFile().mkdirs();
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
boolean isMdOk = parentFile.mkdirs();
if (!isMdOk) {
log.error(envName, "NACOS-XXXX", "save snapshot error");
}
}
if (JVMUtil.isMultiInstance()) {
ConcurrentDiskUtil.writeFileContent(file, config,
Constants.ENCODE);
@ -117,7 +119,7 @@ public class LocalConfigInfoProcessor {
IOUtils.writeStringToFile(file, config, Constants.ENCODE);
}
} catch (IOException ioe) {
log.error(envName, "NACOS-XXXX","save snapshot error, " + file + ", " + ioe.toString());
log.error(envName, "NACOS-XXXX", "save snapshot error, " + file + ", " + ioe.toString());
}
}
}
@ -132,36 +134,34 @@ public class LocalConfigInfoProcessor {
if (files == null || files.length == 0) {
return;
}
for(File file : files){
if(file.getName().endsWith("_nacos")){
for (File file : files) {
if (file.getName().endsWith("_nacos")) {
IOUtils.cleanDirectory(file);
}
}
} catch (IOException ioe) {
log.error("NACOS-XXXX","clean all snapshot error, " + ioe.toString(), ioe);
log.error("NACOS-XXXX", "clean all snapshot error, " + ioe.toString(), ioe);
}
}
static public void cleanEnvSnapshot(String envName){
static public void cleanEnvSnapshot(String envName) {
File tmp = new File(LOCAL_SNAPSHOT_PATH, envName + "_nacos");
tmp = new File(tmp, "snapshot");
try {
IOUtils.cleanDirectory(tmp);
log.info("success dlelet " + envName + "-snapshot");
log.info("success delete " + envName + "-snapshot");
} catch (IOException e) {
log.info("fail dlelet " + envName + "-snapshot, " + e.toString());
log.info("fail delete " + envName + "-snapshot, " + e.toString());
e.printStackTrace();
}
}
static File getFailoverFile(String serverName, String dataId, String group, String tenant) {
File tmp = new File(LOCAL_SNAPSHOT_PATH, serverName + "_nacos");
tmp = new File(tmp, "data");
if (StringUtils.isBlank(tenant)) {
tmp = new File(tmp, "config-data");
} else
{
} else {
tmp = new File(tmp, "config-data-tenant");
tmp = new File(tmp, tenant);
}
@ -182,6 +182,7 @@ public class LocalConfigInfoProcessor {
public static final String LOCAL_FILEROOT_PATH;
public static final String LOCAL_SNAPSHOT_PATH;
static {
LOCAL_FILEROOT_PATH = System.getProperty("JM.LOG.PATH", System.getProperty("user.home")) + File.separator
+ "nacos" + File.separator + "config";

View File

@ -44,14 +44,13 @@ import java.util.Properties;
* Server Agent
*
* @author water.lyl
*
*/
public class ServerHttpAgent {
final static public Logger log = LogUtils.logger(ServerHttpAgent.class);
/**
* @param path
* 相对于web应用根/开头
* @param path 相对于web应用根/开头
* @param headers
* @param paramValues
* @param encoding
@ -78,21 +77,21 @@ public class ServerHttpAgent {
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr() });
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
throw ioe;
}
} while (System.currentTimeMillis() <= endTime);
@ -119,21 +118,21 @@ public class ServerHttpAgent {
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
throw ioe;
}
@ -161,21 +160,21 @@ public class ServerHttpAgent {
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
log.error("NACOS ConnectException", "currentServerAddr:{}. httpCode:",
new Object[] { serverListMgr.getCurrentServerAddr(), result.code });
new Object[] {serverListMgr.getCurrentServerAddr(), result.code});
} else {
return result;
}
} catch (ConnectException ce) {
log.error("NACOS ConnectException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (SocketTimeoutException stoe) {
log.error("NACOS SocketTimeoutException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
serverListMgr.refreshCurrentServerAddr();
} catch (IOException ioe) {
log.error("NACOS IOException", "currentServerAddr:{}",
new Object[] { serverListMgr.getCurrentServerAddr()});
new Object[] {serverListMgr.getCurrentServerAddr()});
throw ioe;
}
@ -321,7 +320,8 @@ public class ServerHttpAgent {
}
log.error(respCode + "", "can not get security credentials, securityCredentialsUrl:{}, response:{}",
new Object[] {securityCredentialsUrl, response});
throw new IOException("can not get security credentials, responseCode: " + respCode + ", response: " + response);
throw new IOException(
"can not get security credentials, responseCode: " + respCode + ", response: " + response);
}
public String getName() {
@ -331,6 +331,7 @@ public class ServerHttpAgent {
public String getNamespace() {
return serverListMgr.getNamespace();
}
public String getTenant() {
return serverListMgr.getTenant();
}

View File

@ -40,7 +40,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Serverlist Manager
*
@ -49,6 +48,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
public class ServerListManager {
final static public Logger log = LogUtils.logger(ServerListManager.class);
public ServerListManager() {
isFixed = false;
isStarted = false;
@ -209,7 +209,6 @@ public class ServerListManager {
return new ServerAddressIterator(serverUrls);
}
class GetServerListTask implements Runnable {
final String url;
@ -225,7 +224,8 @@ public class ServerListManager {
try {
updateIfChanged(getApacheServerList(url, name));
} catch (Exception e) {
log.error(name, "NACOS-XXXX", "[update-serverlist] failed to update serverlist from address server!", e);
log.error(name, "NACOS-XXXX", "[update-serverlist] failed to update serverlist from address server!",
e);
}
}
}
@ -233,7 +233,8 @@ public class ServerListManager {
private void updateIfChanged(List<String> newList) {
if (null == newList || newList.isEmpty()) {
log.warn("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题","[update-serverlist] current serverlist from address server is empty!!!"));
log.warn("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题",
"[update-serverlist] current serverlist from address server is empty!!!"));
log.warn(name, "[update-serverlist] current serverlist from address server is empty!!!");
return;
}
@ -255,7 +256,7 @@ public class ServerListManager {
HttpResult httpResult = HttpSimpleClient.httpGet(url, null, null, null, 3000);
if (HttpURLConnection.HTTP_OK == httpResult.code) {
if (DEFAULT_NAME.equals(name) ) {
if (DEFAULT_NAME.equals(name)) {
EnvUtil.setSelfEnv(httpResult.headers);
}
List<String> lines = IOUtils.readLines(new StringReader(httpResult.content));
@ -279,7 +280,7 @@ public class ServerListManager {
return null;
}
} catch (IOException e) {
log.error("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题",e.toString()));
log.error("NACOS-0001", LoggerHelper.getErrorCodeStr("NACOS", "NACOS-0001", "环境问题", e.toString()));
log.error(addressServerUrl, "NACOS-XXXX", "[check-serverlist] exception. msg={}", e.toString(), e);
return null;
}
@ -294,7 +295,7 @@ public class ServerListManager {
String split = "";
for (String serverIp : serverIps) {
sb.append(split);
sb.append(serverIp);
sb.append(serverIp.replaceAll(":", "_"));
split = "-";
}
return sb.toString();
@ -302,10 +303,10 @@ public class ServerListManager {
@Override
public String toString() {
return "ServerManager-" + name + "-" +getUrlString();
return "ServerManager-" + name + "-" + getUrlString();
}
public boolean contain(String ip){
public boolean contain(String ip) {
return serverUrls.contains(ip);
}
@ -321,7 +322,6 @@ public class ServerListManager {
return currentServerAddr;
}
public String getContentPath() {
return contentPath;
}
@ -369,7 +369,6 @@ public class ServerListManager {
}
/**
* 对地址列表排序同机房优先
*/

View File

@ -29,7 +29,6 @@ import java.util.*;
* 适配spas接口
*
* @author Nacos
*
*/
public class SpasAdapter {
@ -51,13 +50,12 @@ public class SpasAdapter {
return header;
}
public static List<String> getSignHeaders(List<String> paramValues, String secretKey) {
if (null == paramValues) {
return null;
}
Map<String, String> signMap = new HashMap<String, String>(5);
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext();) {
for (Iterator<String> iter = paramValues.iterator(); iter.hasNext(); ) {
String key = iter.next();
if (TENANT_KEY.equals(key) || GROUP_KEY.equals(key)) {
signMap.put(key, iter.next());

View File

@ -21,11 +21,10 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* Time Service
* @author Nacos
*
* @author Nacos
*/
public class TimerService {

View File

@ -28,7 +28,6 @@ import java.util.Properties;
* Properties Listener
*
* @author Nacos
*
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class PropertiesListener extends AbstractListener {
@ -43,9 +42,8 @@ public abstract class PropertiesListener extends AbstractListener {
try {
properties.load(new StringReader(configInfo));
innerReceive(properties);
}
catch (IOException e) {
log.error("NACOS-XXXX","load properties error" + configInfo, e);
} catch (IOException e) {
log.error("NACOS-XXXX", "load properties error" + configInfo, e);
}
}
@ -53,8 +51,7 @@ public abstract class PropertiesListener extends AbstractListener {
/**
* properties type for receiver
*
* @param properties
* properties
* @param properties properties
*/
public abstract void innerReceive(Properties properties);

View File

@ -32,20 +32,16 @@ import java.nio.charset.CharsetDecoder;
* concurrent disk util;op file with file lock
*
* @author configCenter
*
*/
public class ConcurrentDiskUtil {
/**
* get file content
*
* @param path
* file path
* @param charsetName
* charsetName
* @param path file path
* @param charsetName charsetName
* @return content
* @throws IOException
* IOException
* @throws IOException IOException
*/
public static String getFileContent(String path, String charsetName)
throws IOException {
@ -56,13 +52,10 @@ public class ConcurrentDiskUtil {
/**
* get file content
*
* @param file
* file
* @param charsetName
* charsetName
* @param file file
* @param charsetName charsetName
* @return content
* @throws IOException
* IOException
* @throws IOException IOException
*/
public static String getFileContent(File file, String charsetName)
throws IOException {
@ -88,7 +81,7 @@ public class ConcurrentDiskUtil {
i);
}
} while (null == rlock);
int fileSize = (int) fcin.size();
int fileSize = (int)fcin.size();
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
fcin.read(byteBuffer);
byteBuffer.flip();
@ -108,15 +101,11 @@ public class ConcurrentDiskUtil {
/**
* write file content
*
* @param path
* file path
* @param content
* content
* @param charsetName
* charsetName
* @param path file path
* @param content content
* @param charsetName charsetName
* @return whether write ok
* @throws IOException
* IOException
* @throws IOException IOException
*/
public static Boolean writeFileContent(String path, String content,
String charsetName) throws IOException {
@ -127,15 +116,11 @@ public class ConcurrentDiskUtil {
/**
* write file content
*
* @param file
* file
* @param content
* content
* @param charsetName
* charsetName
* @param file file
* @param content content
* @param charsetName charsetName
* @return whether write ok
* @throws IOException
* IOException
* @throws IOException IOException
*/
public static Boolean writeFileContent(File file, String content,
String charsetName) throws IOException {
@ -210,13 +195,10 @@ public class ConcurrentDiskUtil {
/**
* transfer ByteBuffer to String
*
* @param buffer
* buffer
* @param charsetName
* charsetName
* @param buffer buffer
* @param charsetName charsetName
* @return String
* @throws IOException
* IOException
* @throws IOException IOException
*/
public static String byteBufferToString(ByteBuffer buffer,
String charsetName) throws IOException {

View File

@ -23,7 +23,6 @@ import static com.alibaba.nacos.api.common.Constants.WORD_SEPARATOR;
* Content Util
*
* @author Nacos
*
*/
public class ContentUtils {
@ -43,7 +42,6 @@ public class ContentUtils {
}
}
public static String getContentIdentity(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
@ -52,7 +50,6 @@ public class ContentUtils {
return content.substring(0, index);
}
public static String getContent(String content) {
int index = content.indexOf(WORD_SEPARATOR);
if (index == -1) {
@ -61,15 +58,12 @@ public class ContentUtils {
return content.substring(index + 1);
}
public static String truncateContent(String content) {
if (content == null) {
return "";
}
else if (content.length() <= SHOW_CONTENT_SIZE) {
} else if (content.length() <= SHOW_CONTENT_SIZE) {
return content;
}
else {
} else {
return content.substring(0, SHOW_CONTENT_SIZE) + "...";
}
}

View File

@ -21,12 +21,10 @@ import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* IO Util
*
* @author Nacos
*
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class IOUtils {
@ -45,7 +43,7 @@ public class IOUtils {
static public long copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[1 << 12];
long count = 0;
for (int n = 0; (n = input.read(buffer)) >= 0;) {
for (int n = 0; (n = input.read(buffer)) >= 0; ) {
output.write(buffer, 0, n);
count += n;
}
@ -59,7 +57,7 @@ public class IOUtils {
BufferedReader reader = toBufferedReader(input);
List<String> list = new ArrayList<String>();
String line = null;
for (;;) {
for (; ; ) {
line = reader.readLine();
if (null != line) {
list.add(line);
@ -71,7 +69,7 @@ public class IOUtils {
}
static private BufferedReader toBufferedReader(Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(
return reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader(
reader);
}

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.client.logger.Logger;
* Get jvm config
*
* @author Nacos
*
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JVMUtil {

View File

@ -24,7 +24,6 @@ import com.alibaba.nacos.client.logger.LoggerFactory;
* Log Util
*
* @author Nacos
*
*/
public class LogUtils {
@ -37,20 +36,21 @@ public class LogUtils {
/**
* change timeout from 100 to 200
*/
tmp = System.getProperty("JM.LOG.RETAIN.COUNT","7");
tmp = System.getProperty("JM.LOG.RETAIN.COUNT", "7");
JM_LOG_RETAIN_COUNT = Integer.parseInt(tmp);
} catch (NumberFormatException e) {
e.printStackTrace();
throw e;
}
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE","10MB");
JM_LOG_FILE_SIZE = System.getProperty("JM.LOG.FILE.SIZE", "10MB");
// logger init
Logger logger = LoggerFactory.getLogger("com.alibaba.nacos.client.config");
logger.setLevel(Level.INFO);
logger.setAdditivity(false);
logger.activateAppenderWithSizeRolling("nacos", "config.log", Constants.ENCODE, JM_LOG_FILE_SIZE, JM_LOG_RETAIN_COUNT);
logger.activateAppenderWithSizeRolling("nacos", "config.log", Constants.ENCODE, JM_LOG_FILE_SIZE,
JM_LOG_RETAIN_COUNT);
}
public static Logger logger(Class<?> clazz) {

View File

@ -27,14 +27,14 @@ import java.util.concurrent.locks.ReentrantLock;
* MD5 util
*
* @author Nacos
*
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class MD5 {
private static int DIGITS_SIZE = 16;
private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static Map<Character, Integer> rDigits = new HashMap<Character, Integer>(16);
static {
for (int i = 0; i < digits.length; ++i) {
rDigits.put(digits[i], i);
@ -45,38 +45,31 @@ public class MD5 {
private MessageDigest mHasher;
private ReentrantLock opLock = new ReentrantLock();
private MD5() {
try {
mHasher = MessageDigest.getInstance("md5");
}
catch (Exception e) {
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MD5 getInstance() {
return me;
}
public String getMD5String(String content) {
return bytes2string(hash(content));
}
public String getMD5String(byte[] content) {
return bytes2string(hash(content));
}
public byte[] getMD5Bytes(byte[] content) {
return hash(content);
}
/**
* 对字符串进行md5
*
@ -91,20 +84,17 @@ public class MD5 {
throw new IllegalArgumentException("md5 need");
}
return bt;
}
catch (UnsupportedEncodingException e) {
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("unsupported utf-8 encoding", e);
}
finally {
} finally {
opLock.unlock();
}
}
/**
* 对二进制数据进行md5
*
* @param str
* @param data
* @return md5 byte[16]
*/
public byte[] hash(byte[] data) {
@ -115,13 +105,11 @@ public class MD5 {
throw new IllegalArgumentException("md5 need");
}
return bt;
}
finally {
} finally {
opLock.unlock();
}
}
/**
* 将一个字节数组转化为可见的字符串
*
@ -141,5 +129,4 @@ public class MD5 {
return new String(out);
}
}

View File

@ -25,12 +25,10 @@ import com.alibaba.nacos.client.utils.StringUtils;
* Param check util
*
* @author Nacos
*
*/
public class ParamUtils {
private static char[] validChars = new char[] { '_', '-', '.', ':' };
private static char[] validChars = new char[] {'_', '-', '.', ':'};
/**
* 白名单的方式检查, 合法的参数只能包含字母数字以及validChars中的字符, 并且不能为空
@ -47,18 +45,15 @@ public class ParamUtils {
char ch = param.charAt(i);
if (Character.isLetterOrDigit(ch)) {
continue;
}
else if (isValidChar(ch)) {
} else if (isValidChar(ch)) {
continue;
}
else {
} else {
return false;
}
}
return true;
}
private static boolean isValidChar(char ch) {
for (char c : validChars) {
if (c == ch) {

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
* Snapshot switch
*
* @author Nacos
*
*/
public class SnapShotSwitch {

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
* Tenant Util
*
* @author Nacos
*
*/
public class TenantUtil {

View File

@ -1,19 +1,3 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.identify;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@ -30,43 +14,31 @@ package com.alibaba.nacos.client.identify;
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.identify;
import java.io.UnsupportedEncodingException;
/**
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*
* <p>
* This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein.
* </p>
* <p>
* The class can be parameterized in the following manner with various constructors:
* <ul>
* <li>URL-safe mode: Default off.</li>
* <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being multiples of
* 4 in the encoded data.
* <li>Line separator: Default is CRLF ("\r\n")</li>
* </ul>
* </p>
* <p>
* Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode
* character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
* </p>
* <p>
* This class is not thread-safe. Each thread should use its own instance.
* </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @author Apache Software Foundation
* @since 1.0
* @version $Revision: 1080712 $
*/
* Provides Base64 encoding and decoding as defined by <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
* <p>
* <p> This class implements section <cite>6.8. Base64 Content-Transfer-Encoding</cite> from RFC 2045 <cite>Multipurpose
* Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies</cite> by Freed and Borenstein. </p> <p>
* The class can be parameterized in the following manner with various constructors: <ul> <li>URL-safe mode: Default
* off.</li> <li>Line length: Default 76. Line length that aren't multiples of 4 will still essentially end up being
* multiples of 4 in the encoded data. <li>Line separator: Default is CRLF ("\r\n")</li> </ul> </p> <p> Since this class
* operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode character
* encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc). </p> <p> This
* class is not thread-safe. Each thread should use its own instance. </p>
*
* @author Apache Software Foundation
* @version $Revision: 1080712 $
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>
* @since 1.0
*/
public class Base64 {
/**
* BASE32 characters are 6 bits in length.
* They are formed by taking a block of 3 octets to form a 24-bit string,
* BASE32 characters are 6 bits in length. They are formed by taking a block of 3 octets to form a 24-bit string,
* which is converted into 4 BASE64 characters.
*/
private static final int BITS_PER_ENCODED_BYTE = 6;
@ -75,10 +47,8 @@ public class Base64 {
/**
* Chunk separator per RFC 2045 section 2.1.
*
* <p>
* N.B. The next major release may break compatibility and make this field private.
* </p>
* <p> N.B. The next major release may break compatibility and make this field private. </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
*/
@ -87,9 +57,9 @@ public class Base64 {
/**
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet"
* equivalents as specified in Table 1 of RFC 2045.
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* <p>
* Thanks to "commons" project in ws.apache.org for this code. http://svn.apache
* .org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] STANDARD_ENCODE_TABLE = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
@ -100,9 +70,8 @@ public class Base64 {
};
/**
* This is a copy of the STANDARD_ENCODE_TABLE above, but with + and /
* changed to - and _ to make the encoded Base64 results more URL-SAFE.
* This table is only used when the Base64's mode is set to URL-SAFE.
* This is a copy of the STANDARD_ENCODE_TABLE above, but with + and / changed to - and _ to make the encoded Base64
* results more URL-SAFE. This table is only used when the Base64's mode is set to URL-SAFE.
*/
private static final byte[] URL_SAFE_ENCODE_TABLE = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
@ -116,12 +85,12 @@ public class Base64 {
* This array is a lookup table that translates Unicode characters drawn from the "Base64 Alphabet" (as specified in
* Table 1 of RFC 2045) into their 6-bit positive integer equivalents. Characters that are not in the Base64
* alphabet but fall within the bounds of the array are translated to -1.
*
* <p>
* Note: '+' and '-' both decode to 62. '/' and '_' both decode to 63. This means decoder seamlessly handles both
* URL_SAFE and STANDARD base64. (The encoder, on the other hand, needs to know ahead of time what to emit).
*
* Thanks to "commons" project in ws.apache.org for this code.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* <p>
* Thanks to "commons" project in ws.apache.org for this code. http://svn.apache
* .org/repos/asf/webservices/commons/trunk/modules/util/
*/
private static final byte[] DECODE_TABLE = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@ -136,7 +105,9 @@ public class Base64 {
/**
* Base64 uses 6-bit fields.
*/
/** Mask used to extract 6 bits, used when encoding */
/**
* Mask used to extract 6 bits, used when encoding
*/
private static final int MASK_6BITS = 0x3f;
// The static final fields above are used for the original static byte[] methods on Base64.
@ -173,55 +144,43 @@ public class Base64 {
private final int encodeSize;
/**
* Place holder for the bytes we're dealing with for our based logic.
* Bitwise operations store and extract the encoding or decoding from this variable.
* Place holder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the
* encoding or decoding from this variable.
*/
private int bitWorkArea;
/**
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. <p> When encoding the line
* length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE. </p>
* <p>
* When encoding the line length is 0 (no chunking), and the encoding table is STANDARD_ENCODE_TABLE.
* </p>
*
* <p>
* When decoding all variants are supported.
* </p>
* <p> When decoding all variants are supported. </p>
*/
public Base64() {
this(0, CHUNK_SEPARATOR, false);
}
/**
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.
* <p>
* When encoding the line length and line separator are given in the constructor, and the encoding table is
* STANDARD_ENCODE_TABLE.
* </p>
* <p>
* Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode. <p> When encoding the line
* length and line separator are given in the constructor, and the encoding table is STANDARD_ENCODE_TABLE. </p> <p>
* Line lengths that aren't multiples of 4 will still essentially end up being multiples of 4 in the encoded data.
* </p>
* <p>
* When decoding all variants are supported.
* </p>
* </p> <p> When decoding all variants are supported. </p>
*
* @param lineLength
* Each line of encoded data will be at most of the given length (rounded down to nearest multiple of 4).
* If lineLength <= 0, then the output will not be divided into lines (chunks). Ignored when decoding.
* @param lineSeparator
* Each line of encoded data will end with this sequence of bytes.
* @param urlSafe
* Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to encode
* operations. Decoding seamlessly handles both modes.
* @throws IllegalArgumentException
* The provided lineSeparator included some base64 characters. That's not going to work!
* @param lineLength Each line of encoded data will be at most of the given length (rounded down to nearest
* multiple of 4). If lineLength <= 0, then the output will not be divided into lines (chunks).
* Ignored when decoding.
* @param lineSeparator Each line of encoded data will end with this sequence of bytes.
* @param urlSafe Instead of emitting '+' and '/' we emit '-' and '_' respectively. urlSafe is only applied to
* encode operations. Decoding seamlessly handles both modes.
* @throws IllegalArgumentException The provided lineSeparator included some base64 characters. That's not going to
* work!
* @since 1.4
*/
public Base64(int lineLength, byte[] lineSeparator, boolean urlSafe) {
chunkSeparatorLength = lineSeparator == null ? 0 : lineSeparator.length;
unencodedBlockSize = BYTES_PER_UNENCODED_BLOCK;
encodedBlockSize = BYTES_PER_ENCODED_BLOCK;
this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize) * encodedBlockSize : 0;
this.lineLength = (lineLength > 0 && chunkSeparatorLength > 0) ? (lineLength / encodedBlockSize)
* encodedBlockSize : 0;
// TODO could be simplified if there is no requirement to reject invalid line sep when length <=0
// @see test case Base64Test.testConstructors()
if (lineSeparator != null) {
@ -233,7 +192,7 @@ public class Base64 {
}
throw new IllegalArgumentException("lineSeparator must not contain base64 characters: [" + sep + "]");
}
if (lineLength > 0){
if (lineLength > 0) {
this.encodeSize = BYTES_PER_ENCODED_BLOCK + lineSeparator.length;
this.lineSeparator = new byte[lineSeparator.length];
System.arraycopy(lineSeparator, 0, this.lineSeparator, 0, lineSeparator.length);
@ -250,22 +209,15 @@ public class Base64 {
}
/**
* <p>
* Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once with
* the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush last
* remaining bytes (if not multiple of 3).
* </p>
* <p>
* Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* <p> Encodes all of the provided data, starting at inPos, for inAvail bytes. Must be called at least twice: once
* with the data to encode, and once with inAvail set to "-1" to alert encoder that EOF has been reached, so flush
* last remaining bytes (if not multiple of 3). </p> <p> Thanks to "commons" project in ws.apache.org for the
* bitwise operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* </p>
*
* @param in
* byte[] array of binary data to base64 encode.
* @param inPos
* Position to start reading data from.
* @param inAvail
* Amount of bytes available from input for encoding.
* @param in byte[] array of binary data to base64 encode.
* @param inPos Position to start reading data from.
* @param inAvail Amount of bytes available from input for encoding.
*/
void encode(byte[] in, int inPos, int inAvail) {
if (eof) {
@ -279,7 +231,7 @@ public class Base64 {
ensureBufferSize(encodeSize);
int savedPos = pos;
switch (modulus) {
case 1 :
case 1:
buffer[pos++] = encodeTable[(bitWorkArea >> 2) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea << 4) & MASK_6BITS];
@ -289,7 +241,7 @@ public class Base64 {
}
break;
case 2 :
case 2:
buffer[pos++] = encodeTable[(bitWorkArea >> 10) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea >> 4) & MASK_6BITS];
buffer[pos++] = encodeTable[(bitWorkArea << 2) & MASK_6BITS];
@ -312,7 +264,7 @@ public class Base64 {
} else {
for (int i = 0; i < inAvail; i++) {
ensureBufferSize(encodeSize);
modulus = (modulus+1) % BYTES_PER_UNENCODED_BLOCK;
modulus = (modulus + 1) % BYTES_PER_UNENCODED_BLOCK;
int b = in[inPos++];
if (b < 0) {
b += 256;
@ -335,27 +287,17 @@ public class Base64 {
}
/**
* <p>
* Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
* <p> Decodes all of the provided data, starting at inPos, for inAvail bytes. Should be called at least twice: once
* with the data to decode, and once with inAvail set to "-1" to alert decoder that EOF has been reached. The "-1"
* call is not necessary when decoding, but it doesn't hurt, either.
* </p>
* <p>
* Ignores all non-base64 characters. This is how chunked (e.g. 76 character) data is handled, since CR and LF are
* silently ignored, but has implications for other bytes, too. This method subscribes to the garbage-in,
* garbage-out philosophy: it will not check the provided data for validity.
* </p>
* <p>
* Thanks to "commons" project in ws.apache.org for the bitwise operations, and general approach.
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/
* </p>
* call is not necessary when decoding, but it doesn't hurt, either. </p> <p> Ignores all non-base64 characters.
* This is how chunked (e.g. 76 character) data is handled, since CR and LF are silently ignored, but has
* implications for other bytes, too. This method subscribes to the garbage-in, garbage-out philosophy: it will not
* check the provided data for validity. </p> <p> Thanks to "commons" project in ws.apache.org for the bitwise
* operations, and general approach. http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ </p>
*
* @param in
* byte[] array of ascii data to base64 decode.
* @param inPos
* Position to start reading data from.
* @param inAvail
* Amount of bytes available from input for encoding.
* @param in byte[] array of ascii data to base64 decode.
* @param inPos Position to start reading data from.
* @param inAvail Amount of bytes available from input for encoding.
*/
void decode(byte[] in, int inPos, int inAvail) {
if (eof) {
@ -375,12 +317,12 @@ public class Base64 {
if (b >= 0 && b < DECODE_TABLE.length) {
int result = DECODE_TABLE[b];
if (result >= 0) {
modulus = (modulus+1) % BYTES_PER_ENCODED_BLOCK;
modulus = (modulus + 1) % BYTES_PER_ENCODED_BLOCK;
bitWorkArea = (bitWorkArea << BITS_PER_ENCODED_BYTE) + result;
if (modulus == 0) {
buffer[pos++] = (byte) ((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) (bitWorkArea & MASK_8BITS);
buffer[pos++] = (byte)((bitWorkArea >> 16) & MASK_8BITS);
buffer[pos++] = (byte)((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte)(bitWorkArea & MASK_8BITS);
}
}
}
@ -398,14 +340,14 @@ public class Base64 {
switch (modulus) {
// case 1: // 6 bits - ignore entirely
// break;
case 2 :
case 2:
bitWorkArea = bitWorkArea >> 4;
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
buffer[pos++] = (byte)((bitWorkArea) & MASK_8BITS);
break;
case 3 :
case 3:
bitWorkArea = bitWorkArea >> 2;
buffer[pos++] = (byte) ((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte) ((bitWorkArea) & MASK_8BITS);
buffer[pos++] = (byte)((bitWorkArea >> 8) & MASK_8BITS);
buffer[pos++] = (byte)((bitWorkArea) & MASK_8BITS);
break;
default:
break;
@ -416,8 +358,7 @@ public class Base64 {
/**
* Encodes binary data using the base64 algorithm but does not chunk the output.
*
* @param binaryData
* binary data to encode
* @param binaryData binary data to encode
* @return byte[] containing Base64 characters in their UTF-8 representation.
*/
public static byte[] encodeBase64(byte[] binaryData) {
@ -427,17 +368,13 @@ public class Base64 {
/**
* Encodes binary data using the base64 algorithm, optionally chunking the output into 76 character blocks.
*
* @param binaryData
* Array containing binary data to encode.
* @param isChunked
* if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
* @param urlSafe
* if <code>true</code> this encoder will emit - and _ instead of the usual + and / characters.
* @param maxResultSize
* The maximum result size to accept.
* @param binaryData Array containing binary data to encode.
* @param isChunked if <code>true</code> this encoder will chunk the base64 output into 76 character blocks
* @param urlSafe if <code>true</code> this encoder will emit - and _ instead of the usual + and /
* characters.
* @param maxResultSize The maximum result size to accept.
* @return Base64-encoded data.
* @throws IllegalArgumentException
* Thrown when the input array needs an output array bigger than maxResultSize
* @throws IllegalArgumentException Thrown when the input array needs an output array bigger than maxResultSize
* @since 1.4
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked, boolean urlSafe, int maxResultSize) {
@ -447,7 +384,8 @@ public class Base64 {
// Create this so can use the super-class method
// Also ensures that the same roundings are performed by the ctor and the code
Base64 b64 = isChunked ? new Base64(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe) : new Base64(0, CHUNK_SEPARATOR, urlSafe);
Base64 b64 = isChunked ? new Base64(MIME_CHUNK_SIZE, CHUNK_SEPARATOR, urlSafe) : new Base64(0, CHUNK_SEPARATOR,
urlSafe);
long len = b64.getEncodedLength(binaryData);
if (len > maxResultSize) {
throw new IllegalArgumentException("Input array too big, the output array would be bigger (" +
@ -459,25 +397,20 @@ public class Base64 {
return b64.encode(binaryData);
}
/**
* Decodes Base64 data into octets
*
* @param base64Data
* Byte array containing Base64 data
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
return new Base64().decode(base64Data);
}
/**
* Returns whether or not the <code>octet</code> is in the Base32 alphabet.
*
* @param octet
* The value to test
* @param octet The value to test
* @return <code>true</code> if the value is defined in the the Base32 alphabet <code>false</code> otherwise.
*/
protected boolean isInAlphabet(byte octet) {
@ -490,11 +423,9 @@ public class Base64 {
/**
* MIME chunk size per RFC 2045 section 6.8.
*
* <p>
* The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs.
* </p>
* <p> The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any
* equal signs. </p>
*
* @see <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
*/
@ -503,12 +434,14 @@ public class Base64 {
private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
/**
* Defines the default buffer size - currently {@value}
* - must be large enough for at least one encoded block+separator
* Defines the default buffer size - currently {@value} - must be large enough for at least one encoded
* block+separator
*/
private static final int DEFAULT_BUFFER_SIZE = 8192;
/** Mask used to extract 8 bits, used in decoding bytes */
/**
* Mask used to extract 8 bits, used in decoding bytes
*/
private static final int MASK_8BITS = 0xff;
/**
@ -518,15 +451,18 @@ public class Base64 {
private static final byte PAD = PAD_DEFAULT;
/** Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32 */
/**
* Number of bytes in each full block of unencoded data, e.g. 4 for Base64 and 5 for Base32
*/
private final int unencodedBlockSize;
/** Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32 */
/**
* Number of bytes in each full block of encoded data, e.g. 3 for Base64 and 8 for Base32
*/
private final int encodedBlockSize;
/**
* Chunksize for encoding. Not used when decoding.
* A value of zero or less implies no chunking of the encoded data.
* Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data.
* Rounded down to nearest multiple of encodedBlockSize.
*/
private final int lineLength;
@ -552,8 +488,8 @@ public class Base64 {
private int readPos;
/**
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless,
* and must be thrown away.
* Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and
* must be thrown away.
*/
private boolean eof;
@ -564,8 +500,8 @@ public class Base64 {
private int currentLinePos;
/**
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding.
* This variable helps track that.
* Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This
* variable helps track that.
*/
private int modulus;
@ -574,8 +510,8 @@ public class Base64 {
*
* @param size minimum spare space required
*/
private void ensureBufferSize(int size){
if ((buffer == null) || (buffer.length < pos + size)){
private void ensureBufferSize(int size) {
if ((buffer == null) || (buffer.length < pos + size)) {
if (buffer == null) {
buffer = new byte[DEFAULT_BUFFER_SIZE];
pos = 0;
@ -589,15 +525,12 @@ public class Base64 {
}
/**
* Extracts buffered data into the provided byte[] array, starting at position bPos,
* up to a maximum of bAvail bytes. Returns how many bytes were actually extracted.
* Extracts buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail
* bytes. Returns how many bytes were actually extracted.
*
* @param b
* byte[] array to extract the buffered data into.
* @param bPos
* position in byte[] array to start extraction at.
* @param bAvail
* amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @param b byte[] array to extract the buffered data into.
* @param bPos position in byte[] array to start extraction at.
* @param bAvail amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
* @return The number of bytes successfully extracted into the provided byte[] array.
*/
private int readResults(byte[] b, int bPos, int bAvail) {
@ -628,8 +561,7 @@ public class Base64 {
/**
* Decodes a byte[] containing characters in the Base-N alphabet.
*
* @param pArray
* A byte array containing Base-N character data
* @param pArray A byte array containing Base-N character data
* @return a byte array containing binary data
*/
private byte[] decode(byte[] pArray) {
@ -647,8 +579,7 @@ public class Base64 {
/**
* Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
*
* @param pArray
* a byte array containing binary data
* @param pArray a byte array containing binary data
* @return A byte array containing only the basen alphabetic character data
*/
private byte[] encode(byte[] pArray) {
@ -665,11 +596,10 @@ public class Base64 {
/**
* Tests a given byte array to see if it contains any characters within the alphabet or PAD.
*
* <p>
* Intended for use in checking line-ending arrays
*
* @param arrayOctet
* byte array to test
* @param arrayOctet byte array to test
* @return <code>true</code> if any byte is a valid character in the alphabet or PAD; <code>false</code> otherwise
*/
private boolean containsAlphabetOrPad(byte[] arrayOctet) {
@ -688,19 +618,18 @@ public class Base64 {
* Calculates the amount of space needed to encode the supplied array.
*
* @param pArray byte[] array which will later be encoded
*
* @return amount of space needed to encoded the supplied array.
* Returns a long since a max-len array will require > Integer.MAX_VALUE
* @return amount of space needed to encoded the supplied array. Returns a long since a max-len array will require >
* Integer.MAX_VALUE
*/
private long getEncodedLength(byte[] pArray) {
// Calculate non-chunked size - rounded up to allow for padding
// cast to long is needed to avoid possibility of overflow
long len = ((pArray.length + unencodedBlockSize-1) / unencodedBlockSize) * (long) encodedBlockSize;
long len = ((pArray.length + unencodedBlockSize - 1) / unencodedBlockSize) * (long)encodedBlockSize;
if (lineLength > 0) {
/**
* Round up to nearest multiple
*/
len += ((len + lineLength-1) / lineLength) * chunkSeparatorLength;
len += ((len + lineLength - 1) / lineLength) * chunkSeparatorLength;
}
return len;
}

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
* Identify Constants
*
* @author Nacos
*
*/
public class Constants {
public static final String ACCESS_KEY = "accessKey";

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
* Credential Listener
*
* @author Nacos
*
*/
public interface CredentialListener {
/**

View File

@ -25,11 +25,11 @@ import java.util.concurrent.ConcurrentHashMap;
* Credential Service
*
* @author Nacos
*
*/
public final class CredentialService implements SpasCredentialLoader {
static final public Logger log = LogUtils.logger(CredentialService.class);
private static ConcurrentHashMap<String, CredentialService> instances = new ConcurrentHashMap<String, CredentialService>();
private static ConcurrentHashMap<String, CredentialService> instances
= new ConcurrentHashMap<String, CredentialService>();
private String appName;
private Credentials credentials = new Credentials();
@ -47,7 +47,6 @@ public final class CredentialService implements SpasCredentialLoader {
watcher = new CredentialWatcher(appName, this);
}
public static CredentialService getInstance() {
return getInstance(null);
}

View File

@ -33,7 +33,6 @@ import com.alibaba.nacos.client.utils.StringUtils;
* Credential Watcher
*
* @author Nacos
*
*/
public class CredentialWatcher {
static final public Logger SpasLogger = LogUtils.logger(CredentialWatcher.class);
@ -110,15 +109,14 @@ public class CredentialWatcher {
propertyPath = value;
}
if (propertyPath == null || propertyPath.isEmpty()) {
propertyPath = Constants.CREDENTIAL_PATH + (appName == null ? Constants.CREDENTIAL_DEFAULT : appName);
}
else {
propertyPath = Constants.CREDENTIAL_PATH + (appName == null ? Constants.CREDENTIAL_DEFAULT
: appName);
} else {
if (logWarn) {
SpasLogger.info(appName, "Defined credential file: -D" + "spas.identity" + "=" + propertyPath);
}
}
}
else {
} else {
if (logWarn) {
SpasLogger.info(appName, "Load credential file from classpath: " + Constants.PROPERTIES_FILENAME);
}
@ -130,7 +128,8 @@ public class CredentialWatcher {
try {
propertiesIS = new FileInputStream(propertyPath);
} catch (FileNotFoundException e) {
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT) && propertyPath.equals(Constants.CREDENTIAL_PATH + appName)) {
if (appName != null && !appName.equals(Constants.CREDENTIAL_DEFAULT) && propertyPath.equals(
Constants.CREDENTIAL_PATH + appName)) {
propertyPath = Constants.CREDENTIAL_PATH + Constants.CREDENTIAL_DEFAULT;
continue;
}
@ -154,8 +153,7 @@ public class CredentialWatcher {
}
return;
}
}
else {
} else {
Properties properties = new Properties();
try {
properties.load(propertiesIS);

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
* Credentials
*
* @author Nacos
*
*/
public class Credentials implements SpasCredential {
@ -59,7 +58,9 @@ public class Credentials implements SpasCredential {
public boolean identical(Credentials other) {
return this == other ||
(other != null &&
(accessKey == null && other.accessKey == null || accessKey != null && accessKey.equals(other.accessKey)) &&
(secretKey == null && other.secretKey == null || secretKey != null && secretKey.equals(other.secretKey)));
(accessKey == null && other.accessKey == null || accessKey != null && accessKey.equals(other.accessKey))
&&
(secretKey == null && other.secretKey == null || secretKey != null && secretKey.equals(
other.secretKey)));
}
}

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
* Spas Credential Interface
*
* @author Nacos
*
*/
public interface SpasCredential {
/**

View File

@ -19,7 +19,6 @@ package com.alibaba.nacos.client.identify;
* Spas Credential Loader
*
* @author Nacos
*
*/
public interface SpasCredentialLoader {
/**

View File

@ -24,7 +24,11 @@ public enum Level {
/**
* log level
*/
DEBUG("DEBUG"), INFO("INFO"), WARN("WARN"), ERROR("ERROR"), OFF("OFF");
DEBUG("DEBUG"),
INFO("INFO"),
WARN("WARN"),
ERROR("ERROR"),
OFF("OFF");
private String name;

View File

@ -213,12 +213,14 @@ public interface Logger extends ActivateOption {
/**
* 判断Info级别是否开启
*
* @return Info级别是否开启
*/
boolean isInfoEnabled();
/**
* 判断Warn级别是否开启
*
* @return Warn级别是否开启
*/
boolean isWarnEnabled();
@ -232,6 +234,7 @@ public interface Logger extends ActivateOption {
/**
* * 获取内部日志实现对象
*
* @return 内部日志实现对象
*/
Object getDelegate();

View File

@ -15,16 +15,15 @@
*/
package com.alibaba.nacos.client.logger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.nacos.client.logger.log4j.Log4jLoggerFactory;
import com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory;
import com.alibaba.nacos.client.logger.nop.NopLoggerFactory;
import com.alibaba.nacos.client.logger.slf4j.Slf4jLoggerFactory;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* <pre>
* 阿里中间件LoggerFactory获取具体日志实现
@ -56,20 +55,15 @@ public class LoggerFactory {
setLoggerFactory(new Slf4jLoggerFactory());
LogLog.info("Init JM logger with Slf4jLoggerFactory success, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e1) {
try {
setLoggerFactory(new Log4jLoggerFactory());
LogLog.info("Init JM logger with Log4jLoggerFactory, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e2) {
try {
setLoggerFactory(new Log4j2LoggerFactory());
LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e3) {
} catch (Throwable e2) {
setLoggerFactory(new NopLoggerFactory());
LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
+ LoggerFactory.class.getClassLoader(), e2);
}
}
}
loggerCache = new ConcurrentHashMap<String, Logger>();
}

View File

@ -29,7 +29,7 @@ import java.util.Iterator;
/**
* A JSON array. JSONObject supports java.util.List interface.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
@ -38,48 +38,46 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
/**
* Constructs an empty JSONArray.
*/
public JSONArray(){
public JSONArray() {
super();
}
/**
* Constructs a JSONArray containing the elements of the specified
* collection, in the order they are returned by the collection's iterator.
* Constructs a JSONArray containing the elements of the specified collection, in the order they are returned by the
* collection's iterator.
*
* @param c the collection whose elements are to be placed into this JSONArray
*/
public JSONArray(Collection c){
public JSONArray(Collection c) {
super(c);
}
/**
* Encode a list into JSON text and write it to out.
* If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
*
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
* Encode a list into JSON text and write it to out. If this list is also a JSONStreamAware or a JSONAware,
* JSONStreamAware and JSONAware specific behaviours will be ignored at this top level.
*
* @param collection
* @param out
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
*/
public static void writeJSONString(Collection collection, Writer out) throws IOException{
if(collection == null){
public static void writeJSONString(Collection collection, Writer out) throws IOException {
if (collection == null) {
out.write("null");
return;
}
boolean first = true;
Iterator iter=collection.iterator();
Iterator iter = collection.iterator();
out.write('[');
while(iter.hasNext()){
if(first) {
while (iter.hasNext()) {
if (first) {
first = false;
}
else {
} else {
out.write(',');
}
Object value=iter.next();
if(value == null){
Object value = iter.next();
if (value == null) {
out.write("null");
continue;
}
@ -89,41 +87,40 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
out.write(']');
}
public void writeJSONString(Writer out) throws IOException{
public void writeJSONString(Writer out) throws IOException {
writeJSONString(this, out);
}
/**
* Convert a list to JSON text. The result is a JSON array.
* If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
*
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
* Convert a list to JSON text. The result is a JSON array. If this list is also a JSONAware, JSONAware specific
* behaviours will be omitted at this top level.
*
* @param collection
* @return JSON text, or "null" if list is null.
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
*/
public static String toJSONString(Collection collection){
public static String toJSONString(Collection collection) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(collection, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(byte[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(byte[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -132,28 +129,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(byte[] array){
public static String toJSONString(byte[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(short[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(short[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -162,28 +159,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(short[] array){
public static String toJSONString(short[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(int[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(int[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -192,28 +189,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(int[] array){
public static String toJSONString(int[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(long[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(long[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -222,28 +219,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(long[] array){
public static String toJSONString(long[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(float[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(float[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -252,28 +249,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(float[] array){
public static String toJSONString(float[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(double[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(double[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -282,28 +279,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(double[] array){
public static String toJSONString(double[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(boolean[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(boolean[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
out.write(String.valueOf(array[i]));
}
@ -312,28 +309,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(boolean[] array){
public static String toJSONString(boolean[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(char[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(char[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[\"");
out.write(String.valueOf(array[0]));
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write("\",\"");
out.write(String.valueOf(array[i]));
}
@ -342,28 +339,28 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(char[] array){
public static String toJSONString(char[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public static void writeJSONString(Object[] array, Writer out) throws IOException{
if(array == null){
public static void writeJSONString(Object[] array, Writer out) throws IOException {
if (array == null) {
out.write("null");
} else if(array.length == 0) {
} else if (array.length == 0) {
out.write("[]");
} else {
out.write("[");
JSONValue.writeJSONString(array[0], out);
for(int i = 1; i < array.length; i++){
for (int i = 1; i < array.length; i++) {
out.write(",");
JSONValue.writeJSONString(array[i], out);
}
@ -372,25 +369,24 @@ public class JSONArray extends ArrayList implements JSONAware, JSONStreamAware {
}
}
public static String toJSONString(Object[] array){
public static String toJSONString(Object[] array) {
final StringWriter writer = new StringWriter();
try {
writeJSONString(array, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
}
public String toJSONString(){
public String toJSONString() {
return toJSONString(this);
}
/**
* Returns a string representation of this array. This is equivalent to
* calling {@link JSONArray#toJSONString()}.
* Returns a string representation of this array. This is equivalent to calling {@link JSONArray#toJSONString()}.
*/
public String toString() {
return toJSONString();

View File

@ -17,7 +17,8 @@ package com.alibaba.nacos.client.logger.json;
/**
* Beans that support customized output of JSON text shall implement this interface.
* @author FangYidong<fangyidong@yahoo.com.cn>
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public interface JSONAware {

View File

@ -29,21 +29,20 @@ import java.util.Map;
/**
* A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{
public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware {
private static final long serialVersionUID = -503443796854799292L;
public JSONObject() {
super();
}
/**
* Allows creation of a JSONObject from a Map. After that, both the
* generated JSONObject and the Map can be modified independently.
* Allows creation of a JSONObject from a Map. After that, both the generated JSONObject and the Map can be modified
* independently.
*
* @param map
*/
@ -51,34 +50,31 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
super(map);
}
/**
* Encode a map into JSON text and write it to out.
* If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level.
*
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
* Encode a map into JSON text and write it to out. If this map is also a JSONAware or JSONStreamAware, JSONAware or
* JSONStreamAware specific behaviours will be ignored at this top level.
*
* @param map
* @param out
* @see com.alibaba.nacos.client.logger.json.JSONValue#writeJSONString(Object, Writer)
*/
public static void writeJSONString(Map map, Writer out) throws IOException {
if(map == null){
if (map == null) {
out.write("null");
return;
}
boolean first = true;
Iterator iter=map.entrySet().iterator();
Iterator iter = map.entrySet().iterator();
out.write('{');
while(iter.hasNext()){
while (iter.hasNext()) {
if (first) {
first = false;
}
else {
} else {
out.write(',');
}
Map.Entry entry = (Map.Entry) iter.next();
Map.Entry entry = (Map.Entry)iter.next();
out.write('\"');
out.write(escape(String.valueOf(entry.getKey())));
out.write('\"');
@ -88,20 +84,19 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
out.write('}');
}
public void writeJSONString(Writer out) throws IOException{
public void writeJSONString(Writer out) throws IOException {
writeJSONString(this, out);
}
/**
* Convert a map to JSON text. The result is a JSON object.
* If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level.
*
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
* Convert a map to JSON text. The result is a JSON object. If this map is also a JSONAware, JSONAware specific
* behaviours will be omitted at this top level.
*
* @param map
* @return JSON text, or "null" if map is null.
* @see com.alibaba.nacos.client.logger.json.JSONValue#toJSONString(Object)
*/
public static String toJSONString(Map map){
public static String toJSONString(Map map) {
final StringWriter writer = new StringWriter();
try {
@ -113,21 +108,20 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
}
}
public String toJSONString(){
public String toJSONString() {
return toJSONString(this);
}
public String toString(){
public String toString() {
return toJSONString();
}
public static String toString(String key,Object value){
public static String toString(String key, Object value) {
StringBuffer sb = new StringBuffer();
sb.append('\"');
if(key == null) {
if (key == null) {
sb.append("null");
}
else {
} else {
JSONValue.escape(key, sb);
}
sb.append('\"').append(':');
@ -138,15 +132,14 @@ public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAwa
}
/**
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
* It's the same as JSONValue.escape() only for compatibility here.
*
* @see com.alibaba.nacos.client.logger.json.JSONValue#escape(String)
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). It's the same as
* JSONValue.escape() only for compatibility here.
*
* @param s
* @return
* @see com.alibaba.nacos.client.logger.json.JSONValue#escape(String)
*/
public static String escape(String s){
public static String escape(String s) {
return JSONValue.escape(s);
}
}

View File

@ -19,20 +19,17 @@ import java.io.IOException;
import java.io.Writer;
/**
* Beans that support customized output of JSON text to a writer shall implement
* this interface.
* Beans that support customized output of JSON text to a writer shall implement this interface.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public interface JSONStreamAware {
/**
* write JSON string to out.
*
* @param out
* out writer
* @throws IOException
* Exception
* @param out out writer
* @throws IOException Exception
*/
void writeJSONString(Writer out) throws IOException;
}

View File

@ -30,213 +30,186 @@ import java.util.Map;
import com.alibaba.nacos.client.logger.json.parser.JSONParser;
import com.alibaba.nacos.client.logger.json.parser.ParseException;
/**
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONValue {
/**
* Parse JSON text into java object from the input source.
* Please use parseWithException() if you don't want to ignore the exception.
*
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* Parse JSON text into java object from the input source. Please use parseWithException() if you don't want to
* ignore the exception.
*
* @param in
* @return Instance of the following:
* com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray,
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean,
* null
*
* @deprecated this method may throw an {@code Error} instead of returning
* {@code null}; please use {@link JSONValue#parseWithException(Reader)}
* instead
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
* JSONValue#parseWithException(Reader)} instead
*/
public static Object parse(Reader in){
try{
JSONParser parser=new JSONParser();
public static Object parse(Reader in) {
try {
JSONParser parser = new JSONParser();
return parser.parse(in);
}
catch(Exception e){
} catch (Exception e) {
return null;
}
}
/**
* Parse JSON text into java object from the given string.
* Please use parseWithException() if you don't want to ignore the exception.
*
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* Parse JSON text into java object from the given string. Please use parseWithException() if you don't want to
* ignore the exception.
*
* @param s
* @return Instance of the following:
* com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray,
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean,
* null
*
* @deprecated this method may throw an {@code Error} instead of returning
* {@code null}; please use {@link JSONValue#parseWithException(String)}
* instead
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser#parse(Reader)
* @see #parseWithException(Reader)
* @deprecated this method may throw an {@code Error} instead of returning {@code null}; please use {@link
* JSONValue#parseWithException(String)} instead
*/
public static Object parse(String s){
StringReader in=new StringReader(s);
public static Object parse(String s) {
StringReader in = new StringReader(s);
return parse(in);
}
/**
* Parse JSON text into java object from the input source.
*
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser
*
* @param in
* @return Instance of the following:
* com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray,
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean,
* null
*
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @throws IOException
* @throws ParseException
* @see com.alibaba.nacos.client.logger.jsonparser.JSONParser
*/
public static Object parseWithException(Reader in) throws IOException, ParseException {
JSONParser parser=new JSONParser();
JSONParser parser = new JSONParser();
return parser.parse(in);
}
public static Object parseWithException(String s) throws ParseException{
JSONParser parser=new JSONParser();
public static Object parseWithException(String s) throws ParseException {
JSONParser parser = new JSONParser();
return parser.parse(s);
}
/**
* Encode an object into JSON text and write it to out.
* <p>
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly.
* If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware
* will be considered firstly.
* <p>
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with
* "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead.
*
* @see com.alibaba.nacos.client.logger.jsonJSONObject#writeJSONString(Map, Writer)
* @see com.alibaba.nacos.client.logger.jsonJSONArray#writeJSONString(List, Writer)
* DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or
* List) with "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or
* JSONArray.writeJSONString(List, Writer) instead.
*
* @param value
* @param writer
* @see com.alibaba.nacos.client.logger.jsonJSONObject#writeJSONString(Map, Writer)
* @see com.alibaba.nacos.client.logger.jsonJSONArray#writeJSONString(List, Writer)
*/
public static void writeJSONString(Object value, Writer out) throws IOException {
if(value == null){
if (value == null) {
out.write("null");
return;
}
if(value instanceof String){
if (value instanceof String) {
out.write('\"');
out.write(escape((String)value));
out.write('\"');
return;
}
if(value instanceof Double){
if(((Double)value).isInfinite() || ((Double)value).isNaN()) {
if (value instanceof Double) {
if (((Double)value).isInfinite() || ((Double)value).isNaN()) {
out.write("null");
}
else {
} else {
out.write(value.toString());
}
return;
}
if(value instanceof Float){
if(((Float)value).isInfinite() || ((Float)value).isNaN()) {
if (value instanceof Float) {
if (((Float)value).isInfinite() || ((Float)value).isNaN()) {
out.write("null");
}
else {
} else {
out.write(value.toString());
}
return;
}
if(value instanceof Number){
if (value instanceof Number) {
out.write(value.toString());
return;
}
if(value instanceof Boolean){
if (value instanceof Boolean) {
out.write(value.toString());
return;
}
if((value instanceof JSONStreamAware)){
if ((value instanceof JSONStreamAware)) {
((JSONStreamAware)value).writeJSONString(out);
return;
}
if((value instanceof JSONAware)){
if ((value instanceof JSONAware)) {
out.write(((JSONAware)value).toJSONString());
return;
}
if(value instanceof Map){
if (value instanceof Map) {
JSONObject.writeJSONString((Map)value, out);
return;
}
if(value instanceof Collection){
if (value instanceof Collection) {
JSONArray.writeJSONString((Collection)value, out);
return;
}
if(value instanceof byte[]){
if (value instanceof byte[]) {
JSONArray.writeJSONString((byte[])value, out);
return;
}
if(value instanceof short[]){
if (value instanceof short[]) {
JSONArray.writeJSONString((short[])value, out);
return;
}
if(value instanceof int[]){
if (value instanceof int[]) {
JSONArray.writeJSONString((int[])value, out);
return;
}
if(value instanceof long[]){
if (value instanceof long[]) {
JSONArray.writeJSONString((long[])value, out);
return;
}
if(value instanceof float[]){
if (value instanceof float[]) {
JSONArray.writeJSONString((float[])value, out);
return;
}
if(value instanceof double[]){
if (value instanceof double[]) {
JSONArray.writeJSONString((double[])value, out);
return;
}
if(value instanceof boolean[]){
if (value instanceof boolean[]) {
JSONArray.writeJSONString((boolean[])value, out);
return;
}
if(value instanceof char[]){
if (value instanceof char[]) {
JSONArray.writeJSONString((char[])value, out);
return;
}
if(value instanceof Object[]){
if (value instanceof Object[]) {
JSONArray.writeJSONString((Object[])value, out);
return;
}
@ -249,21 +222,20 @@ public class JSONValue {
* <p>
* If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly.
* <p>
* DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with
* "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
*
* @see com.alibaba.nacos.client.logger.json.JSONObject#toJSONString(Map)
* DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with "this"
* as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead.
*
* @param value
* @return JSON text, or "null" if value is null or it's an NaN or an INF number.
* @see com.alibaba.nacos.client.logger.json.JSONObject#toJSONString(Map)
*/
public static String toJSONString(Object value){
public static String toJSONString(Object value) {
final StringWriter writer = new StringWriter();
try{
try {
writeJSONString(value, writer);
return writer.toString();
} catch(IOException e){
} catch (IOException e) {
// This should never happen for a StringWriter
throw new RuntimeException(e);
}
@ -271,11 +243,12 @@ public class JSONValue {
/**
* Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
*
* @param s
* @return
*/
public static String escape(String s){
if(s==null) {
public static String escape(String s) {
if (s == null) {
return null;
}
StringBuffer sb = new StringBuffer();
@ -289,9 +262,9 @@ public class JSONValue {
*/
static void escape(String s, StringBuffer sb) {
final int len = s.length();
for(int i=0;i<len;i++){
char ch=s.charAt(i);
switch(ch){
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
@ -318,15 +291,14 @@ public class JSONValue {
break;
default:
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
if(isUnicodeChar(ch)){
String ss=Integer.toHexString(ch);
if (isUnicodeChar(ch)) {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for(int k=0;k<FOUR-ss.length();k++){
for (int k = 0; k < FOUR - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
}
else{
} else {
sb.append(ch);
}
}

View File

@ -21,20 +21,23 @@ import java.util.Map;
/**
* Container factory for creating containers for JSON object and JSON array.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContainerFactory)
*
* @author FangYidong<fangyidong@yahoo.com.cn>
*/
public interface ContainerFactory {
/**
* create json container
* @return A Map instance to store JSON object, or null if you want to use com.alibaba.nacos.client.logger.jsonJSONObject.
*
* @return A Map instance to store JSON object, or null if you want to use com.alibaba.nacos.client.logger
* .jsonJSONObject.
*/
Map createObjectContainer();
/**
* create array json container
* @return A List instance to store JSON array, or null if you want to use com.alibaba.nacos.client.logger.jsonJSONArray.
*
* @return A List instance to store JSON array, or null if you want to use com.alibaba.nacos.client.logger
* .jsonJSONArray.
*/
List creatArrayContainer();
}

View File

@ -20,18 +20,16 @@ import java.io.IOException;
/**
* A simplified and stoppable SAX-like content handler for stream processing of JSON text.
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
* @see org.xml.sax.ContentHandler
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean)
*
* @author FangYidong<fangyidong@yahoo.com.cn>
*/
public interface ContentHandler {
/**
* Receive notification of the beginning of JSON processing.
* The parser will invoke this method only once.
* Receive notification of the beginning of JSON processing. The parser will invoke this method only once.
*
* @throws ParseException
* - JSONParser will stop and throw the same exception to the caller when receiving this exception.
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
* exception.
* @throws IOException
*/
void startJSON() throws ParseException, IOException;
@ -48,8 +46,8 @@ public interface ContentHandler {
* Receive notification of the beginning of a JSON object.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* - JSONParser will stop and throw the same exception to the caller when receiving this exception.
* @throws ParseException - JSONParser will stop and throw the same exception to the caller when receiving this
* exception.
* @throws IOException
* @see #endJSON
*/
@ -69,7 +67,6 @@ public interface ContentHandler {
* Receive notification of the beginning of a JSON object entry.
*
* @param key - Key of a JSON object entry.
*
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException
@ -108,18 +105,9 @@ public interface ContentHandler {
boolean endArray() throws ParseException, IOException;
/**
* Receive notification of the JSON primitive values:
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean
* null
*
* @param value - Instance of the following:
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean
* null
* Receive notification of the JSON primitive values: java.lang.String, java.lang.Number, java.lang.Boolean null
*
* @param value - Instance of the following: java.lang.String, java.lang.Number, java.lang.Boolean null
* @return false if the handler wants to stop parsing after return.
* @throws ParseException
* @throws IOException

View File

@ -29,41 +29,39 @@ import java.util.Map;
import com.alibaba.nacos.client.logger.json.JSONArray;
import com.alibaba.nacos.client.logger.json.JSONObject;
/**
* Parser for JSON text. Please note that JSONParser is NOT thread-safe.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JSONParser {
public static final int S_INIT=0;
public static final int S_IN_FINISHED_VALUE=1;
public static final int S_IN_OBJECT=2;
public static final int S_IN_ARRAY=3;
public static final int S_PASSED_PAIR_KEY=4;
public static final int S_IN_PAIR_VALUE=5;
public static final int S_END=6;
public static final int S_IN_ERROR=-1;
public static final int S_INIT = 0;
public static final int S_IN_FINISHED_VALUE = 1;
public static final int S_IN_OBJECT = 2;
public static final int S_IN_ARRAY = 3;
public static final int S_PASSED_PAIR_KEY = 4;
public static final int S_IN_PAIR_VALUE = 5;
public static final int S_END = 6;
public static final int S_IN_ERROR = -1;
private LinkedList handlerStatusStack;
private Yylex lexer = new Yylex((Reader)null);
private Yytoken token = null;
private int status = S_INIT;
private int peekStatus(LinkedList statusStack){
if(statusStack.size()==0) {
private int peekStatus(LinkedList statusStack) {
if (statusStack.size() == 0) {
return -1;
}
Integer status=(Integer)statusStack.getFirst();
Integer status = (Integer)statusStack.getFirst();
return status.intValue();
}
/**
* Reset the parser to the initial state without resetting the underlying reader.
*
*/
public void reset(){
public void reset() {
token = null;
status = S_INIT;
handlerStatusStack = null;
@ -76,7 +74,7 @@ public class JSONParser {
* @throws IOException
* @throws ParseException
*/
public void reset(Reader in){
public void reset(Reader in) {
lexer.yyreset(in);
reset();
}
@ -84,20 +82,19 @@ public class JSONParser {
/**
* @return The position of the beginning of the current token.
*/
public int getPosition(){
public int getPosition() {
return lexer.getPosition();
}
public Object parse(String s) throws ParseException{
public Object parse(String s) throws ParseException {
return parse(s, (ContainerFactory)null);
}
public Object parse(String s, ContainerFactory containerFactory) throws ParseException{
StringReader in=new StringReader(s);
try{
public Object parse(String s, ContainerFactory containerFactory) throws ParseException {
StringReader in = new StringReader(s);
try {
return parse(in, containerFactory);
}
catch(IOException ie){
} catch (IOException ie) {
/*
* Actually it will never happen.
*/
@ -105,7 +102,7 @@ public class JSONParser {
}
}
public Object parse(Reader in) throws IOException, ParseException{
public Object parse(Reader in) throws IOException, ParseException {
return parse(in, (ContainerFactory)null);
}
@ -114,158 +111,148 @@ public class JSONParser {
*
* @param in
* @param containerFactory - Use this factory to createyour own JSON object and JSON array containers.
* @return Instance of the following:
* com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray,
* java.lang.String,
* java.lang.Number,
* java.lang.Boolean,
* null
*
* @return Instance of the following: com.alibaba.nacos.client.logger.jsonJSONObject,
* com.alibaba.nacos.client.logger.jsonJSONArray, java.lang.String, java.lang.Number, java.lang.Boolean, null
* @throws IOException
* @throws ParseException
*/
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{
public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException {
reset(in);
LinkedList statusStack = new LinkedList();
LinkedList valueStack = new LinkedList();
try{
do{
try {
do {
nextToken();
switch(status){
switch (status) {
case S_INIT:
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_VALUE:
status=S_IN_FINISHED_VALUE;
status = S_IN_FINISHED_VALUE;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(token.value);
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(createObjectContainer(containerFactory));
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(createArrayContainer(containerFactory));
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
if(token.type==Yytoken.TYPE_EOF) {
if (token.type == Yytoken.TYPE_EOF) {
return valueStack.removeFirst();
}
else {
} else {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
case S_IN_OBJECT:
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(token.value instanceof String){
String key=(String)token.value;
if (token.value instanceof String) {
String key = (String)token.value;
valueStack.addFirst(key);
status=S_PASSED_PAIR_KEY;
status = S_PASSED_PAIR_KEY;
statusStack.addFirst(Integer.valueOf(status));
}
else{
status=S_IN_ERROR;
} else {
status = S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if(valueStack.size()>1){
if (valueStack.size() > 1) {
statusStack.removeFirst();
valueStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
String key=(String)valueStack.removeFirst();
Map parent=(Map)valueStack.getFirst();
parent.put(key,token.value);
status=peekStatus(statusStack);
String key = (String)valueStack.removeFirst();
Map parent = (Map)valueStack.getFirst();
parent.put(key, token.value);
status = peekStatus(statusStack);
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
key=(String)valueStack.removeFirst();
parent=(Map)valueStack.getFirst();
List newArray=createArrayContainer(containerFactory);
parent.put(key,newArray);
status=S_IN_ARRAY;
key = (String)valueStack.removeFirst();
parent = (Map)valueStack.getFirst();
List newArray = createArrayContainer(containerFactory);
parent.put(key, newArray);
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newArray);
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
key=(String)valueStack.removeFirst();
parent=(Map)valueStack.getFirst();
Map newObject=createObjectContainer(containerFactory);
parent.put(key,newObject);
status=S_IN_OBJECT;
key = (String)valueStack.removeFirst();
parent = (Map)valueStack.getFirst();
Map newObject = createObjectContainer(containerFactory);
parent.put(key, newObject);
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newObject);
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}
break;
case S_IN_ARRAY:
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
List val=(List)valueStack.getFirst();
List val = (List)valueStack.getFirst();
val.add(token.value);
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if(valueStack.size()>1){
if (valueStack.size() > 1) {
statusStack.removeFirst();
valueStack.removeFirst();
status=peekStatus(statusStack);
}
else{
status=S_IN_FINISHED_VALUE;
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
val=(List)valueStack.getFirst();
Map newObject=createObjectContainer(containerFactory);
val = (List)valueStack.getFirst();
Map newObject = createObjectContainer(containerFactory);
val.add(newObject);
status=S_IN_OBJECT;
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newObject);
break;
case Yytoken.TYPE_LEFT_SQUARE:
val=(List)valueStack.getFirst();
List newArray=createArrayContainer(containerFactory);
val = (List)valueStack.getFirst();
List newArray = createArrayContainer(containerFactory);
val.add(newArray);
status=S_IN_ARRAY;
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
valueStack.addFirst(newArray);
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_ERROR:
@ -273,59 +260,57 @@ public class JSONParser {
default:
break;
}//switch
if(status==S_IN_ERROR){
if (status == S_IN_ERROR) {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}while(token.type!=Yytoken.TYPE_EOF);
}
catch(IOException ie){
} while (token.type != Yytoken.TYPE_EOF);
} catch (IOException ie) {
throw ie;
}
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
private void nextToken() throws ParseException, IOException{
private void nextToken() throws ParseException, IOException {
token = lexer.yylex();
if(token == null) {
if (token == null) {
token = new Yytoken(Yytoken.TYPE_EOF, null);
}
}
private Map createObjectContainer(ContainerFactory containerFactory){
if(containerFactory == null) {
private Map createObjectContainer(ContainerFactory containerFactory) {
if (containerFactory == null) {
return new JSONObject();
}
Map m = containerFactory.createObjectContainer();
if(m == null) {
if (m == null) {
return new JSONObject();
}
return m;
}
private List createArrayContainer(ContainerFactory containerFactory){
if(containerFactory == null) {
private List createArrayContainer(ContainerFactory containerFactory) {
if (containerFactory == null) {
return new JSONArray();
}
List l = containerFactory.creatArrayContainer();
if(l == null) {
if (l == null) {
return new JSONArray();
}
return l;
}
public void parse(String s, ContentHandler contentHandler) throws ParseException{
public void parse(String s, ContentHandler contentHandler) throws ParseException {
parse(s, contentHandler, false);
}
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{
StringReader in=new StringReader(s);
try{
public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException {
StringReader in = new StringReader(s);
try {
parse(in, contentHandler, isResume);
}
catch(IOException ie){
} catch (IOException ie) {
/*
* Actually it will never happen.
*/
@ -333,31 +318,28 @@ public class JSONParser {
}
}
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{
public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException {
parse(in, contentHandler, false);
}
/**
* Stream processing of JSON text.
*
* @see ContentHandler
*
* @param in
* @param contentHandler
* @param isResume - Indicates if it continues previous parsing operation.
* If set to true, resume parsing the old stream, and parameter 'in' will be ignored.
* If this method is called for the first time in this instance, isResume will be ignored.
*
* @param isResume - Indicates if it continues previous parsing operation. If set to true, resume parsing the
* old stream, and parameter 'in' will be ignored. If this method is called for the first time
* in this instance, isResume will be ignored.
* @throws IOException
* @throws ParseException
* @see ContentHandler
*/
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{
if(!isResume){
public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException {
if (!isResume) {
reset(in);
handlerStatusStack = new LinkedList();
}
else{
if(handlerStatusStack == null){
} else {
if (handlerStatusStack == null) {
isResume = false;
reset(in);
handlerStatusStack = new LinkedList();
@ -366,122 +348,119 @@ public class JSONParser {
LinkedList statusStack = handlerStatusStack;
try{
do{
switch(status){
try {
do {
switch (status) {
case S_INIT:
contentHandler.startJSON();
nextToken();
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_VALUE:
status=S_IN_FINISHED_VALUE;
status = S_IN_FINISHED_VALUE;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.primitive(token.value)) {
if (!contentHandler.primitive(token.value)) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startObject()) {
if (!contentHandler.startObject()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startArray()) {
if (!contentHandler.startArray()) {
return;
}
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}//inner switch
break;
case S_IN_FINISHED_VALUE:
nextToken();
if(token.type==Yytoken.TYPE_EOF){
if (token.type == Yytoken.TYPE_EOF) {
contentHandler.endJSON();
status = S_END;
return;
}
else{
} else {
status = S_IN_ERROR;
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
case S_IN_OBJECT:
nextToken();
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(token.value instanceof String){
String key=(String)token.value;
status=S_PASSED_PAIR_KEY;
if (token.value instanceof String) {
String key = (String)token.value;
status = S_PASSED_PAIR_KEY;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startObjectEntry(key)) {
if (!contentHandler.startObjectEntry(key)) {
return;
}
}
else{
status=S_IN_ERROR;
} else {
status = S_IN_ERROR;
}
break;
case Yytoken.TYPE_RIGHT_BRACE:
if(statusStack.size()>1){
if (statusStack.size() > 1) {
statusStack.removeFirst();
status=peekStatus(statusStack);
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
else{
status=S_IN_FINISHED_VALUE;
}
if(!contentHandler.endObject()) {
if (!contentHandler.endObject()) {
return;
}
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
break;
}//inner switch
break;
case S_PASSED_PAIR_KEY:
nextToken();
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COLON:
break;
case Yytoken.TYPE_VALUE:
statusStack.removeFirst();
status=peekStatus(statusStack);
if(!contentHandler.primitive(token.value)) {
status = peekStatus(statusStack);
if (!contentHandler.primitive(token.value)) {
return;
}
if(!contentHandler.endObjectEntry()) {
if (!contentHandler.endObjectEntry()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
statusStack.removeFirst();
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
status=S_IN_ARRAY;
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startArray()) {
if (!contentHandler.startArray()) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
statusStack.removeFirst();
statusStack.addFirst(Integer.valueOf(S_IN_PAIR_VALUE));
status=S_IN_OBJECT;
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startObject()) {
if (!contentHandler.startObject()) {
return;
}
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}
break;
@ -492,49 +471,48 @@ public class JSONParser {
*/
statusStack.removeFirst();
status = peekStatus(statusStack);
if(!contentHandler.endObjectEntry()) {
if (!contentHandler.endObjectEntry()) {
return;
}
break;
case S_IN_ARRAY:
nextToken();
switch(token.type){
switch (token.type) {
case Yytoken.TYPE_COMMA:
break;
case Yytoken.TYPE_VALUE:
if(!contentHandler.primitive(token.value)) {
if (!contentHandler.primitive(token.value)) {
return;
}
break;
case Yytoken.TYPE_RIGHT_SQUARE:
if(statusStack.size()>1){
if (statusStack.size() > 1) {
statusStack.removeFirst();
status=peekStatus(statusStack);
status = peekStatus(statusStack);
} else {
status = S_IN_FINISHED_VALUE;
}
else{
status=S_IN_FINISHED_VALUE;
}
if(!contentHandler.endArray()) {
if (!contentHandler.endArray()) {
return;
}
break;
case Yytoken.TYPE_LEFT_BRACE:
status=S_IN_OBJECT;
status = S_IN_OBJECT;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startObject()) {
if (!contentHandler.startObject()) {
return;
}
break;
case Yytoken.TYPE_LEFT_SQUARE:
status=S_IN_ARRAY;
status = S_IN_ARRAY;
statusStack.addFirst(Integer.valueOf(status));
if(!contentHandler.startArray()) {
if (!contentHandler.startArray()) {
return;
}
break;
default:
status=S_IN_ERROR;
status = S_IN_ERROR;
}//inner switch
break;
@ -546,24 +524,20 @@ public class JSONParser {
default:
break;
}//switch
if(status==S_IN_ERROR){
if (status == S_IN_ERROR) {
throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token);
}
}while(token.type!=Yytoken.TYPE_EOF);
}
catch(IOException ie){
} while (token.type != Yytoken.TYPE_EOF);
} catch (IOException ie) {
status = S_IN_ERROR;
throw ie;
}
catch(ParseException pe){
} catch (ParseException pe) {
status = S_IN_ERROR;
throw pe;
}
catch(RuntimeException re){
} catch (RuntimeException re) {
status = S_IN_ERROR;
throw re;
}
catch(Error e){
} catch (Error e) {
status = S_IN_ERROR;
throw e;
}

View File

@ -18,8 +18,7 @@ package com.alibaba.nacos.client.logger.json.parser;
/**
* ParseException explains why and where the error occurs in source JSON text.
*
* @author FangYidong<fangyidong@yahoo.com.cn>
*
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
public class ParseException extends Exception {
private static final long serialVersionUID = -7880698968187728547L;
@ -32,15 +31,15 @@ public class ParseException extends Exception {
private Object unexpectedObject;
private int position;
public ParseException(int errorType){
public ParseException(int errorType) {
this(-1, errorType, null);
}
public ParseException(int errorType, Object unexpectedObject){
public ParseException(int errorType, Object unexpectedObject) {
this(-1, errorType, unexpectedObject);
}
public ParseException(int position, int errorType, Object unexpectedObject){
public ParseException(int position, int errorType, Object unexpectedObject) {
this.position = position;
this.errorType = errorType;
this.unexpectedObject = unexpectedObject;
@ -55,9 +54,8 @@ public class ParseException extends Exception {
}
/**
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#getPosition()
*
* @return The character position (starting with 0) of the input where the error occurs.
* @see com.alibaba.nacos.client.logger.json.parser.JSONParser#getPosition()
*/
public int getPosition() {
return position;
@ -68,12 +66,10 @@ public class ParseException extends Exception {
}
/**
* @return One of the following base on the value of errorType: ERROR_UNEXPECTED_CHAR java.lang.Character
* ERROR_UNEXPECTED_TOKEN com.alibaba.nacos.client.logger.jsonparser.Yytoken ERROR_UNEXPECTED_EXCEPTION
* java.lang.Exception
* @see com.alibaba.nacos.client.logger.json.parser.Yytoken
*
* @return One of the following base on the value of errorType:
* ERROR_UNEXPECTED_CHAR java.lang.Character
* ERROR_UNEXPECTED_TOKEN com.alibaba.nacos.client.logger.jsonparser.Yytoken
* ERROR_UNEXPECTED_EXCEPTION java.lang.Exception
*/
public Object getUnexpectedObject() {
return unexpectedObject;
@ -86,12 +82,14 @@ public class ParseException extends Exception {
public String getMessage() {
StringBuffer sb = new StringBuffer();
switch(errorType){
switch (errorType) {
case ERROR_UNEXPECTED_CHAR:
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append(".");
sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position)
.append(".");
break;
case ERROR_UNEXPECTED_TOKEN:
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(".");
sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append(
".");
break;
case ERROR_UNEXPECTED_EXCEPTION:
sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject);

View File

@ -23,28 +23,32 @@ import java.io.UnsupportedEncodingException;
/**
* Yylex
* @author Nacos
*
* @author Nacos
*/
class Yylex {
/** This character denotes the end of file */
/**
* This character denotes the end of file
*/
public static final int YYEOF = -1;
/** initial size of the lookahead buffer */
/**
* initial size of the lookahead buffer
*/
private static final int ZZ_BUFFERSIZE = 16384;
/** lexical states */
/**
* lexical states
*/
public static final int YYINITIAL = 0;
public static final int STRING_BEGIN = 2;
/**
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
* ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
* at the beginning of a line
* l is of the form l = 2*k, k a non negative integer
* ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l ZZ_LEXSTATE[l+1] is the state in the DFA for the
* lexical state l at the beginning of a line l is of the form l = 2*k, k a non negative integer
*/
private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 };
private static final int ZZ_LEXSTATE[] = {0, 0, 1, 1};
/**
* Translates characters to character classes
@ -82,7 +86,7 @@ class Yylex {
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
do { result[j++] = value; } while (--count > 0);
}
return j;
}
@ -118,7 +122,7 @@ class Yylex {
/**
* The transition table of the DFA
*/
private static final int ZZ_TRANS[] = { 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12,
private static final int ZZ_TRANS[] = {2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12,
13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
@ -153,7 +157,7 @@ class Yylex {
-1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, -1, -1,
43, 43, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, -1,
44, -1, 44, -1, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, 44, 44, -1, -1, -1,
-1, -1, -1, -1, -1, };
-1, -1, -1, -1, -1,};
/**
* error codes
@ -165,8 +169,8 @@ class Yylex {
/**
* error messages for the codes above
*/
private static final String[] ZZ_ERROR_MSG = { "Unkown internal scanner error", "Error: could not match input",
"Error: pushback value was too large" };
private static final String[] ZZ_ERROR_MSG = {"Unkown internal scanner error", "Error: could not match input",
"Error: pushback value was too large"};
/**
* ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code>
@ -190,45 +194,59 @@ class Yylex {
while (i < l) {
int count = packed.charAt(i++);
int value = packed.charAt(i++);
do result[j++] = value; while (--count > 0);
do { result[j++] = value; } while (--count > 0);
}
return j;
}
/** the input device */
/**
* the input device
*/
private java.io.Reader zzReader;
/** the current state of the DFA */
/**
* the current state of the DFA
*/
private int zzState;
/** the current lexical state */
/**
* the current lexical state
*/
private int zzLexicalState = YYINITIAL;
/**
* this buffer contains the current text to be matched and is
* the source of the yytext() string
* this buffer contains the current text to be matched and is the source of the yytext() string
*/
private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
/** the textposition at the last accepting state */
/**
* the textposition at the last accepting state
*/
private int zzMarkedPos;
/** the current text position in the buffer */
/**
* the current text position in the buffer
*/
private int zzCurrentPos;
/** startRead marks the beginning of the yytext() string in the buffer */
/**
* startRead marks the beginning of the yytext() string in the buffer
*/
private int zzStartRead;
/**
* endRead marks the last character in the buffer, that has been read
* from input
* endRead marks the last character in the buffer, that has been read from input
*/
private int zzEndRead;
/** the number of characters up to the start of the matched text */
/**
* the number of characters up to the start of the matched text
*/
private int yychar;
/** zzAtEOF == true <=> the scanner is at the EOF */
/**
* zzAtEOF == true <=> the scanner is at the EOF
*/
private boolean zzAtEOF;
/**
@ -241,8 +259,7 @@ class Yylex {
}
/**
* Creates a new scanner
* There is also a java.io.InputStream version of this constructor.
* Creates a new scanner There is also a java.io.InputStream version of this constructor.
*
* @param in the java.io.Reader to read input from.
*/
@ -251,8 +268,7 @@ class Yylex {
}
/**
* Creates a new scanner.
* There is also java.io.Reader version of this constructor.
* Creates a new scanner. There is also java.io.Reader version of this constructor.
*
* @param in the java.io.Inputstream to read input from.
* @throws UnsupportedEncodingException
@ -274,7 +290,7 @@ class Yylex {
while (i < NIGTY) {
int count = packed.charAt(i++);
char value = packed.charAt(i++);
do map[j++] = value; while (--count > 0);
do { map[j++] = value; } while (--count > 0);
}
return map;
}
@ -319,7 +335,7 @@ class Yylex {
if (c == -1) {
return true;
} else {
zzBuffer[zzEndRead++] = (char) c;
zzBuffer[zzEndRead++] = (char)c;
return false;
}
}
@ -341,11 +357,9 @@ class Yylex {
}
/**
* Resets the scanner to read from a new input stream.
* Does not close the old reader.
* All internal variables are reset, the old input stream
* <b>cannot</b> be reused (internal buffer is discarded and lost).
* Lexical state is set to <tt>ZZ_INITIAL</tt>.
* Resets the scanner to read from a new input stream. Does not close the old reader. All internal variables are
* reset, the old input stream <b>cannot</b> be reused (internal buffer is discarded and lost). Lexical state is set
* to <tt>ZZ_INITIAL</tt>.
*
* @param reader the new input stream
*/
@ -381,12 +395,10 @@ class Yylex {
}
/**
* Returns the character at position <tt>pos</tt> from the
* matched text.
* It is equivalent to yytext().charAt(pos), but faster
* Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos),
* but faster
*
* @param pos the position of the character to fetch.
* A value from 0 to yylength()-1.
* @param pos the position of the character to fetch. A value from 0 to yylength()-1.
* @return the character at position pos
*/
public final char yycharat(int pos) {
@ -401,14 +413,10 @@ class Yylex {
}
/**
* Reports an error that occured while scanning.
* In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method
* will only be called with things that "Can't Possibly Happen".
* If this method is called, something is seriously wrong
* (e.g. a JFlex bug producing a faulty scanner etc.).
* Usual syntax/scanner level error handling should be done
* in error fallback rules.
* Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of
* yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly
* Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner
* etc.). Usual syntax/scanner level error handling should be done in error fallback rules.
*
* @param errorCode the code of the errormessage to display
*/
@ -424,11 +432,10 @@ class Yylex {
}
/**
* Pushes the specified amount of characters back into the input stream.
* They will be read again by then next call of the scanning method
* Pushes the specified amount of characters back into the input stream. They will be read again by then next call
* of the scanning method
*
* @param number the number of characters to be read again.
* This number must not be greater than yylength()!
* @param number the number of characters to be read again. This number must not be greater than yylength()!
*/
public void yypushback(int number) {
if (number > yylength()) {
@ -439,8 +446,8 @@ class Yylex {
}
/**
* Resumes scanning until the next regular expression is matched,
* the end of input is encountered or an I/O-Error occurs.
* Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error
* occurs.
*
* @return the next token
* @throws java.io.IOException if any I/O-Error occurs
@ -478,8 +485,7 @@ class Yylex {
if (zzCurrentPosL < zzEndReadL) {
zzInput = zzBufferL[zzCurrentPosL++];
}
else if (zzAtEOF) {
} else if (zzAtEOF) {
zzInput = YYEOF;
break zzForAction;
} else {
@ -572,7 +578,8 @@ class Yylex {
case 33:
break;
case 1: {
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, Character.valueOf(yycharat(0)));
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR,
Character.valueOf(yycharat(0)));
}
case 34:
break;
@ -614,7 +621,7 @@ class Yylex {
case 24: {
try {
int ch = Integer.parseInt(yytext().substring(2), 16);
sb.append((char) ch);
sb.append((char)ch);
} catch (Exception e) {
throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e);
}

View File

@ -20,35 +20,35 @@
package com.alibaba.nacos.client.logger.json.parser;
/**
* @author FangYidong<fangyidong@yahoo.com.cn>
* @author FangYidong<fangyidong @ yahoo.com.cn>
*/
public class Yytoken {
/**
* JSON primitive value: string,number,boolean,null
*/
public static final int TYPE_VALUE=0;
public static final int TYPE_LEFT_BRACE=1;
public static final int TYPE_RIGHT_BRACE=2;
public static final int TYPE_LEFT_SQUARE=3;
public static final int TYPE_RIGHT_SQUARE=4;
public static final int TYPE_COMMA=5;
public static final int TYPE_COLON=6;
public static final int TYPE_VALUE = 0;
public static final int TYPE_LEFT_BRACE = 1;
public static final int TYPE_RIGHT_BRACE = 2;
public static final int TYPE_LEFT_SQUARE = 3;
public static final int TYPE_RIGHT_SQUARE = 4;
public static final int TYPE_COMMA = 5;
public static final int TYPE_COLON = 6;
/**
* end of file
*/
public static final int TYPE_EOF=-1;
public static final int TYPE_EOF = -1;
public int type=0;
public Object value=null;
public int type = 0;
public Object value = null;
public Yytoken(int type,Object value){
this.type=type;
this.value=value;
public Yytoken(int type, Object value) {
this.type = type;
this.value = value;
}
public String toString(){
public String toString() {
StringBuffer sb = new StringBuffer();
switch(type){
switch (type) {
case TYPE_VALUE:
sb.append("VALUE(").append(value).append(")");
break;

View File

@ -1,146 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.log4j;
import org.apache.log4j.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.Log4jActivateOption;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil;
/**
* Log4jLogger
* @author Nacos
*
*/
public class Log4jLogger extends LoggerSupport implements Logger {
private org.apache.log4j.Logger delegate;
public Log4jLogger(org.apache.log4j.Logger delegate) {
super(delegate);
if (delegate == null) {
throw new IllegalArgumentException("delegate Logger is null");
}
this.delegate = delegate;
this.activateOption = new Log4jActivateOption(delegate);
}
@Override
public void debug(String context, String message) {
if (isDebugEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.debug(MessageUtil.getMessage(context, message));
}
}
@Override
public void debug(String context, String format, Object... args) {
if (isDebugEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.debug(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void info(String context, String message) {
if (isInfoEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.info(MessageUtil.getMessage(context, message));
}
}
@Override
public void info(String context, String format, Object... args) {
if (isInfoEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.info(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void warn(String message, Throwable t) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(null, message), t);
}
}
@Override
public void warn(String context, String message) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(context, message));
}
}
@Override
public void warn(String context, String format, Object... args) {
if (isWarnEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.warn(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void error(String context, String errorCode, String message) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message));
}
}
@Override
public void error(String context, String errorCode, String message, Throwable t) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message), t);
}
}
@Override
public void error(String context, String errorCode, String format, Object... args) {
if (isErrorEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.error(MessageUtil.getMessage(context, errorCode, MessageUtil.formatMessage(format, args)));
}
}
@Override
public boolean isDebugEnabled() {
return delegate.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return delegate.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return delegate.isEnabledFor(Level.WARN);
}
@Override
public boolean isErrorEnabled() {
return delegate.isEnabledFor(Level.ERROR);
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.log4j;
import org.apache.log4j.LogManager;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.nop.NopLogger;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
/**
* Log4jLogger Factory
* @author Nacos
*
*/
public class Log4jLoggerFactory implements ILoggerFactory {
public Log4jLoggerFactory() throws ClassNotFoundException {
Class.forName("org.apache.log4j.Level");
}
public Logger getLogger(Class<?> clazz) {
try {
return new Log4jLogger(LogManager.getLogger(clazz));
} catch (Throwable t) {
LogLog.error("Failed to get Log4jLogger", t);
return new NopLogger();
}
}
public Logger getLogger(String name) {
try {
return new Log4jLogger(LogManager.getLogger(name));
} catch (Throwable t) {
LogLog.error("Failed to get Log4jLogger", t);
return new NopLogger();
}
}
}

View File

@ -21,11 +21,10 @@ import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil;
/**
* Log4j2Logger
* @author Nacos
*
* @author Nacos
*/
public class Log4j2Logger extends LoggerSupport implements Logger {

Some files were not shown because too many files have changed in this diff Show More