Apply checkstyle to the build

Please note that the build will fail at the moment due to various checkstyle
violations which should be fixed soon
This commit is contained in:
Trustin Lee 2012-01-11 20:16:14 +09:00
parent c38e6c77c2
commit ebfc4513e0
188 changed files with 3219 additions and 3061 deletions

2
.gitignore vendored
View File

@ -5,7 +5,7 @@
*.ipr
*.iws
.geany
*/target
/target
*/target
/reports
*/reports

View File

@ -135,7 +135,7 @@ public abstract class AbstractChannelBuffer implements ChannelBuffer {
@Override
public boolean getBoolean(int index) {
return (getByte(index) == 1);
return getByte(index) != 0;
}
@Override
@ -278,7 +278,7 @@ public abstract class AbstractChannelBuffer implements ChannelBuffer {
@Override
public boolean readBoolean() {
return (readByte() == 1);
return readByte() != 0;
}
@Override

View File

@ -47,7 +47,7 @@ import java.nio.charset.UnsupportedCharsetException;
*
* <pre>
* {@link ChannelBuffer} buffer = ...;
* for (int i = 0; i &lt; buffer.capacity(); i ++</strong>) {
* for (int i = 0; i &lt; buffer.capacity(); i ++) {
* byte b = buffer.getByte(i);
* System.out.println((char) b);
* }

View File

@ -84,7 +84,7 @@ import io.netty.util.CharsetUtil;
* @apiviz.landmark
* @apiviz.has io.netty.buffer.ChannelBuffer oneway - - creates
*/
public class ChannelBuffers {
public final class ChannelBuffers {
/**
* Big endian byte order.
@ -307,7 +307,11 @@ public class ChannelBuffers {
return EMPTY_BUFFER;
}
if (buffer.hasArray()) {
return wrappedBuffer(buffer.order(), buffer.array(), buffer.arrayOffset() + buffer.position(),buffer.remaining());
return wrappedBuffer(
buffer.order(),
buffer.array(),
buffer.arrayOffset() + buffer.position(),
buffer.remaining());
} else {
return new ByteBufferBackedChannelBuffer(buffer);
}

View File

@ -57,9 +57,9 @@ public class DirectChannelBufferFactory extends AbstractChannelBufferFactory {
private final Object bigEndianLock = new Object();
private final Object littleEndianLock = new Object();
private final int preallocatedBufferCapacity;
private ChannelBuffer preallocatedBigEndianBuffer = null;
private ChannelBuffer preallocatedBigEndianBuffer;
private int preallocatedBigEndianBufferPosition;
private ChannelBuffer preallocatedLittleEndianBuffer = null;
private ChannelBuffer preallocatedLittleEndianBuffer;
private int preallocatedLittleEndianBufferPosition;
/**

55
build/pom.xml Normal file
View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2011 The Netty Project
~
~ The Netty Project licenses this file to you under the Apache License,
~ version 2.0 (the "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at:
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
~ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
~ License for the specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.netty</groupId>
<artifactId>netty-parent</artifactId>
<version>4.0.0.Alpha1-SNAPSHOT</version>
</parent>
<groupId>io.netty</groupId>
<artifactId>netty-build</artifactId>
<version>1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Netty/Build</name>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>5.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-checkstyle-plugin</artifactId>
<executions>
<execution>
<id>check-style</id>
<phase>none</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,23 @@
package io.netty.build.checkstyle;
import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.FilterSet;
public class SuppressionFilter extends AutomaticBean implements Filter {
private FilterSet filters = new FilterSet();
private Pattern pattern;
public void setPattern(String pattern) {
this.pattern = Pattern.compile(pattern);
}
@Override
public boolean accept(AuditEvent evt) {
return !pattern.matcher(evt.getFileName()).find();
}
}

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.2//EN"
"http://www.puppycrawl.com/dtds/configuration_1_2.dtd">
<module name="Checker">
<module name="io.netty.build.checkstyle.SuppressionFilter">
<property name="pattern" value="(test[^/]*/.*|LocalTimeProtocol|LinkedTransferQueue|jzlib/.*|com/sun/nio/sctp/.*)\.java" />
</module>
<module name="FileTabCharacter"/>
<module name="JavadocPackage"/>
<module name="NewlineAtEndOfFile"/>
<module name="RegexpSingleline">
<property name="format" value="@(author|version)"/>
<property name="ignoreCase" value="true"/>
</module>
<module name="TreeWalker">
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround">
<property name="tokens" value="ASSIGN, BAND, BAND_ASSIGN, BOR, BOR_ASSIGN, BSR, BSR_ASSIGN, BXOR, BXOR_ASSIGN, DIV, DIV_ASSIGN, EQUAL, GE, GT, LAND, LCURLY, LE, LITERAL_ASSERT, LITERAL_CATCH, LITERAL_DO, LITERAL_ELSE, LITERAL_FINALLY, LITERAL_FOR, LITERAL_IF, LITERAL_RETURN, LITERAL_SYNCHRONIZED, LITERAL_TRY, LITERAL_WHILE, LOR, LT, MINUS, MINUS_ASSIGN, MOD, MOD_ASSIGN, NOT_EQUAL, PLUS, PLUS_ASSIGN, RCURLY, SL, SLIST, SL_ASSIGN, SR, SR_ASSIGN, STAR, STAR_ASSIGN, TYPE_EXTENSION_AND, DEC, INC"/>
</module>
<!-- Commented out due to false positives.
<module name="MissingDeprecated"/>
-->
<module name="MissingOverride"/>
<module name="PackageAnnotation"/>
<module name="EmptyBlock">
<property name="option" value="text"/>
</module>
<module name="LeftCurly"/>
<module name="RightCurly"/>
<module name="NeedBraces"/>
<module name="AvoidNestedBlocks">
<property name="allowInSwitchCase" value="true"/>
</module>
<module name="FinalClass"/>
<module name="InterfaceIsType"/>
<module name="HideUtilityClassConstructor"/>
<module name="CovariantEquals"/>
<module name="DoubleCheckedLocking"/>
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<!--
<module name="FinalLocalVariable"/>
-->
<module name="RedundantThrows">
<property name="logLoadErrors" value="false"/>
<property name="suppressLoadErrors" value="true"/>
</module>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<module name="NoFinalizer"/>
<module name="SuperClone"/>
<module name="SuperFinalize"/>
<module name="PackageDeclaration"/>
<module name="ExplicitInitialization"/>
<module name="DefaultComesLast"/>
<module name="UnnecessaryParentheses"/>
<module name="AvoidStarImport">
<property name="allowStaticMemberImports" value="true"/>
</module>
<module name="RedundantImport"/>
<!-- Commented out due to false positives.
<module name="UnusedImports">
<property name="processJavadoc" value="true"/>
</module>
-->
<module name="JavadocStyle">
<property name="checkFirstSentence" value="false"/>
</module>
<module name="UpperEll"/>
<module name="ArrayTypeStyle"/>
<module name="OuterTypeFilename"/>
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<module name="GenericWhitespace"/>
<module name="EmptyForInitializerPad"/>
<module name="EmptyForIteratorPad"/>
<module name="MethodParamPad"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
</module>
</module>

View File

@ -32,14 +32,11 @@ import io.netty.buffer.ChannelBuffers;
*/
public abstract class AbstractDiskHttpData extends AbstractHttpData {
protected File file = null;
protected File file;
private boolean isRenamed;
private FileChannel fileChannel;
private boolean isRenamed = false;
private FileChannel fileChannel = null;
public AbstractDiskHttpData(String name, Charset charset, long size)
throws NullPointerException, IllegalArgumentException {
public AbstractDiskHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}

View File

@ -23,17 +23,12 @@ import java.nio.charset.Charset;
public abstract class AbstractHttpData implements HttpData {
protected final String name;
protected long definedSize = 0;
protected long size = 0;
protected long definedSize;
protected long size;
protected Charset charset = HttpCodecUtil.DEFAULT_CHARSET;
protected boolean completed;
protected boolean completed = false;
public AbstractHttpData(String name, Charset charset, long size)
throws NullPointerException, IllegalArgumentException {
public AbstractHttpData(String name, Charset charset, long size) {
if (name == null) {
throw new NullPointerException("name");
}

View File

@ -32,14 +32,11 @@ import io.netty.buffer.ChannelBuffers;
*/
public abstract class AbstractMemoryHttpData extends AbstractHttpData {
private ChannelBuffer channelBuffer = null;
private ChannelBuffer channelBuffer;
private int chunkPosition;
protected boolean isRenamed;
private int chunkPosition = 0;
protected boolean isRenamed = false;
public AbstractMemoryHttpData(String name, Charset charset, long size)
throws NullPointerException, IllegalArgumentException {
public AbstractMemoryHttpData(String name, Charset charset, long size) {
super(name, charset, size);
}

View File

@ -41,10 +41,10 @@ import java.util.regex.Pattern;
*/
public class CookieDecoder {
private final static Pattern PATTERN =
private static final Pattern PATTERN =
Pattern.compile("(?:\\s|[;,])*\\$*([^;=]+)(?:=(?:[\"']((?:\\\\.|[^\"])*)[\"']|([^;,]*)))?(\\s*(?:[;,]+\\s*|$))");
private final static String COMMA = ",";
private static final String COMMA = ",";
private final boolean lenient;

View File

@ -204,8 +204,10 @@ public class CookieEncoder {
}
}
if(sb.length() > 0)
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}

View File

@ -35,11 +35,11 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
*/
public static long MINSIZE = 0x4000;
private boolean useDisk = false;
private boolean useDisk;
private boolean checkSize = false;
private boolean checkSize;
private long minSize = 0L;
private long minSize;
/**
* Keep all HttpDatas until cleanAllHttpDatas() is called.
@ -91,8 +91,7 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
}
@Override
public Attribute createAttribute(HttpRequest request, String name) throws NullPointerException,
IllegalArgumentException {
public Attribute createAttribute(HttpRequest request, String name) {
if (useDisk) {
Attribute attribute = new DiskAttribute(name);
List<HttpData> fileToDelete = getList(request);
@ -111,8 +110,7 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
* @see io.netty.handler.codec.http2.HttpDataFactory#createAttribute(java.lang.String, java.lang.String)
*/
@Override
public Attribute createAttribute(HttpRequest request, String name, String value)
throws NullPointerException, IllegalArgumentException {
public Attribute createAttribute(HttpRequest request, String name, String value) {
if (useDisk) {
Attribute attribute;
try {
@ -143,7 +141,7 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
@Override
public FileUpload createFileUpload(HttpRequest request, String name, String filename,
String contentType, String contentTransferEncoding, Charset charset,
long size) throws NullPointerException, IllegalArgumentException {
long size) {
if (useDisk) {
FileUpload fileUpload = new DiskFileUpload(name, filename, contentType,
contentTransferEncoding, charset, size);

View File

@ -24,7 +24,7 @@ import io.netty.buffer.ChannelBuffers;
* Disk implementation of Attributes
*/
public class DiskAttribute extends AbstractDiskHttpData implements Attribute {
public static String baseDirectory = null;
public static String baseDirectory;
public static boolean deleteOnExitTemporaryFile = true;
@ -47,8 +47,7 @@ public class DiskAttribute extends AbstractDiskHttpData implements Attribute {
* @throws IllegalArgumentException
* @throws IOException
*/
public DiskAttribute(String name, String value)
throws NullPointerException, IllegalArgumentException, IOException {
public DiskAttribute(String name, String value) throws IOException {
super(name, HttpCodecUtil.DEFAULT_CHARSET, 0); // Attribute have no default size
setValue(value);
}

View File

@ -22,7 +22,7 @@ import java.nio.charset.Charset;
* Disk FileUpload implementation that stores file into real files
*/
public class DiskFileUpload extends AbstractDiskHttpData implements FileUpload {
public static String baseDirectory = null;
public static String baseDirectory;
public static boolean deleteOnExitTemporaryFile = true;
@ -30,15 +30,14 @@ public class DiskFileUpload extends AbstractDiskHttpData implements FileUpload {
public static String postfix = ".tmp";
private String filename = null;
private String filename;
private String contentType = null;
private String contentType;
private String contentTransferEncoding = null;
private String contentTransferEncoding;
public DiskFileUpload(String name, String filename, String contentType,
String contentTransferEncoding, Charset charset, long size)
throws NullPointerException, IllegalArgumentException {
String contentTransferEncoding, Charset charset, long size) {
super(name, charset, size);
setFilename(filename);
setContentType(contentType);

View File

@ -22,7 +22,7 @@ import io.netty.util.CharsetUtil;
/**
*/
class HttpCodecUtil {
final class HttpCodecUtil {
//space ' '
static final byte SP = 32;

View File

@ -29,8 +29,7 @@ public interface HttpDataFactory {
* @throws NullPointerException
* @throws IllegalArgumentException
*/
Attribute createAttribute(HttpRequest request, String name)
throws NullPointerException, IllegalArgumentException;
Attribute createAttribute(HttpRequest request, String name);
/**
*
@ -41,8 +40,7 @@ public interface HttpDataFactory {
* @throws NullPointerException
* @throws IllegalArgumentException
*/
Attribute createAttribute(HttpRequest request, String name, String value)
throws NullPointerException, IllegalArgumentException;
Attribute createAttribute(HttpRequest request, String name, String value);
/**
*
@ -56,7 +54,7 @@ public interface HttpDataFactory {
*/
FileUpload createFileUpload(HttpRequest request, String name, String filename,
String contentType, String contentTransferEncoding, Charset charset,
long size) throws NullPointerException, IllegalArgumentException;
long size);
/**
* Remove the given InterfaceHttpData from clean list (will not delete the file, except if the file

View File

@ -568,11 +568,9 @@ public abstract class HttpMessageDecoder extends ReplayingDecoder<HttpMessageDec
if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
}
}
else if (nextByte == HttpCodecUtil.LF) {
} else if (nextByte == HttpCodecUtil.LF) {
return sb.toString();
}
else {
} else {
if (lineLength >= maxLineLength) {
// TODO: Respond with Bad Request and discard the traffic
// or close the connection.

View File

@ -23,7 +23,8 @@ import io.netty.util.CharsetUtil;
/**
* Shared Static object between HttpMessageDecoder, HttpPostRequestDecoder and HttpPostRequestEncoder
*/
public class HttpPostBodyUtil {
final class HttpPostBodyUtil {
public static int chunkSize = 8096;
/**
* HTTP content disposition header name.

View File

@ -50,12 +50,12 @@ public class HttpPostRequestDecoder {
/**
* Does request have a body to decode
*/
private boolean bodyToDecode = false;
private boolean bodyToDecode;
/**
* Does the last chunk already received
*/
private boolean isLastChunk = false;
private boolean isLastChunk;
/**
* HttpDatas from Body
@ -71,28 +71,28 @@ public class HttpPostRequestDecoder {
/**
* The current channelBuffer
*/
private ChannelBuffer undecodedChunk = null;
private ChannelBuffer undecodedChunk;
/**
* Does this request is a Multipart request
*/
private boolean isMultipart = false;
private boolean isMultipart;
/**
* Body HttpDatas current position
*/
private int bodyListHttpDataRank = 0;
private int bodyListHttpDataRank;
/**
* If multipart, this is the boundary for the flobal multipart
*/
private String multipartDataBoundary = null;
private String multipartDataBoundary;
/**
* If multipart, there could be internal multiparts (mixed) to the global multipart.
* Only one level is allowed.
*/
private String multipartMixedBoundary = null;
private String multipartMixedBoundary;
/**
* Current status
@ -102,17 +102,17 @@ public class HttpPostRequestDecoder {
/**
* Used in Multipart
*/
private Map<String, Attribute> currentFieldAttributes = null;
private Map<String, Attribute> currentFieldAttributes;
/**
* The current FileUpload that is currently in decode process
*/
private FileUpload currentFileUpload = null;
private FileUpload currentFileUpload;
/**
* The current Attribute that is currently in decode process
*/
private Attribute currentAttribute = null;
private Attribute currentAttribute;
/**
*
@ -122,8 +122,7 @@ public class HttpPostRequestDecoder {
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException,
NullPointerException {
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE),
request, HttpCodecUtil.DEFAULT_CHARSET);
}
@ -137,8 +136,7 @@ public class HttpPostRequestDecoder {
* @throws ErrorDataDecoderException if the default charset was wrong when decoding or other errors
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request)
throws ErrorDataDecoderException, IncompatibleDataDecoderException,
NullPointerException {
throws ErrorDataDecoderException, IncompatibleDataDecoderException {
this(factory, request, HttpCodecUtil.DEFAULT_CHARSET);
}
@ -153,7 +151,7 @@ public class HttpPostRequestDecoder {
*/
public HttpPostRequestDecoder(HttpDataFactory factory, HttpRequest request,
Charset charset) throws ErrorDataDecoderException,
IncompatibleDataDecoderException, NullPointerException {
IncompatibleDataDecoderException {
if (factory == null) {
throw new NullPointerException("factory");
}

View File

@ -51,16 +51,16 @@ public class HttpPostRequestEncoder implements ChunkedInput {
/**
* Chunked false by default
*/
private boolean isChunked = false;
private boolean isChunked;
/**
* InterfaceHttpData for Body (without encoding)
*/
private List<InterfaceHttpData> bodyListDatas = null;
private List<InterfaceHttpData> bodyListDatas;
/**
* The final Multipart List of InterfaceHttpData including encoding
*/
private List<InterfaceHttpData> multipartHttpDatas = null;
private List<InterfaceHttpData> multipartHttpDatas;
/**
* Does this request is a Multipart request
@ -70,17 +70,17 @@ public class HttpPostRequestEncoder implements ChunkedInput {
/**
* If multipart, this is the boundary for the flobal multipart
*/
private String multipartDataBoundary = null;
private String multipartDataBoundary;
/**
* If multipart, there could be internal multiparts (mixed) to the global multipart.
* Only one level is allowed.
*/
private String multipartMixedBoundary = null;
private String multipartMixedBoundary;
/**
* To check if the header has been finalized
*/
private boolean headerFinalized = false;
private boolean headerFinalized;
/**
*
@ -90,7 +90,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the request is not a POST
*/
public HttpPostRequestEncoder(HttpRequest request, boolean multipart)
throws ErrorDataEncoderException, NullPointerException {
throws ErrorDataEncoderException {
this(new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE),
request, multipart, HttpCodecUtil.DEFAULT_CHARSET);
}
@ -104,7 +104,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the request is not a POST
*/
public HttpPostRequestEncoder(HttpDataFactory factory, HttpRequest request, boolean multipart)
throws ErrorDataEncoderException, NullPointerException {
throws ErrorDataEncoderException {
this(factory, request, multipart, HttpCodecUtil.DEFAULT_CHARSET);
}
@ -118,8 +118,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the request is not a POST
*/
public HttpPostRequestEncoder(HttpDataFactory factory, HttpRequest request,
boolean multipart, Charset charset) throws ErrorDataEncoderException,
NullPointerException {
boolean multipart, Charset charset) throws ErrorDataEncoderException {
if (factory == null) {
throw new NullPointerException("factory");
}
@ -157,24 +156,24 @@ public class HttpPostRequestEncoder implements ChunkedInput {
/**
* Does the last non empty chunk already encoded so that next chunk will be empty (last chunk)
*/
private boolean isLastChunk = false;
private boolean isLastChunk;
/**
* Last chunk already sent
*/
private boolean isLastChunkSent = false;
private boolean isLastChunkSent;
/**
* The current FileUpload that is currently in encode process
*/
private FileUpload currentFileUpload = null;
private FileUpload currentFileUpload;
/**
* While adding a FileUpload, is the multipart currently in Mixed Mode
*/
private boolean duringMixedMode = false;
private boolean duringMixedMode;
/**
* Global Body size
*/
private long globalBodySize = 0;
private long globalBodySize;
/**
* True if this request is a Multipart request
@ -224,7 +223,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already done
*/
public void setBodyHttpDatas(List<InterfaceHttpData> datas)
throws NullPointerException, ErrorDataEncoderException {
throws ErrorDataEncoderException {
if (datas == null) {
throw new NullPointerException("datas");
}
@ -246,7 +245,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already done
*/
public void addBodyAttribute(String name, String value)
throws NullPointerException, ErrorDataEncoderException {
throws ErrorDataEncoderException {
if (name == null) {
throw new NullPointerException("name");
}
@ -268,7 +267,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already done
*/
public void addBodyFileUpload(String name, File file, String contentType, boolean isText)
throws NullPointerException, ErrorDataEncoderException {
throws ErrorDataEncoderException {
if (name == null) {
throw new NullPointerException("name");
}
@ -307,7 +306,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already done
*/
public void addBodyFileUploads(String name, File[] file, String[] contentType, boolean[] isText)
throws NullPointerException, ErrorDataEncoderException {
throws ErrorDataEncoderException {
if (file.length != contentType.length && file.length != isText.length) {
throw new NullPointerException("Different array length");
}
@ -323,7 +322,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
* @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already done
*/
public void addBodyHttpData(InterfaceHttpData data)
throws NullPointerException, ErrorDataEncoderException {
throws ErrorDataEncoderException {
if (headerFinalized) {
throw new ErrorDataEncoderException("Cannot add value once finalized");
}
@ -554,7 +553,7 @@ public class HttpPostRequestEncoder implements ChunkedInput {
/**
* Iterator to be used when encoding will be called chunk after chunk
*/
private ListIterator<InterfaceHttpData> iterator = null;
private ListIterator<InterfaceHttpData> iterator;
/**
* Finalize the request by preparing the Header in the request and
@ -675,11 +674,11 @@ public class HttpPostRequestEncoder implements ChunkedInput {
/**
* The ChannelBuffer currently used by the encoder
*/
private ChannelBuffer currentBuffer = null;
private ChannelBuffer currentBuffer;
/**
* The current InterfaceHttpData to encode (used if more chunks are available)
*/
private InterfaceHttpData currentData = null;
private InterfaceHttpData currentData;
/**
* If not multipart, does the currentBuffer stands for the Key or for the Value
*/

View File

@ -36,8 +36,7 @@ public class MemoryAttribute extends AbstractMemoryHttpData implements Attribute
* @throws IllegalArgumentException
* @throws IOException
*/
public MemoryAttribute(String name, String value)
throws NullPointerException, IllegalArgumentException, IOException {
public MemoryAttribute(String name, String value) throws IOException {
super(name, HttpCodecUtil.DEFAULT_CHARSET, 0); // Attribute have no default size
setValue(value);
}

View File

@ -24,15 +24,14 @@ import java.nio.charset.Charset;
*/
public class MemoryFileUpload extends AbstractMemoryHttpData implements FileUpload {
private String filename = null;
private String filename;
private String contentType = null;
private String contentType;
private String contentTransferEncoding = null;
private String contentTransferEncoding;
public MemoryFileUpload(String name, String filename, String contentType,
String contentTransferEncoding, Charset charset, long size)
throws NullPointerException, IllegalArgumentException {
String contentTransferEncoding, Charset charset, long size) {
super(name, charset, size);
setFilename(filename);
setContentType(contentType);

View File

@ -26,20 +26,16 @@ import io.netty.buffer.ChannelBuffer;
* Mixed implementation using both in Memory and in File with a limit of size
*/
public class MixedAttribute implements Attribute {
private Attribute attribute = null;
private Attribute attribute;
private long limitSize = 0;
private long limitSize;
public MixedAttribute(String name,
long limitSize) throws NullPointerException,
IllegalArgumentException {
public MixedAttribute(String name, long limitSize) {
this.limitSize = limitSize;
attribute = new MemoryAttribute(name);
}
public MixedAttribute(String name, String value,
long limitSize) throws NullPointerException,
IllegalArgumentException {
public MixedAttribute(String name, String value, long limitSize) {
this.limitSize = limitSize;
if (value.length() > this.limitSize) {
try {
@ -62,8 +58,7 @@ public class MixedAttribute implements Attribute {
}
@Override
public void addContent(ChannelBuffer buffer, boolean last)
throws IOException {
public void addContent(ChannelBuffer buffer, boolean last) throws IOException {
if (attribute instanceof MemoryAttribute) {
if (attribute.length() + buffer.readableBytes() > limitSize) {
DiskAttribute diskAttribute = new DiskAttribute(attribute

View File

@ -26,16 +26,15 @@ import io.netty.buffer.ChannelBuffer;
* Mixed implementation using both in Memory and in File with a limit of size
*/
public class MixedFileUpload implements FileUpload {
private FileUpload fileUpload = null;
private FileUpload fileUpload;
private long limitSize = 0;
private long limitSize;
private long definedSize = 0;
private long definedSize;
public MixedFileUpload(String name, String filename, String contentType,
String contentTransferEncoding, Charset charset, long size,
long limitSize) throws NullPointerException,
IllegalArgumentException {
long limitSize) {
this.limitSize = limitSize;
if (size > this.limitSize) {
fileUpload = new DiskFileUpload(name, filename, contentType,

View File

@ -174,8 +174,7 @@ public class QueryStringDecoder {
int pathEndPos = uri.indexOf('?');
if (pathEndPos < 0) {
path = uri;
}
else {
} else {
return path = uri.substring(0, pathEndPos);
}
}

View File

@ -25,7 +25,7 @@ import io.netty.util.CharsetUtil;
*/
public class ContinuationWebSocketFrame extends WebSocketFrame {
private String aggregatedText = null;
private String aggregatedText;
/**
* Creates a new empty continuation frame.

View File

@ -42,7 +42,7 @@ final class UTF8Output {
12, 12, 12, 12, 12, 12, 12, 12 };
private int state = UTF8_ACCEPT;
private int codep = 0;
private int codep;
private final StringBuilder stringBuilder;
@ -60,7 +60,7 @@ final class UTF8Output {
public void write(int b) {
byte type = TYPES[b & 0xFF];
codep = (state != UTF8_ACCEPT) ? (b & 0x3f) | (codep << 6) : (0xff >> type) & (b);
codep = (state != UTF8_ACCEPT) ? (b & 0x3f) | (codep << 6) : (0xff >> type) & b;
state = STATES[state + type];

View File

@ -64,20 +64,20 @@ public class WebSocket08FrameDecoder extends ReplayingDecoder<WebSocket08FrameDe
private static final byte OPCODE_PING = 0x9;
private static final byte OPCODE_PONG = 0xA;
private UTF8Output fragmentedFramesText = null;
private int fragmentedFramesCount = 0;
private UTF8Output fragmentedFramesText;
private int fragmentedFramesCount;
private boolean frameFinalFlag;
private int frameRsv;
private int frameOpcode;
private long framePayloadLength;
private ChannelBuffer framePayload = null;
private int framePayloadBytesRead = 0;
private ChannelBuffer framePayload;
private int framePayloadBytesRead;
private ChannelBuffer maskingKey;
private boolean allowExtensions = false;
private boolean maskedPayload = false;
private boolean receivedClosingHandshake = false;
private boolean allowExtensions;
private boolean maskedPayload;
private boolean receivedClosingHandshake;
public enum State {
FRAME_START, MASKING_KEY, PAYLOAD, CORRUPT
@ -118,7 +118,7 @@ public class WebSocket08FrameDecoder extends ReplayingDecoder<WebSocket08FrameDe
byte b = buffer.readByte();
frameFinalFlag = (b & 0x80) != 0;
frameRsv = (b & 0x70) >> 4;
frameOpcode = (b & 0x0F);
frameOpcode = b & 0x0F;
if (logger.isDebugEnabled()) {
logger.debug("Decoding WebSocket Frame opCode=" + frameOpcode);
@ -127,7 +127,7 @@ public class WebSocket08FrameDecoder extends ReplayingDecoder<WebSocket08FrameDe
// MASK, PAYLOAD LEN 1
b = buffer.readByte();
boolean frameMasked = (b & 0x80) != 0;
int framePayloadLen1 = (b & 0x7F);
int framePayloadLen1 = b & 0x7F;
if (frameRsv != 0 && !this.allowExtensions) {
protocolViolation(channel, "RSV != 0 and no extension negotiated, RSV:" + frameRsv);

View File

@ -66,7 +66,7 @@ public class WebSocket08FrameEncoder extends OneToOneEncoder {
private static final byte OPCODE_PING = 0x9;
private static final byte OPCODE_PONG = 0xA;
private boolean maskPayload = false;
private boolean maskPayload;
/**
* Constructor
@ -116,7 +116,7 @@ public class WebSocket08FrameEncoder extends OneToOneEncoder {
int b0 = 0;
if (frame.isFinalFragment()) {
b0 |= (1 << 7);
b0 |= 1 << 7;
}
b0 |= (frame.getRsv() % 8) << 4;
b0 |= opcode % 128;
@ -138,13 +138,13 @@ public class WebSocket08FrameEncoder extends OneToOneEncoder {
} else if (length <= 0xFFFF) {
header = ChannelBuffers.buffer(4 + maskLength);
header.writeByte(b0);
header.writeByte(this.maskPayload ? (0xFE) : 126);
header.writeByte(this.maskPayload ? 0xFE : 126);
header.writeByte((length >>> 8) & 0xFF);
header.writeByte((length) & 0xFF);
header.writeByte(length & 0xFF);
} else {
header = ChannelBuffers.buffer(10 + maskLength);
header.writeByte(b0);
header.writeByte(this.maskPayload ? (0xFF) : 127);
header.writeByte(this.maskPayload ? 0xFF : 127);
header.writeLong(length);
}

View File

@ -36,20 +36,14 @@ public abstract class WebSocketClientHandshaker {
private WebSocketVersion version = WebSocketVersion.UNKNOWN;
private boolean openingHandshakeCompleted = false;
private boolean openingHandshakeCompleted;
private String subProtocolRequest = null;
private String subProtocolRequest;
private String subProtocolResponse = null;
private String subProtocolResponse;
protected Map<String, String> customHeaders = null;
protected Map<String, String> customHeaders;
/**
*
* @param webSocketURL
* @param version
* @param subProtocol
*/
public WebSocketClientHandshaker(URI webSocketURL, WebSocketVersion version, String subProtocol,
Map<String, String> customHeaders) {
this.webSocketURL = webSocketURL;

View File

@ -45,7 +45,7 @@ import io.netty.handler.codec.http.HttpVersion;
*/
public class WebSocketClientHandshaker00 extends WebSocketClientHandshaker {
private byte[] expectedChallengeResponseBytes = null;
private byte[] expectedChallengeResponseBytes;
/**
* Constructor specifying the destination web socket location and version to initiate

View File

@ -46,11 +46,11 @@ public class WebSocketClientHandshaker08 extends WebSocketClientHandshaker {
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private String expectedChallengeResponseString = null;
private String expectedChallengeResponseString;
private static final String protocol = null;
private boolean allowExtensions = false;
private boolean allowExtensions;
/**
* Constructor specifying the destination web socket location and version to initiate

View File

@ -46,11 +46,11 @@ public class WebSocketClientHandshaker13 extends WebSocketClientHandshaker {
public static final String MAGIC_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private String expectedChallengeResponseString = null;
private String expectedChallengeResponseString;
private static final String protocol = null;
private boolean allowExtensions = false;
private boolean allowExtensions;
/**
* Constructor specifying the destination web socket location and version to initiate

View File

@ -31,7 +31,7 @@ public abstract class WebSocketFrame {
/**
* RSV1, RSV2, RSV3 used for extensions
*/
private int rsv = 0;
private int rsv;
/**
* Contents of this frame

View File

@ -34,7 +34,7 @@ public abstract class WebSocketServerHandshaker {
private String subProtocols;
private String[] subProtocolsArray = null;
private String[] subProtocolsArray;
private WebSocketVersion version = WebSocketVersion.UNKNOWN;

View File

@ -49,7 +49,7 @@ public class WebSocketServerHandshaker08 extends WebSocketServerHandshaker {
public static final String WEBSOCKET_08_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private boolean allowExtensions = false;
private boolean allowExtensions;
/**
* Constructor specifying the destination web socket location

View File

@ -50,7 +50,7 @@ public class WebSocketServerHandshaker13 extends WebSocketServerHandshaker {
public static final String WEBSOCKET_13_ACCEPT_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
private boolean allowExtensions = false;
private boolean allowExtensions;
/**
* Constructor specifying the destination web socket location

View File

@ -32,7 +32,7 @@ public class WebSocketServerHandshakerFactory {
private final String subProtocols;
private boolean allowExtensions = false;
private boolean allowExtensions;
/**
* Constructor specifying the destination web socket location

View File

@ -32,7 +32,7 @@ import io.netty.buffer.HeapChannelBufferFactory;
* @apiviz.landmark
* @apiviz.uses io.netty.handler.codec.base64.Base64Dialect
*/
public class Base64 {
public final class Base64 {
/** Maximum line length (76) of Base64 output. */
private static final int MAX_LINE_LENGTH = 76;
@ -301,9 +301,9 @@ public class Base64 {
sbiDecode = DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // White space, Equals sign or better
if (sbiDecode >= EQUALS_SIGN_ENC) {
if (sbiDecode >= EQUALS_SIGN_ENC) { // Equals sign or better
b4[b4Posn ++] = sbiCrop;
if (b4Posn > 3) {
if (b4Posn > 3) { // Quartet built
outBuffPosn += decode4to3(
b4, 0, dest, outBuffPosn, dialect);
b4Posn = 0;
@ -312,10 +312,9 @@ public class Base64 {
if (sbiCrop == EQUALS_SIGN) {
break;
}
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
}
}
} else {
throw new IllegalArgumentException(
"bad Base64 input character at " + i + ": " +
src.getUnsignedByte(i) + " (decimal)");
@ -331,18 +330,16 @@ public class Base64 {
byte[] DECODABET = decodabet(dialect);
// Example: Dk==
if (src[srcOffset + 2] == EQUALS_SIGN) {
// Example: Dk==
int outBuff =
(DECODABET[src[srcOffset ]] & 0xFF) << 18 |
(DECODABET[src[srcOffset + 1]] & 0xFF) << 12;
dest.setByte(destOffset, (byte) (outBuff >>> 16));
return 1;
}
} else if (src[srcOffset + 3] == EQUALS_SIGN) {
// Example: DkL=
else if (src[srcOffset + 3] == EQUALS_SIGN) {
int outBuff =
(DECODABET[src[srcOffset ]] & 0xFF) << 18 |
(DECODABET[src[srcOffset + 1]] & 0xFF) << 12 |
@ -351,10 +348,8 @@ public class Base64 {
dest.setByte(destOffset , (byte) (outBuff >>> 16));
dest.setByte(destOffset + 1, (byte) (outBuff >>> 8));
return 2;
}
} else {
// Example: DkLE
else {
int outBuff;
try {
outBuff =

View File

@ -21,7 +21,7 @@ import io.netty.channel.ChannelPipeline;
/**
*/
class EmbeddedChannelFactory implements ChannelFactory {
final class EmbeddedChannelFactory implements ChannelFactory {
static final ChannelFactory INSTANCE = new EmbeddedChannelFactory();

View File

@ -21,7 +21,7 @@ import io.netty.buffer.ChannelBuffers;
/**
* A set of commonly used delimiters for {@link DelimiterBasedFrameDecoder}.
*/
public class Delimiters {
public final class Delimiters {
/**
* Returns a {@code NUL (0x00)} delimiter, which could be used for

View File

@ -145,8 +145,8 @@ import io.netty.handler.codec.serialization.ObjectDecoder;
* header from the frame. If you don't want to strip the prepended header, you
* could specify <tt>0</tt> for <tt>initialBytesToSkip</tt>.
* <pre>
* lengthFieldOffset</b> = 1 (= the length of HDR1)
* lengthFieldLength</b> = 2
* lengthFieldOffset = 1 (= the length of HDR1)
* lengthFieldLength = 2
* <b>lengthAdjustment</b> = <b>1</b> (= the length of HDR2)
* <b>initialBytesToStrip</b> = <b>3</b> (= the length of HDR1 + LEN)
*
@ -403,14 +403,12 @@ public class LengthFieldBasedFrameDecoder extends FrameDecoder {
this.tooLongFrameLength = 0;
discardingTooLongFrame = false;
if ((!failFast) ||
(failFast && firstDetectionOfTooLongFrame))
{
(failFast && firstDetectionOfTooLongFrame)) {
fail(ctx, tooLongFrameLength);
}
} else {
// Keep discarding and notify handlers if necessary.
if (failFast && firstDetectionOfTooLongFrame)
{
if (failFast && firstDetectionOfTooLongFrame) {
fail(ctx, this.tooLongFrameLength);
}
}

View File

@ -19,7 +19,7 @@ import java.lang.ref.Reference;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
public class ClassResolvers {
public final class ClassResolvers {
/**
* cache disabled
@ -86,4 +86,8 @@ public class ClassResolvers {
return ClassResolvers.class.getClassLoader();
}
private ClassResolvers() {
// Unused
}
}

View File

@ -191,6 +191,9 @@ public class ObjectDecoderInputStream extends InputStream implements
return in.readInt();
}
/**
* @deprecated Use {@link java.io.BufferedReader#readLine()} instead.
*/
@Override
@Deprecated
public final String readLine() throws IOException {

View File

@ -26,7 +26,7 @@ import java.util.Map;
* A utility class that provides various common operations and constants
* related with {@link Charset} and its relevant classes.
*/
public class CharsetUtil {
public final class CharsetUtil {
/**
* 16-bit UTF (UCS Transformation Format) whose byte order is identified by

View File

@ -19,7 +19,7 @@ package io.netty.util;
* A utility class that provides the convenient shutdown of
* {@link ExternalResourceReleasable}s.
*/
public class ExternalResourceUtil {
public final class ExternalResourceUtil {
/**
* Releases the specified {@link ExternalResourceReleasable}s.

View File

@ -20,11 +20,8 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* Utility which checks if {@value #UNSAFE} class can be found in the classpath
*
*/
public class UnsafeDetectUtil {
public final class UnsafeDetectUtil {
private static final String UNSAFE = "sun.misc.Unsafe";
private static final boolean UNSAFE_FOUND = isUnsafeFound(AtomicInteger.class.getClassLoader());

View File

@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
*/
class AtomicFieldUpdaterUtil {
final class AtomicFieldUpdaterUtil {
private static final boolean AVAILABLE;

View File

@ -65,7 +65,7 @@ public final class ConcurrentHashMap<K, V> extends AbstractMap<K, V>
/**
* The maximum capacity, used if a higher value is implicitly specified by
* either of the constructors with arguments. MUST be a power of two
* <= 1<<30 to ensure that entries are indexable using integers.
* &lt;= 1&lt;&lt;30 to ensure that entries are indexable using integers.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

View File

@ -65,7 +65,7 @@ public final class ConcurrentIdentityHashMap<K, V> extends AbstractMap<K, V>
/**
* The maximum capacity, used if a higher value is implicitly specified by
* either of the constructors with arguments. MUST be a power of two
* <= 1<<30 to ensure that entries are indexable using integers.
* &lt;= 1&lt;&lt;30 to ensure that entries are indexable using integers.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

View File

@ -72,7 +72,7 @@ public final class ConcurrentIdentityWeakKeyHashMap<K, V> extends AbstractMap<K,
/**
* The maximum capacity, used if a higher value is implicitly specified by
* either of the constructors with arguments. MUST be a power of two
* <= 1<<30 to ensure that entries are indexable using integers.
* &lt;= 1&lt;&lt;30 to ensure that entries are indexable using integers.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

View File

@ -72,7 +72,7 @@ public final class ConcurrentWeakKeyHashMap<K, V> extends AbstractMap<K, V> impl
/**
* The maximum capacity, used if a higher value is implicitly specified by
* either of the constructors with arguments. MUST be a power of two
* <= 1<<30 to ensure that entries are indexable using integers.
* &lt;= 1&lt;&lt;30 to ensure that entries are indexable using integers.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

View File

@ -22,7 +22,7 @@ import java.util.List;
* Conversion utility class to parse a property represented as a string or
* an object.
*/
public class ConversionUtil {
public final class ConversionUtil {
/**
* Converts the specified object into an integer.

View File

@ -25,7 +25,7 @@ import java.util.concurrent.TimeUnit;
* their termination. An {@link Executor} which is not an {@link ExecutorService}
* will be ignored silently.
*/
public class ExecutorUtil {
public final class ExecutorUtil {
/**
* Returns {@code true} if and only if the specified {@code executor}

View File

@ -26,7 +26,7 @@ import io.netty.util.UnsafeDetectUtil;
*/
public class QueueFactory {
public final class QueueFactory {
private static final boolean useUnsafe = UnsafeDetectUtil.isUnsafeFound(QueueFactory.class.getClassLoader());
@ -41,7 +41,7 @@ public class QueueFactory {
* @param itemClass the {@link Class} type which will be used as {@link BlockingQueue} items
* @return queue the {@link BlockingQueue} implementation
*/
public static final <T> BlockingQueue<T> createQueue(Class<T> itemClass) {
public static <T> BlockingQueue<T> createQueue(Class<T> itemClass) {
if (useUnsafe) {
return new LinkedTransferQueue<T>();
} else {
@ -56,7 +56,7 @@ public class QueueFactory {
* @param itemClass the {@link Class} type which will be used as {@link BlockingQueue} items
* @return queue the {@link BlockingQueue} implementation
*/
public static final <T> BlockingQueue<T> createQueue(Collection<? extends T> collection, Class<T> itemClass) {
public static <T> BlockingQueue<T> createQueue(Collection<? extends T> collection, Class<T> itemClass) {
if (useUnsafe) {
return new LinkedTransferQueue<T>(collection);
} else {

View File

@ -20,7 +20,7 @@ import java.util.Formatter;
/**
* String utility class.
*/
public class StringUtil {
public final class StringUtil {
private StringUtil() {
// Unused.

View File

@ -20,7 +20,7 @@ import java.util.regex.Pattern;
/**
* Accesses the system property swallowing a {@link SecurityException}.
*/
public class SystemPropertyUtil {
public final class SystemPropertyUtil {
/**
* Returns the value of the Java system property with the specified

View File

@ -48,9 +48,9 @@ import java.util.Random;
*/
final class ThreadLocalRandom extends Random {
// same constants as Random, but must be redeclared because private
private final static long multiplier = 0x5DEECE66DL;
private final static long addend = 0xBL;
private final static long mask = (1L << 48) - 1;
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
/**
* The random seed. We can't use super.seed.

View File

@ -49,6 +49,20 @@ public class DiscardClient {
firstMessageSize = 256;
}
new DiscardClient(host, port, firstMessageSize).run();
}
private final String host;
private final int port;
private final int firstMessageSize;
public DiscardClient(String host, int port, int firstMessageSize) {
this.host = host;
this.port = port;
this.firstMessageSize = firstMessageSize;
}
public void run() {
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(

View File

@ -38,7 +38,7 @@ public class DiscardClientHandler extends SimpleChannelUpstreamHandler {
private static final Logger logger = Logger.getLogger(
DiscardClientHandler.class.getName());
private long transferredBytes = 0;
private long transferredBytes;
private final byte[] content;
public DiscardClientHandler(int messageSize) {
@ -84,7 +84,7 @@ public class DiscardClientHandler extends SimpleChannelUpstreamHandler {
@Override
public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) {
transferredBytes =+e.getWrittenAmount();
transferredBytes += e.getWrittenAmount();
}
@Override

View File

@ -30,6 +30,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class DiscardServer {
public static void main(String[] args) throws Exception {
new DiscardServer().run();
}
public void run() {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(

View File

@ -34,7 +34,7 @@ public class DiscardServerHandler extends SimpleChannelUpstreamHandler {
private static final Logger logger = Logger.getLogger(
DiscardServerHandler.class.getName());
private long transferredBytes = 0;
private long transferredBytes;
public long getTransferredBytes() {
return transferredBytes;
@ -53,7 +53,7 @@ public class DiscardServerHandler extends SimpleChannelUpstreamHandler {
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
// Discard received data silently by doing nothing.
transferredBytes += (((ChannelBuffer) e.getMessage()).readableBytes());
transferredBytes += ((ChannelBuffer) e.getMessage()).readableBytes();
}
@Override

View File

@ -52,6 +52,20 @@ public class EchoClient {
firstMessageSize = 256;
}
new EchoClient(host, port, firstMessageSize).run();
}
private final String host;
private final int port;
private final int firstMessageSize;
public EchoClient(String host, int port, int firstMessageSize) {
this.host = host;
this.port = port;
this.firstMessageSize = firstMessageSize;
}
public void run() {
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(

View File

@ -30,6 +30,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class EchoServer {
public static void main(String[] args) throws Exception {
new EchoServer().run();
}
public void run() {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(

View File

@ -46,6 +46,20 @@ public class FactorialClient {
throw new IllegalArgumentException("count must be a positive integer.");
}
new FactorialClient(host, port, count).run();
}
private final String host;
private final int port;
private final int count;
public FactorialClient(String host, int port, int count) {
this.host = host;
this.port = port;
this.count = count;
}
public void run() {
// Configure the client.
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(

View File

@ -45,7 +45,7 @@ public class FactorialClientHandler extends SimpleChannelUpstreamHandler {
// Stateful properties
private int i = 1;
private int receivedMessages = 0;
private int receivedMessages;
private final int count;
final BlockingQueue<BigInteger> answer = new LinkedBlockingQueue<BigInteger>();

View File

@ -28,6 +28,11 @@ import io.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class FactorialServer {
public static void main(String[] args) throws Exception {
new FactorialServer().run();
}
public void run() {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(

View File

@ -134,8 +134,7 @@ public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler {
// Cache Validation
String ifModifiedSince = request.getHeader(HttpHeaders.Names.IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.equals(""))
{
if (ifModifiedSince != null && !ifModifiedSince.equals("")) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

View File

@ -66,14 +66,14 @@ public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
private volatile HttpRequest request;
private volatile boolean readingChunks = false;
private volatile boolean readingChunks;
private final StringBuilder responseContent = new StringBuilder();
private static final HttpDataFactory factory = new DefaultHttpDataFactory(
DefaultHttpDataFactory.MINSIZE); // Disk if size exceed MINSIZE
private HttpPostRequestDecoder decoder = null;
private HttpPostRequestDecoder decoder;
static {
DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file
// on exit (in normal

View File

@ -50,7 +50,7 @@ import io.netty.util.CharsetUtil;
public class WebSocketServerHandler extends SimpleChannelUpstreamHandler {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketServerHandler.class);
private WebSocketServerHandshaker handshaker = null;
private WebSocketServerHandshaker handshaker;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

View File

@ -36,13 +36,7 @@ import io.netty.handler.codec.http.websocketx.WebSocketVersion;
public class App {
public static void main(String[] args) throws Exception {
ConsoleHandler ch = new ConsoleHandler();
ch.setLevel(Level.FINE);
Logger.getLogger("").addHandler(ch);
Logger.getLogger("").setLevel(Level.FINE);
runClient();
System.exit(0);
new App().runClient();
}
/**
@ -50,7 +44,7 @@ public class App {
*
* @throws Exception
*/
public static void runClient() throws Exception {
public void runClient() throws Exception {
MyCallbackHandler callbackHandler = new MyCallbackHandler();
WebSocketClientFactory factory = new WebSocketClientFactory();
@ -91,7 +85,7 @@ public class App {
* Our web socket callback handler for this app
*/
public static class MyCallbackHandler implements WebSocketCallback {
public boolean connected = false;
public boolean connected;
public ArrayList<String> messagesReceived = new ArrayList<String>();
public MyCallbackHandler() {

View File

@ -53,9 +53,9 @@ public class WebSocketClientHandler extends SimpleChannelUpstreamHandler impleme
private URI url;
private final WebSocketCallback callback;
private Channel channel;
private WebSocketClientHandshaker handshaker = null;
private WebSocketClientHandshaker handshaker;
private final WebSocketVersion version;
private Map<String, String> customHeaders = null;
private Map<String, String> customHeaders;
public WebSocketClientHandler(ClientBootstrap bootstrap, URI url, WebSocketVersion version,
WebSocketCallback callback, Map<String, String> customHeaders) {

View File

@ -24,14 +24,12 @@ package io.netty.example.http.websocketx.client;
import java.io.IOException;
/**
* Copied from https://github.com/cgbystrom/netty-tools
*
* A WebSocket related exception
*
* Copied from https://github.com/cgbystrom/netty-tools
*/
public class WebSocketException extends IOException {
/**
*/
private static final long serialVersionUID = 1L;
public WebSocketException(String s) {

View File

@ -52,7 +52,7 @@ public class WebSocketServerHandler extends SimpleChannelUpstreamHandler {
private static final String WEBSOCKET_PATH = "/websocket";
private WebSocketServerHandshaker handshaker = null;
private WebSocketServerHandshaker handshaker;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

View File

@ -22,7 +22,7 @@ import io.netty.util.CharsetUtil;
/**
* Generates the demo HTML page which is served at http://localhost:8080/
*/
public class WebSocketServerIndexPage {
public final class WebSocketServerIndexPage {
private static final String NEWLINE = "\r\n";
@ -89,4 +89,8 @@ public class WebSocketServerIndexPage {
+ NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE,
CharsetUtil.US_ASCII);
}
private WebSocketServerIndexPage() {
// Unused
}
}

View File

@ -52,7 +52,7 @@ public class WebSocketSslServerHandler extends SimpleChannelUpstreamHandler {
private static final String WEBSOCKET_PATH = "/websocket";
private WebSocketServerHandshaker handshaker = null;
private WebSocketServerHandshaker handshaker;
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

View File

@ -22,7 +22,7 @@ import io.netty.util.CharsetUtil;
/**
* Generates the demo HTML page which is served at http://localhost:8080/
*/
public class WebSocketSslServerIndexPage {
public final class WebSocketSslServerIndexPage {
private static final String NEWLINE = "\r\n";
@ -89,4 +89,8 @@ public class WebSocketSslServerIndexPage {
+ NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE,
CharsetUtil.US_ASCII);
}
private WebSocketSslServerIndexPage() {
// Unused
}
}

View File

@ -28,7 +28,7 @@ import io.netty.logging.InternalLoggerFactory;
/**
* Creates a {@link SSLContext} for just server certificates.
*/
public class WebSocketSslServerSslContext {
public final class WebSocketSslServerSslContext {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketSslServerSslContext.class);
private static final String PROTOCOL = "TLS";

View File

@ -18,19 +18,16 @@
* <p>This package contains an example web socket web server with server SSL.
* <p>To run this example, follow the steps below:
* <dl>
* <dt>Step 1. Generate Your Key</dt>
* <dt>Step 1. Generate Your Key
* <dd>
* <code>keytool -genkey -keystore mySrvKeystore -keyalg RSA</code>.
* Make sure that you set the key password to be the same the key file password.
* </dd>
* <dt>Step 2. Specify your key store file and password as system properties</dt>
* <dt>Step 2. Specify your key store file and password as system properties
* <dd>
* <code>-Dkeystore.file.path=&lt;path to mySrvKeystore&gt; -Dkeystore.file.password=&lt;password&gt;</code>
* </dd>
* <dt>Step 3. Run WebSocketSslServer as a Java application</dt>
* <dt>Step 3. Run WebSocketSslServer as a Java application
* <dd>
* Once started, you can test the web server against your browser by navigating to https://localhost:8081/
* </dd>
* </dl>
* <p>To find out more about setting up key stores, refer to this
* <a href="http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html">giude</a>.

View File

@ -15,8 +15,18 @@
*/
package io.netty.example.iostream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.netty.bootstrap.ClientBootstrap;
import io.netty.channel.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPipelineFactory;
import io.netty.channel.DefaultChannelPipeline;
import io.netty.channel.MessageEvent;
import io.netty.channel.SimpleChannelHandler;
import io.netty.channel.iostream.IOStreamAddress;
import io.netty.channel.iostream.IOStreamChannelFactory;
import io.netty.handler.codec.frame.DelimiterBasedFrameDecoder;
@ -24,9 +34,6 @@ import io.netty.handler.codec.frame.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* An example demonstrating the use of the {@link io.netty.channel.iostream.IOStreamChannel}.
*/

View File

@ -42,6 +42,20 @@ public class HexDumpProxy {
String remoteHost = args[1];
int remotePort = Integer.parseInt(args[2]);
run(localPort, remoteHost, remotePort);
}
private final int localPort;
private final String remoteHost;
private final int remotePort;
public HexDumpProxy(int localPort, String remoteHost, int remotePort) {
this.localPort = localPort;
this.remoteHost = remoteHost;
this.remotePort = remotePort;
}
public void run() {
System.err.println(
"Proxying *:" + localPort + " to " +
remoteHost + ':' + remotePort + " ...");

View File

@ -15,14 +15,18 @@
*/
package io.netty.example.sctp;
import io.netty.buffer.ChannelBuffers;
import io.netty.channel.*;
import io.netty.channel.sctp.SctpPayload;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import io.netty.buffer.ChannelBuffers;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelStateEvent;
import io.netty.channel.ExceptionEvent;
import io.netty.channel.MessageEvent;
import io.netty.channel.SimpleChannelUpstreamHandler;
import io.netty.channel.sctp.SctpPayload;
/**
* Handler implementation for the echo client. It initiates the message
* and upon receiving echo back to the server

View File

@ -30,7 +30,7 @@ import java.io.InputStream;
* -keystore cert.jks
* </pre>
*/
public class SecureChatKeyStore {
public final class SecureChatKeyStore {
private static final short[] DATA = {
0xfe, 0xed, 0xfe, 0xed, 0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01,

View File

@ -49,7 +49,7 @@ import io.netty.handler.ssl.SslHandler;
* to validate the client certificate.</li>
* </ul>
*/
public class SecureChatSslContextFactory {
public final class SecureChatSslContextFactory {
private static final String PROTOCOL = "TLS";
private static final SSLContext SERVER_CONTEXT;
@ -99,4 +99,8 @@ public class SecureChatSslContextFactory {
public static SSLContext getClientContext() {
return CLIENT_CONTEXT;
}
private SecureChatSslContextFactory() {
// Unused
}
}

View File

@ -84,8 +84,7 @@ public class UptimeClientHandler extends SimpleChannelUpstreamHandler {
if (cause instanceof ReadTimeoutException) {
// The connection was OK but there was no traffic for last period.
println("Disconnecting due to no inbound traffic");
}
else {
} else {
cause.printStackTrace();
}
ctx.getChannel().close();

View File

@ -43,9 +43,15 @@ public class ChainedExecutor implements Executor, ExternalResourceReleasable{
* @param next the {@link Executor} to use if the {@link ChannelEventRunnableFilter} does not match
*/
public ChainedExecutor(ChannelEventRunnableFilter filter, Executor cur, Executor next) {
if (cur == null) throw new NullPointerException("cur");
if (next == null) throw new NullPointerException("next");
if (filter == null) throw new NullPointerException("filter");
if (cur == null) {
throw new NullPointerException("cur");
}
if (next == null) {
throw new NullPointerException("next");
}
if (filter == null) {
throw new NullPointerException("filter");
}
this.cur = cur;
this.next = next;

View File

@ -290,7 +290,7 @@ public class OrderedMemoryAwareThreadPoolExecutor extends
tasks.add(command);
if (isRunning.get() == false) {
if (!isRunning.get()) {
doUnorderedExecute(this);
}
}

View File

@ -22,8 +22,8 @@ import io.netty.handler.execution.ChannelEventRunnable;
public interface ChannelEventRunnableFilter {
/**
* Return <code>true<code> if the {@link ChannelEventRunnable} should get handled by the {@link Executor}
* Return <code>true</code> if the {@link ChannelEventRunnable} should get handled by the {@link Executor}
*
*/
public boolean filter(ChannelEventRunnable event);
boolean filter(ChannelEventRunnable event);
}

View File

@ -23,42 +23,30 @@ import java.util.StringTokenizer;
/**
*/
public abstract class CIDR implements Comparable<CIDR>
{
/**
* The base address of the CIDR notation
*/
public abstract class CIDR implements Comparable<CIDR> {
/** The base address of the CIDR notation */
protected InetAddress baseAddress;
/**
* The mask used in the CIDR notation
*/
/** The mask used in the CIDR notation */
protected int cidrMask;
/**
* Create CIDR using the CIDR Notation
* @param baseAddress
* @param cidrMask
*
* @return the generated CIDR
* @throws UnknownHostException
*/
public static CIDR newCIDR(InetAddress baseAddress, int cidrMask) throws UnknownHostException
{
if (cidrMask < 0)
{
public static CIDR newCIDR(InetAddress baseAddress, int cidrMask) throws UnknownHostException {
if (cidrMask < 0) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
if (baseAddress instanceof Inet4Address)
{
if (cidrMask > 32)
{
if (baseAddress instanceof Inet4Address) {
if (cidrMask > 32) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
return new CIDR4((Inet4Address) baseAddress, cidrMask);
}
// IPv6.
if (cidrMask > 128)
{
if (cidrMask > 128) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
return new CIDR6((Inet6Address) baseAddress, cidrMask);
@ -66,30 +54,23 @@ public abstract class CIDR implements Comparable<CIDR>
/**
* Create CIDR using the normal Notation
* @param baseAddress
* @param scidrMask
*
* @return the generated CIDR
* @throws UnknownHostException
*/
public static CIDR newCIDR(InetAddress baseAddress, String scidrMask) throws UnknownHostException
{
public static CIDR newCIDR(InetAddress baseAddress, String scidrMask) throws UnknownHostException {
int cidrMask = getNetMask(scidrMask);
if (cidrMask < 0)
{
if (cidrMask < 0) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
if (baseAddress instanceof Inet4Address)
{
if (cidrMask > 32)
{
if (baseAddress instanceof Inet4Address) {
if (cidrMask > 32) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
return new CIDR4((Inet4Address) baseAddress, cidrMask);
}
cidrMask += 96;
// IPv6.
if (cidrMask > 128)
{
if (cidrMask > 128) {
throw new UnknownHostException("Invalid mask length used: " + cidrMask);
}
return new CIDR6((Inet6Address) baseAddress, cidrMask);
@ -101,56 +82,45 @@ public abstract class CIDR implements Comparable<CIDR>
* CIDR subnet = newCIDR ("10.10.10.0/24"); or
* CIDR subnet = newCIDR ("1fff:0:0a88:85a3:0:0:ac1f:8001/24"); or
* CIDR subnet = newCIDR ("10.10.10.0/255.255.255.0");
* @param cidr
*
* @return the generated CIDR
* @throws UnknownHostException
*/
public static CIDR newCIDR(String cidr) throws UnknownHostException
{
public static CIDR newCIDR(String cidr) throws UnknownHostException {
int p = cidr.indexOf("/");
if (p < 0)
{
if (p < 0) {
throw new UnknownHostException("Invalid CIDR notation used: " + cidr);
}
String addrString = cidr.substring(0, p);
String maskString = cidr.substring(p + 1);
InetAddress addr = addressStringToInet(addrString);
int mask = 0;
if (maskString.indexOf(".") < 0)
{
if (maskString.indexOf(".") < 0) {
mask = parseInt(maskString, -1);
}
else
{
} else {
mask = getNetMask(maskString);
if (addr instanceof Inet6Address)
{
if (addr instanceof Inet6Address) {
mask += 96;
}
}
if (mask < 0)
{
if (mask < 0) {
throw new UnknownHostException("Invalid mask length used: " + maskString);
}
return newCIDR(addr, mask);
}
/** @return the baseAddress of the CIDR block. */
public InetAddress getBaseAddress()
{
public InetAddress getBaseAddress() {
return baseAddress;
}
/** @return the Mask length. */
public int getMask()
{
public int getMask() {
return cidrMask;
}
/** @return the textual CIDR notation. */
@Override
public String toString()
{
public String toString() {
return baseAddress.getHostAddress() + "/" + cidrMask;
}
@ -160,76 +130,71 @@ public abstract class CIDR implements Comparable<CIDR>
/**
* Compares the given InetAddress against the CIDR and returns true if
* the ip is in the subnet-ip-range and false if not.
* @param inetAddress
*
* @return returns true if the given IP address is inside the currently
* set network.
*/
public abstract boolean contains(InetAddress inetAddress);
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object arg0) {
if (!(arg0 instanceof CIDR)) {
return false;
}
return (this.compareTo((CIDR) arg0) == 0);
return this.compareTo((CIDR) arg0) == 0;
}
/** Convert an IPv4 or IPv6 textual representation into an
@Override
public int hashCode() {
return baseAddress.hashCode();
}
/**
* Convert an IPv4 or IPv6 textual representation into an
* InetAddress.
* @param addr
*
* @return the created InetAddress
* @throws UnknownHostException
*/
private static InetAddress addressStringToInet(String addr) throws UnknownHostException
{
private static InetAddress addressStringToInet(String addr) throws UnknownHostException {
return InetAddress.getByName(addr);
}
/**
* Get the Subnet's Netmask in Decimal format.<BR>
* i.e.: getNetMask("255.255.255.0") returns the integer CIDR mask
*
* @param netMask a network mask
* @return the integer CIDR mask
* */
private static int getNetMask(String netMask)
{
*/
private static int getNetMask(String netMask) {
StringTokenizer nm = new StringTokenizer(netMask, ".");
int i = 0;
int[] netmask = new int[4];
while (nm.hasMoreTokens())
{
while (nm.hasMoreTokens()) {
netmask[i] = Integer.parseInt(nm.nextToken());
i++;
}
int mask1 = 0;
for (i = 0; i < 4; i++)
{
for (i = 0; i < 4; i++) {
mask1 += Integer.bitCount(netmask[i]);
}
return mask1;
}
/** @param intstr a string containing an integer.
/**
* @param intstr a string containing an integer.
* @param def the default if the string does not contain a valid
* integer.
* @return the inetAddress from the integer
*/
private static int parseInt(String intstr, int def)
{
private static int parseInt(String intstr, int def) {
Integer res;
if (intstr == null)
{
if (intstr == null) {
return def;
}
try
{
try {
res = Integer.decode(intstr);
}
catch (Exception e)
{
} catch (Exception e) {
res = new Integer(def);
}
return res.intValue();
@ -237,22 +202,18 @@ public abstract class CIDR implements Comparable<CIDR>
/**
* Compute a byte representation of IpV4 from a IpV6
* @param address
*
* @return the byte representation
* @throws IllegalArgumentException if the IpV6 cannot be mapped to IpV4
*/
public static byte[] getIpV4FromIpV6(Inet6Address address) throws IllegalArgumentException
{
public static byte[] getIpV4FromIpV6(Inet6Address address) {
byte[] baddr = address.getAddress();
for (int i = 0; i < 9; i++)
{
if (baddr[i] != 0)
{
for (int i = 0; i < 9; i++) {
if (baddr[i] != 0) {
throw new IllegalArgumentException("This IPv6 address cannot be used in IPv4 context");
}
}
if (baddr[10] != 0 && baddr[10] != 0xFF || baddr[11] != 0 && baddr[11] != 0xFF)
{
if (baddr[10] != 0 && baddr[10] != 0xFF || baddr[11] != 0 && baddr[11] != 0xFF) {
throw new IllegalArgumentException("This IPv6 address cannot be used in IPv4 context");
}
return new byte[]
@ -261,12 +222,11 @@ public abstract class CIDR implements Comparable<CIDR>
/**
* Compute a byte representation of IpV6 from a IpV4
* @param address
*
* @return the byte representation
* @throws IllegalArgumentException if the IpV6 cannot be mapped to IpV4
*/
public static byte[] getIpV6FromIpV4(Inet4Address address) throws IllegalArgumentException
{
public static byte[] getIpV6FromIpV4(Inet4Address address) {
byte[] baddr = address.getAddress();
return new byte[]
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, baddr[0], baddr[1], baddr[2], baddr[3]};

View File

@ -22,93 +22,66 @@ import java.net.UnknownHostException;
/**
*/
public class CIDR4 extends CIDR
{
/**
* The integer for the base address
*/
public class CIDR4 extends CIDR {
/** The integer for the base address */
private int addressInt;
/**
* The integer for the end address
*/
/** The integer for the end address */
private final int addressEndInt;
/**
* @param newaddr
* @param mask
*/
protected CIDR4(Inet4Address newaddr, int mask)
{
protected CIDR4(Inet4Address newaddr, int mask) {
cidrMask = mask;
addressInt = ipv4AddressToInt(newaddr);
int newmask = ipv4PrefixLengthToMask(mask);
addressInt &= newmask;
try
{
try {
baseAddress = intToIPv4Address(addressInt);
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
// this should never happen
}
addressEndInt = addressInt + ipv4PrefixLengthToLength(cidrMask) - 1;
}
@Override
public InetAddress getEndAddress()
{
try
{
public InetAddress getEndAddress() {
try {
return intToIPv4Address(addressEndInt);
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
// this should never happen
return null;
}
}
@Override
public int compareTo(CIDR arg)
{
if (arg instanceof CIDR6)
{
public int compareTo(CIDR arg) {
if (arg instanceof CIDR6) {
byte[] address = getIpV4FromIpV6((Inet6Address) arg.baseAddress);
int net = ipv4AddressToInt(address);
if (net == addressInt && arg.cidrMask == cidrMask)
{
if (net == addressInt && arg.cidrMask == cidrMask) {
return 0;
}
if (net < addressInt)
{
if (net < addressInt) {
return 1;
}
else if (net > addressInt)
{
} else if (net > addressInt) {
return -1;
}
else if (arg.cidrMask < cidrMask)
{
} else if (arg.cidrMask < cidrMask) {
return -1;
}
return 1;
}
CIDR4 o = (CIDR4) arg;
if (o.addressInt == addressInt && o.cidrMask == cidrMask)
{
if (o.addressInt == addressInt && o.cidrMask == cidrMask) {
return 0;
}
if (o.addressInt < addressInt)
{
if (o.addressInt < addressInt) {
return 1;
}
else if (o.addressInt > addressInt)
{
} else if (o.addressInt > addressInt) {
return -1;
}
else if (o.cidrMask < cidrMask)
{
} else if (o.cidrMask < cidrMask) {
// greater Mask means less IpAddresses so -1
return -1;
}
@ -119,34 +92,33 @@ public class CIDR4 extends CIDR
* @see io.netty.handler.ipfilter.CIDR#contains(java.net.InetAddress)
*/
@Override
public boolean contains(InetAddress inetAddress)
{
public boolean contains(InetAddress inetAddress) {
int search = ipv4AddressToInt(inetAddress);
return search >= addressInt && search <= addressEndInt;
}
/** Given an IPv4 baseAddress length, return the block length. I.e., a
* baseAddress length of 24 will return 256. */
private static int ipv4PrefixLengthToLength(int prefix_length)
{
/**
* Given an IPv4 baseAddress length, return the block length. I.e., a
* baseAddress length of 24 will return 256.
*/
private static int ipv4PrefixLengthToLength(int prefix_length) {
return 1 << 32 - prefix_length;
}
/** Given a baseAddress length, return a netmask. I.e, a baseAddress length
* of 24 will return 0xFFFFFF00. */
private static int ipv4PrefixLengthToMask(int prefix_length)
{
/**
* Given a baseAddress length, return a netmask. I.e, a baseAddress length
* of 24 will return 0xFFFFFF00.
*/
private static int ipv4PrefixLengthToMask(int prefix_length) {
return ~((1 << 32 - prefix_length) - 1);
}
/** Convert an integer into an (IPv4) InetAddress.
* @param addr
/**
* Convert an integer into an (IPv4) InetAddress.
*
* @return the created InetAddress
* @throws UnknownHostException
* @throws UnknownHostException
*/
private static InetAddress intToIPv4Address(int addr) throws UnknownHostException
{
private static InetAddress intToIPv4Address(int addr) throws UnknownHostException {
byte[] a = new byte[4];
a[0] = (byte) (addr >> 24 & 0xFF);
a[1] = (byte) (addr >> 16 & 0xFF);
@ -155,39 +127,33 @@ public class CIDR4 extends CIDR
return InetAddress.getByAddress(a);
}
/** Given an IPv4 address, convert it into an integer.
* @param addr
* @return the integer representation of the InetAddress
/**
* Given an IPv4 address, convert it into an integer.
*
* @return the integer representation of the InetAddress
* @throws IllegalArgumentException if the address is really an
* IPv6 address.
*/
private static int ipv4AddressToInt(InetAddress addr)
{
private static int ipv4AddressToInt(InetAddress addr) {
byte[] address = null;
if (addr instanceof Inet6Address)
{
if (addr instanceof Inet6Address) {
address = getIpV4FromIpV6((Inet6Address) addr);
}
else
{
} else {
address = addr.getAddress();
}
return ipv4AddressToInt(address);
}
/** Given an IPv4 address as array of bytes, convert it into an integer.
* @param address
* @return the integer representation of the InetAddress
/**
* Given an IPv4 address as array of bytes, convert it into an integer.
*
* @return the integer representation of the InetAddress
* @throws IllegalArgumentException if the address is really an
* IPv6 address.
*/
private static int ipv4AddressToInt(byte[] address)
{
private static int ipv4AddressToInt(byte[] address) {
int net = 0;
for (byte addres : address)
{
for (byte addres : address) {
net <<= 8;
net |= addres & 0xFF;
}

View File

@ -26,71 +26,52 @@ import io.netty.logging.InternalLoggerFactory;
/**
*/
public class CIDR6 extends CIDR
{
public class CIDR6 extends CIDR {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(CIDR6.class);
/**
* The big integer for the base address
*/
/** The big integer for the base address */
private BigInteger addressBigInt;
/**
* The big integer for the end address
*/
/** The big integer for the end address */
private final BigInteger addressEndBigInt;
/**
* @param newaddress
* @param newmask
*/
protected CIDR6(Inet6Address newaddress, int newmask)
{
protected CIDR6(Inet6Address newaddress, int newmask) {
cidrMask = newmask;
addressBigInt = ipv6AddressToBigInteger(newaddress);
BigInteger mask = ipv6CidrMaskToMask(newmask);
try
{
try {
addressBigInt = addressBigInt.and(mask);
baseAddress = bigIntToIPv6Address(addressBigInt);
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
// this should never happen.
}
addressEndBigInt = addressBigInt.add(ipv6CidrMaskToBaseAddress(cidrMask)).subtract(BigInteger.ONE);
}
@Override
public InetAddress getEndAddress()
{
try
{
public InetAddress getEndAddress() {
try {
return bigIntToIPv6Address(addressEndBigInt);
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
logger.error("invalid ip address calculated as an end address");
return null;
}
}
@Override
public int compareTo(CIDR arg)
{
if (arg instanceof CIDR4)
{
public int compareTo(CIDR arg) {
if (arg instanceof CIDR4) {
BigInteger net = ipv6AddressToBigInteger(arg.baseAddress);
int res = net.compareTo(addressBigInt);
if (res == 0)
{
if (arg.cidrMask == cidrMask)
{
if (res == 0) {
if (arg.cidrMask == cidrMask) {
return 0;
}
else if (arg.cidrMask < cidrMask)
{
} else if (arg.cidrMask < cidrMask) {
return -1;
}
return 1;
@ -98,15 +79,12 @@ public class CIDR6 extends CIDR
return res;
}
CIDR6 o = (CIDR6) arg;
if (o.addressBigInt.equals(addressBigInt) && o.cidrMask == cidrMask)
{
if (o.addressBigInt.equals(addressBigInt) && o.cidrMask == cidrMask) {
return 0;
}
int res = o.addressBigInt.compareTo(addressBigInt);
if (res == 0)
{
if (o.cidrMask < cidrMask)
{
if (res == 0) {
if (o.cidrMask < cidrMask) {
// greater Mask means less IpAddresses so -1
return -1;
}
@ -119,79 +97,66 @@ public class CIDR6 extends CIDR
* @see io.netty.handler.ipfilter.CIDR#contains(java.net.InetAddress)
*/
@Override
public boolean contains(InetAddress inetAddress)
{
public boolean contains(InetAddress inetAddress) {
BigInteger search = ipv6AddressToBigInteger(inetAddress);
return search.compareTo(addressBigInt) >= 0 && search.compareTo(addressEndBigInt) <= 0;
}
/** Given an IPv6 baseAddress length, return the block length. I.e., a
* baseAddress length of 96 will return 2**32. */
private static BigInteger ipv6CidrMaskToBaseAddress(int cidrMask)
{
/**
* Given an IPv6 baseAddress length, return the block length. I.e., a
* baseAddress length of 96 will return 2**32.
*/
private static BigInteger ipv6CidrMaskToBaseAddress(int cidrMask) {
return BigInteger.ONE.shiftLeft(128 - cidrMask);
}
private static BigInteger ipv6CidrMaskToMask(int cidrMask)
{
private static BigInteger ipv6CidrMaskToMask(int cidrMask) {
return BigInteger.ONE.shiftLeft(128 - cidrMask).subtract(BigInteger.ONE).not();
}
/** Given an IPv6 address, convert it into a BigInteger.
* @param addr
* @return the integer representation of the InetAddress
/**
* Given an IPv6 address, convert it into a BigInteger.
*
* @return the integer representation of the InetAddress
* @throws IllegalArgumentException if the address is not an IPv6
* address.
*/
private static BigInteger ipv6AddressToBigInteger(InetAddress addr)
{
private static BigInteger ipv6AddressToBigInteger(InetAddress addr) {
byte[] ipv6;
if (addr instanceof Inet4Address)
{
if (addr instanceof Inet4Address) {
ipv6 = getIpV6FromIpV4((Inet4Address) addr);
}
else
{
} else {
ipv6 = addr.getAddress();
}
if (ipv6[0] == -1)
{
if (ipv6[0] == -1) {
return new BigInteger(1, ipv6);
}
return new BigInteger(ipv6);
}
/** Convert a big integer into an IPv6 address.
* @param addr
* @return the inetAddress from the integer
/**
* Convert a big integer into an IPv6 address.
*
* @return the inetAddress from the integer
* @throws UnknownHostException if the big integer is too large,
* and thus an invalid IPv6 address.
*/
private static InetAddress bigIntToIPv6Address(BigInteger addr) throws UnknownHostException
{
private static InetAddress bigIntToIPv6Address(BigInteger addr) throws UnknownHostException {
byte[] a = new byte[16];
byte[] b = addr.toByteArray();
if (b.length > 16 && !(b.length == 17 && b[0] == 0))
{
if (b.length > 16 && !(b.length == 17 && b[0] == 0)) {
throw new UnknownHostException("invalid IPv6 address (too big)");
}
if (b.length == 16)
{
if (b.length == 16) {
return InetAddress.getByAddress(b);
}
// handle the case where the IPv6 address starts with "FF".
if (b.length == 17)
{
if (b.length == 17) {
System.arraycopy(b, 1, a, 0, 16);
}
else
{
} else {
// copy the address into a 16 byte array, zero-filled.
int p = 16 - b.length;
for (int i = 0; i < b.length; i++)
{
for (int i = 0; i < b.length; i++) {
a[p + i] = b[i];
}
}

View File

@ -25,11 +25,8 @@ import io.netty.channel.ChannelHandlerContext;
* The listener interface for receiving ipFilter events.
*
* @see IpFilteringHandler
*
*/
public interface IpFilterListener
{
public interface IpFilterListener {
/**
* Called when the channel has the CONNECTED status and the channel was allowed by a previous call to accept().
@ -37,8 +34,7 @@ public interface IpFilterListener
* or whatever you need. This method returns a ChannelFuture on which the implementation
* can wait uninterruptibly before continuing.<br>
* For instance, If a message is sent back, the corresponding ChannelFuture has to be returned.
* @param ctx
* @param e
*
* @param inetSocketAddress the remote {@link InetSocketAddress} from client
* @return the associated ChannelFuture to be waited for before closing the channel. Null is allowed.
*/
@ -50,8 +46,7 @@ public interface IpFilterListener
* or whatever you need. This method returns a ChannelFuture on which the implementation
* will wait uninterruptibly before closing the channel.<br>
* For instance, If a message is sent back, the corresponding ChannelFuture has to be returned.
* @param ctx
* @param e
*
* @param inetSocketAddress the remote {@link InetSocketAddress} from client
* @return the associated ChannelFuture to be waited for before closing the channel. Null is allowed.
*/
@ -63,8 +58,7 @@ public interface IpFilterListener
* If one wants to not block events, just overridden this method by returning always true.<br><br>
* <b>Note that OPENED and BOUND events are still passed to the next entry in the pipeline since
* those events come out before the CONNECTED event and so the possibility to filter the connection.</b>
* @param ctx
* @param e
*
* @return True if the event should continue, False if the event should not continue
* since this channel was blocked by this filter
*/

View File

@ -15,20 +15,11 @@
*/
package io.netty.handler.ipfilter;
/**
* This Interface defines an Ip Filter Rule.
*/
public interface IpFilterRule extends IpSet
{
/**
*
* @return True if this Rule is an ALLOW rule
*/
/** This Interface defines an Ip Filter Rule. */
public interface IpFilterRule extends IpSet {
/** @return True if this Rule is an ALLOW rule */
boolean isAllowRule();
/**
*
* @return True if this Rule is a DENY rule
*/
/** @return True if this Rule is a DENY rule */
boolean isDenyRule();
}

View File

@ -49,27 +49,19 @@ import io.netty.channel.ChannelHandlerContext;
* if possible.</b><br><br><br>
* <b>This handler should be created only once and reused on every pipeline since it handles
* a global status of what is allowed or blocked.</b><br><br>
*
* <p/>
* Note that {@link IpSubnetFilterRule} which supports IPV4 and IPV6 should be used with as much as
* possible no mixed IP protocol. Both IPV4 and IPV6 are supported but a mix (IpFilter in IPV6 notation
* and the address from the channel in IPV4, or the reverse) can lead to wrong result.
*/
@Sharable
public class IpFilterRuleHandler extends IpFilteringHandlerImpl
{
/**
* List of {@link IpFilterRule}
*/
public class IpFilterRuleHandler extends IpFilteringHandlerImpl {
/** List of {@link IpFilterRule} */
private final CopyOnWriteArrayList<IpFilterRule> ipFilterRuleList = new CopyOnWriteArrayList<IpFilterRule>();
/**
* Constructor from a new list of IpFilterRule
* @param newList
*/
public IpFilterRuleHandler(List<IpFilterRule> newList)
{
if (newList != null)
{
/** Constructor from a new list of IpFilterRule */
public IpFilterRuleHandler(List<IpFilterRule> newList) {
if (newList != null) {
ipFilterRuleList.addAll(newList);
}
}
@ -78,33 +70,22 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
* Empty constructor (no IpFilterRule in the List at construction). In such a situation,
* empty list implies allow all.
*/
public IpFilterRuleHandler()
{
public IpFilterRuleHandler() {
}
// Below are methods directly inspired from CopyOnWriteArrayList methods
/**
* Add an ipFilterRule in the list at the end
* @param ipFilterRule
*/
public void add(IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
/** Add an ipFilterRule in the list at the end */
public void add(IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
ipFilterRuleList.add(ipFilterRule);
}
/**
* Add an ipFilterRule in the list at the specified position (shifting to the right other elements)
* @param index
* @param ipFilterRule
*/
public void add(int index, IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
/** Add an ipFilterRule in the list at the specified position (shifting to the right other elements) */
public void add(int index, IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
ipFilterRuleList.add(index, ipFilterRule);
@ -113,26 +94,17 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Appends all of the elements in the specified collection to the end of this list,
* in the order that they are returned by the specified collection's iterator.
* @param c
*/
public void addAll(Collection<IpFilterRule> c)
{
if (c == null)
{
public void addAll(Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
ipFilterRuleList.addAll(c);
}
/**
* Inserts all of the elements in the specified collection into this list, starting at the specified position.
* @param index
* @param c
*/
public void addAll(int index, Collection<IpFilterRule> c)
{
if (c == null)
{
/** Inserts all of the elements in the specified collection into this list, starting at the specified position. */
public void addAll(int index, Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
ipFilterRuleList.addAll(index, c);
@ -140,13 +112,11 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Append the element if not present.
* @param c
*
* @return the number of elements added
*/
public int addAllAbsent(Collection<IpFilterRule> c)
{
if (c == null)
{
public int addAllAbsent(Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
return ipFilterRuleList.addAllAbsent(c);
@ -154,35 +124,28 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Append the element if not present.
* @param ipFilterRule
*
* @return true if the element was added
*/
public boolean addIfAbsent(IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
public boolean addIfAbsent(IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
return ipFilterRuleList.addIfAbsent(ipFilterRule);
}
/**
* Clear the list
*/
public void clear()
{
/** Clear the list */
public void clear() {
ipFilterRuleList.clear();
}
/**
* Returns true if this list contains the specified element
* @param ipFilterRule
*
* @return true if this list contains the specified element
*/
public boolean contains(IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
public boolean contains(IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
return ipFilterRuleList.contains(ipFilterRule);
@ -190,13 +153,11 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Returns true if this list contains all of the elements of the specified collection
* @param c
*
* @return true if this list contains all of the elements of the specified collection
*/
public boolean containsAll(Collection<IpFilterRule> c)
{
if (c == null)
{
public boolean containsAll(Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
return ipFilterRuleList.containsAll(c);
@ -204,31 +165,25 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Returns the element at the specified position in this list
* @param index
*
* @return the element at the specified position in this list
*/
public IpFilterRule get(int index)
{
public IpFilterRule get(int index) {
return ipFilterRuleList.get(index);
}
/**
* Returns true if this list contains no elements
*
* @return true if this list contains no elements
*/
public boolean isEmpty()
{
public boolean isEmpty() {
return ipFilterRuleList.isEmpty();
}
/**
* Remove the ipFilterRule from the list
* @param ipFilterRule
*/
public void remove(IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
/** Remove the ipFilterRule from the list */
public void remove(IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
ipFilterRuleList.remove(ipFilterRule);
@ -236,35 +191,24 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Removes the element at the specified position in this list
* @param index
*
* @return the element previously at the specified position
*/
public IpFilterRule remove(int index)
{
public IpFilterRule remove(int index) {
return ipFilterRuleList.remove(index);
}
/**
* Removes from this list all of its elements that are contained in the specified collection
* @param c
*/
public void removeAll(Collection<IpFilterRule> c)
{
if (c == null)
{
/** Removes from this list all of its elements that are contained in the specified collection */
public void removeAll(Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
ipFilterRuleList.removeAll(c);
}
/**
* Retains only the elements in this list that are contained in the specified collection
* @param c
*/
public void retainAll(Collection<IpFilterRule> c)
{
if (c == null)
{
/** Retains only the elements in this list that are contained in the specified collection */
public void retainAll(Collection<IpFilterRule> c) {
if (c == null) {
throw new NullPointerException("Collection can not be null");
}
ipFilterRuleList.retainAll(c);
@ -272,14 +216,11 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Replaces the element at the specified position in this list with the specified element
* @param index
* @param ipFilterRule
*
* @return the element previously at the specified position
*/
public IpFilterRule set(int index, IpFilterRule ipFilterRule)
{
if (ipFilterRule == null)
{
public IpFilterRule set(int index, IpFilterRule ipFilterRule) {
if (ipFilterRule == null) {
throw new NullPointerException("IpFilterRule can not be null");
}
return ipFilterRuleList.set(index, ipFilterRule);
@ -287,10 +228,10 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list.
*/
public int size()
{
public int size() {
return ipFilterRuleList.size();
}
@ -299,21 +240,17 @@ public class IpFilterRuleHandler extends IpFilteringHandlerImpl
*/
@Override
protected boolean accept(ChannelHandlerContext ctx, ChannelEvent e, InetSocketAddress inetSocketAddress)
throws Exception
{
if (ipFilterRuleList.isEmpty())
{
throws Exception {
if (ipFilterRuleList.isEmpty()) {
// No limitation neither in deny or allow, so accept
return true;
}
InetAddress inetAddress = inetSocketAddress.getAddress();
Iterator<IpFilterRule> iterator = ipFilterRuleList.iterator();
IpFilterRule ipFilterRule = null;
while (iterator.hasNext())
{
while (iterator.hasNext()) {
ipFilterRule = iterator.next();
if (ipFilterRule.contains(inetAddress))
{
if (ipFilterRule.contains(inetAddress)) {
// Match founds, is it a ALLOW or DENY rule
return ipFilterRule.isAllowRule();
}

View File

@ -42,11 +42,8 @@ import io.netty.logging.InternalLoggerFactory;
* <br>
* new IPFilterRuleHandler().addAll(new IpFilterRuleList("+n:localhost, -n:*"));
* <br>
*
*/
public class IpFilterRuleList extends ArrayList<IpFilterRule>
{
public class IpFilterRuleList extends ArrayList<IpFilterRule> {
private static final long serialVersionUID = -6164162941749588780L;
private static final InternalLogger logger = InternalLoggerFactory.getInstance(IpFilterRuleList.class);
@ -56,43 +53,37 @@ public class IpFilterRuleList extends ArrayList<IpFilterRule>
*
* @param rules the rules
*/
public IpFilterRuleList(String rules)
{
public IpFilterRuleList(String rules) {
parseRules(rules);
}
private void parseRules(String rules)
{
private void parseRules(String rules) {
String[] ruless = rules.split(",");
for (String rule : ruless)
{
for (String rule : ruless) {
parseRule(rule.trim());
}
}
private void parseRule(String rule)
{
if (rule == null || rule.length() == 0)
private void parseRule(String rule) {
if (rule == null || rule.length() == 0) {
return;
if (!(rule.startsWith("+") || rule.startsWith("-")))
{
}
if (!(rule.startsWith("+") || rule.startsWith("-"))) {
logger.error("syntax error in ip filter rule:" + rule);
return;
}
boolean allow = rule.startsWith("+");
if (rule.charAt(1) == 'n' || rule.charAt(1) == 'i')
if (rule.charAt(1) == 'n' || rule.charAt(1) == 'i') {
this.add(new PatternRule(allow, rule.substring(1)));
else if (rule.charAt(1) == 'c')
try
{
} else if (rule.charAt(1) == 'c') {
try {
this.add(new IpSubnetFilterRule(allow, rule.substring(3)));
}
catch (UnknownHostException e)
{
} catch (UnknownHostException e) {
logger.error("error parsing ip filter " + rule, e);
}
else
} else {
logger.error("syntax error in ip filter rule:" + rule);
}
}
}

View File

@ -21,8 +21,7 @@ package io.netty.handler.ipfilter;
* <br>
* Users can add an {@link IpFilterListener} to add specific actions in case a connection is allowed or refused.
*/
public interface IpFilteringHandler
{
public interface IpFilteringHandler {
/**
* Sets the filter listener.
@ -31,8 +30,6 @@ public interface IpFilteringHandler
*/
void setIpFilterListener(IpFilterListener listener);
/**
* Remove the filter listener.
*/
/** Remove the filter listener. */
void removeIpFilterListener();
}

View File

@ -26,24 +26,18 @@ import io.netty.channel.ChannelUpstreamHandler;
import io.netty.channel.Channels;
// TODO: Auto-generated Javadoc
/**
* General class that handle Ip Filtering.
*
*/
public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler, IpFilteringHandler
{
/** General class that handle Ip Filtering. */
public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler, IpFilteringHandler {
private IpFilterListener listener = null;
private IpFilterListener listener;
/**
* Called when the channel is connected. It returns True if the corresponding connection
* is to be allowed. Else it returns False.
* @param ctx
* @param e
*
* @param inetSocketAddress the remote {@link InetSocketAddress} from client
* @return True if the corresponding connection is allowed, else False.
* @throws Exception
*/
protected abstract boolean accept(ChannelHandlerContext ctx, ChannelEvent e, InetSocketAddress inetSocketAddress)
throws Exception;
@ -54,35 +48,32 @@ public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler,
* or whatever you need. This method returns a ChannelFuture on which the implementation
* will wait uninterruptibly before closing the channel.<br>
* For instance, If a message is sent back, the corresponding ChannelFuture has to be returned.
* @param ctx
* @param e
*
* @param inetSocketAddress the remote {@link InetSocketAddress} from client
* @return the associated ChannelFuture to be waited for before closing the channel. Null is allowed.
* @throws Exception
*/
protected ChannelFuture handleRefusedChannel(ChannelHandlerContext ctx, ChannelEvent e,
InetSocketAddress inetSocketAddress) throws Exception
{
if (listener == null)
InetSocketAddress inetSocketAddress) throws Exception {
if (listener == null) {
return null;
}
return listener.refused(ctx, e, inetSocketAddress);
}
protected ChannelFuture handleAllowedChannel(ChannelHandlerContext ctx, ChannelEvent e,
InetSocketAddress inetSocketAddress) throws Exception
{
if (listener == null)
InetSocketAddress inetSocketAddress) throws Exception {
if (listener == null) {
return null;
}
return listener.allowed(ctx, e, inetSocketAddress);
}
/**
* Internal method to test if the current channel is blocked. Should not be overridden.
* @param ctx
*
* @return True if the current channel is blocked, else False
*/
protected boolean isBlocked(ChannelHandlerContext ctx)
{
protected boolean isBlocked(ChannelHandlerContext ctx) {
return ctx.getAttachment() != null;
}
@ -92,80 +83,61 @@ public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler,
* If one wants to not block events, just overridden this method by returning always true.<br><br>
* <b>Note that OPENED and BOUND events are still passed to the next entry in the pipeline since
* those events come out before the CONNECTED event and so the possibility to filter the connection.</b>
* @param ctx
* @param e
*
* @return True if the event should continue, False if the event should not continue
* since this channel was blocked by this filter
* @throws Exception
*/
protected boolean continues(ChannelHandlerContext ctx, ChannelEvent e) throws Exception
{
if (listener != null)
protected boolean continues(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (listener != null) {
return listener.continues(ctx, e);
else
} else {
return false;
}
}
/* (non-Javadoc)
* @see io.netty.channel.ChannelUpstreamHandler#handleUpstream(io.netty.channel.ChannelHandlerContext, io.netty.channel.ChannelEvent)
*/
@Override
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception
{
if (e instanceof ChannelStateEvent)
{
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
if (e instanceof ChannelStateEvent) {
ChannelStateEvent evt = (ChannelStateEvent) e;
switch (evt.getState())
{
switch (evt.getState()) {
case OPEN:
case BOUND:
// Special case: OPEND and BOUND events are before CONNECTED,
// but CLOSED and UNBOUND events are after DISCONNECTED: should those events be blocked too?
if (isBlocked(ctx) && !continues(ctx, evt))
{
if (isBlocked(ctx) && !continues(ctx, evt)) {
// don't pass to next level since channel was blocked early
return;
}
else
{
} else {
ctx.sendUpstream(e);
return;
}
case CONNECTED:
if (evt.getValue() != null)
{
if (evt.getValue() != null) {
// CONNECTED
InetSocketAddress inetSocketAddress = (InetSocketAddress) e.getChannel().getRemoteAddress();
if (!accept(ctx, e, inetSocketAddress))
{
if (!accept(ctx, e, inetSocketAddress)) {
ctx.setAttachment(Boolean.TRUE);
ChannelFuture future = handleRefusedChannel(ctx, e, inetSocketAddress);
if (future != null)
{
if (future != null) {
future.addListener(ChannelFutureListener.CLOSE);
}
else
{
} else {
Channels.close(e.getChannel());
}
if (isBlocked(ctx) && !continues(ctx, evt))
{
if (isBlocked(ctx) && !continues(ctx, evt)) {
// don't pass to next level since channel was blocked early
return;
}
}
else
{
} else {
handleAllowedChannel(ctx, e, inetSocketAddress);
}
// This channel is not blocked
ctx.setAttachment(null);
}
else
{
} else {
// DISCONNECTED
if (isBlocked(ctx) && !continues(ctx, evt))
{
if (isBlocked(ctx) && !continues(ctx, evt)) {
// don't pass to next level since channel was blocked early
return;
}
@ -173,8 +145,7 @@ public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler,
break;
}
}
if (isBlocked(ctx) && !continues(ctx, e))
{
if (isBlocked(ctx) && !continues(ctx, e)) {
// don't pass to next level since channel was blocked early
return;
}
@ -186,8 +157,7 @@ public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler,
* @see io.netty.handler.ipfilter.IpFilteringHandler#setIpFilterListener(io.netty.handler.ipfilter.IpFilterListener)
*/
@Override
public void setIpFilterListener(IpFilterListener listener)
{
public void setIpFilterListener(IpFilterListener listener) {
this.listener = listener;
}
@ -195,8 +165,7 @@ public abstract class IpFilteringHandlerImpl implements ChannelUpstreamHandler,
* @see io.netty.handler.ipfilter.IpFilteringHandler#removeIpFilterListener()
*/
@Override
public void removeIpFilterListener()
{
public void removeIpFilterListener() {
this.listener = null;
}

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