Compare commits

..

87 Commits

Author SHA1 Message Date
Ranjith Manickam d0de8bb6e2
Update README.md 2020-12-23 13:00:58 +05:30
Ranjith Manickam 8593f88243 update downloads badge 2020-12-23 12:50:14 +05:30
Ranjith Manickam 9da24f2328 Add maven repo 2020-12-23 12:38:24 +05:30
Ranjith Manickam e31ea59636 Add maven repo 2020-12-23 12:28:11 +05:30
Ranjith Manickam 45b0b98725
Update README.md 2020-11-08 09:58:03 +05:30
Ranjith Manickam 2e505deee1
Update README.md 2020-05-15 16:11:45 +05:30
Ranjith Manickam df80fa0da3
Update README.md 2020-05-13 11:10:57 +05:30
Ranjith Manickam f4c6322793
Update pom.xml 2020-05-13 11:08:04 +05:30
Ranjith Manickam a0eab9407e version update 2020-05-13 11:03:04 +05:30
Ranjith Manickam 1f6e57c164 Fix for - NPE in SessionHandlerValve.java accessing Tomcat's /manager app 2020-05-13 11:02:21 +05:30
Ranjith Manickam 5d0c7aa7a1 Update README.md 2020-05-02 14:53:18 +05:30
Ranjith Manickam 3916e217a5
Update pom.xml 2020-05-02 14:45:13 +05:30
Ranjith Manickam 39df08832a changes to support single-sign-on (sso) 2020-05-02 14:39:17 +05:30
Ranjith Manickam 372332e8dc changes to support single-sign-on (sso) 2020-04-10 07:23:00 +05:30
Ranjith Manickam 7ace9f2b7b changes to support single-sign-on (sso) 2020-04-08 20:59:24 +05:30
Ranjith Manickam 0ecdfc2661 changes to support single-sign-on (sso) 2020-04-08 20:57:07 +05:30
Ranjith Manickam 80acc01418 changes to support single-sign-on (sso) 2020-04-02 12:44:40 +05:30
Ranjith Manickam ab04189b93
Update pom.xml 2020-03-22 00:27:41 +05:30
Ranjith Manickam 246b64def9
Merge pull request #52 from ran-jit/sso
changes to support single-sign-on (sso)
2020-03-22 00:25:18 +05:30
Ranjith Manickam 2b13fdadc9 changes to support single-sign-on (sso) 2020-03-20 23:51:51 +05:30
Ranjith Manickam 16fffca534 updated download summary 2020-02-09 16:23:54 +05:30
Ranjith Manickam b1d33afd0a update 2020-02-09 16:20:57 +05:30
Ranjith Manickam 920662654e
Update README.md 2020-02-09 16:17:36 +05:30
Ranjith Manickam 905ae577c5
Update README.md 2020-02-08 19:13:06 +05:30
Ranjith Manickam 45b1c5a9b0
Update README.md 2020-02-08 19:10:26 +05:30
Ranjith Manickam 9a409e43a4
Update README.md 2020-02-06 10:28:09 +05:30
Ranjith Manickam 113933975c application config system property support changes 2020-02-05 19:37:31 +05:30
Ranjith Manickam f45e1b23a9 application config system property support changes 2020-02-05 17:29:47 +05:30
Ranjith Manickam b73c1b78c2
Update README.md 2019-10-03 12:42:21 +05:30
Ranjith Manickam 094f612138
Update README.md 2019-09-04 22:03:25 +05:30
Ranjith Manickam 3d5afda53e
Update README.md 2019-08-15 13:14:55 +05:30
Ranjith Manickam 8902534782
Update README.md 2019-08-12 19:41:01 +05:30
Ranjith Manickam 7ea845ebca tomcat session persistent policy update 2019-08-12 19:29:32 +05:30
Ranjith Manickam 4eb0e433b1
Update README.md 2019-07-04 02:42:00 +05:30
Ranjith Manickam df14798b1c
Update README.md 2019-07-04 02:28:23 +05:30
Ranjith Manickam a0c0a81332
update.. 2019-07-04 02:23:30 +05:30
Ranjith Manickam 43816ec3c7
Update README.md 2019-06-04 22:43:28 +05:30
Ranjith Manickam 8dcdb983fa
Update pom.xml 2019-05-25 01:40:11 +05:30
Ranjith Manickam 068967a773
Update pom.xml 2019-05-20 04:28:19 +05:30
Ranjith Manickam bbb4023689 Jedis version upgradation fixes. 2019-05-20 03:23:33 +05:30
Ranjith Manickam 82fb1baa19
version update. 2019-05-20 01:49:58 +05:30
Ranjith Manickam b2b2da64f2 version update 2019-05-20 01:49:13 +05:30
Ranjith Manickam 180240b5bb Jedis version updated from 2.9.0 to 3.0.1 for solving redis cluster fixes 2019-05-20 01:36:38 +05:30
Ranjith Manickam b895652ed0
Update README.md 2019-04-27 17:53:12 +05:30
Ranjith Manickam 02004d5bd0
Update README.md 2019-04-27 17:50:15 +05:30
Ranjith Manickam 11e7525e32
Update pom.xml 2019-04-11 00:10:49 +05:30
Ranjith Manickam b3bdf8308c Session remove fixes.. 2019-04-09 18:06:07 +05:30
Ranjith Manickam e631a027ff
Merge pull request #27 from ran-jit/add-license-1
Added LICENSE.md
2019-01-08 21:31:06 +05:30
Ranjith Manickam 8b31223ba6
Create LICENSE.md 2019-01-08 21:30:37 +05:30
Ranjith Manickam 785b629f28 Updated configuration properties. 2018-12-05 02:40:45 +05:30
Ranjith Manickam 40fca0c65f Updated configuration properties. 2018-12-05 02:38:01 +05:30
Ranjith Manickam 35787c2708 Updated configuration properties. 2018-12-05 02:31:53 +05:30
Ranjith Manickam aa52190ed1 Updated configuration properties. 2018-12-05 02:30:20 +05:30
Ranjith Manickam b89e5df0ef Bug fixes and added redis sentinel supportability changes. 2018-12-05 01:57:32 +05:30
Ranjith Manickam 4abfa4b37a Bug fixes and added redis sentinel supportability changes. 2018-12-05 01:56:23 +05:30
Ranjith Manickam de63bca985 Bug fixes and added redis sentinel supportability changes. 2018-12-05 00:30:13 +05:30
Ranjith Manickam aac6ee85f9 Bug fixes and added redis sentinel supportability changes. 2018-12-04 03:17:42 +05:30
Ranjith Manickam ecca5a5794 Bug fixes and added redis sentinel supportability changes. 2018-12-04 03:11:58 +05:30
Ranjith Manickam 551a855675 Bug fixes and added redis sentinel supportability changes. 2018-12-04 03:05:05 +05:30
Ranjith Manickam 8aa5359453 Bug fixes and added redis sentinel supportability changes. 2018-12-04 02:43:03 +05:30
Ranjith Manickam c41cfedd77 Bug fixes and added redis sentinel supportability changes. 2018-12-04 01:39:28 +05:30
Ranjith Manickam 2b09e15466 Bug fixes and added redis sentinel supportability changes. 2018-12-04 01:14:16 +05:30
Ranjith Manickam c4f205cb51 Bug fixes and added redis sentinel supportability changes. 2018-12-04 01:12:08 +05:30
Ranjith Manickam f48861ad95 Bug fixes and added redis sentinel supportability changes. 2018-12-03 00:40:45 +05:30
Ranjith Manickam 6d58ee6d44 Bug fixes and added redis sentinel supportability changes. 2018-12-03 00:15:39 +05:30
Ranjith Manickam 9238d1ee9d Bug fixes and added redis sentinel supportability changes. 2018-12-03 00:06:37 +05:30
Ranjith Manickam d4a2a68a8a Bug fixes and added redis sentinel supportability changes. 2018-12-02 23:47:55 +05:30
Ranjith Manickam 92adf755ba Bug fixes and added redis sentinel supportability changes. 2018-12-02 23:43:37 +05:30
Ranjith Manickam a95d5d9f5c Updated readme for sentinel supportability.. 2018-12-02 23:29:49 +05:30
Ranjith Manickam 8941013e6f Updated readme for sentinel supportability.. 2018-12-02 23:28:15 +05:30
Ranjith Manickam 99813fecc0 removed unused files. 2018-12-02 23:20:30 +05:30
Ranjith Manickam d562a03d63 Bug fixes and added redis sentinel supportability changes. 2018-12-02 23:18:28 +05:30
Ranjith Manickam 9069315d96
Update readMe.txt 2018-11-30 17:23:21 +05:30
Ranjith Manickam 7a0e0cd63a
Update README.md 2018-11-30 17:19:45 +05:30
Ranjith Manickam fbff128b98
Update README.md 2018-11-30 17:19:04 +05:30
Ranjith Manickam 18819ce619
Update README.md 2018-10-13 03:05:36 +05:30
Ranjith Manickam aca60da9df
Update README.md 2018-10-13 03:05:01 +05:30
Ranjith Manickam 628f7b406a Updated intellij files. 2018-08-18 20:21:23 +05:30
Ranjith Manickam 3e7d764356 Update.. 2018-07-12 15:39:01 +05:30
Ranjith Manickam a5dbb89e0d version changes.. 2018-07-09 18:20:11 +05:30
Ranjith Manickam 3164b1e59b
Merge pull request #15 from ran-jit/ranjith/2.0.5
Ranjith/2.0.5
2018-07-09 18:15:29 +05:30
Ranjith Manickam 6aff279fbd Code cleanup 2018-07-09 18:12:27 +05:30
Ranjith Manickam 6a65b99e24 Redis cache changes. 2018-07-05 19:03:13 +05:30
Ranjith Manickam e904a8a2c8
Update README.md 2018-04-28 20:55:57 +05:30
Keerthana b745ce003c version upgrade.. 2018-04-28 20:50:03 +05:30
Keerthana 05c9b7adc9 session expire timeout issue fixes.. 2018-04-28 20:46:55 +05:30
Ranjith Manickam ac38594ff7
version update.. 2018-04-20 13:21:03 +05:30
39 changed files with 3215 additions and 1589 deletions

View File

@ -1,31 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

17
.gitattributes vendored
View File

@ -1,17 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

6
.gitignore vendored
View File

@ -21,3 +21,9 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/target/
# Intellij
.idea/
target/
*.iws
*.iml

View File

@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>tomcat-cluster-redis-session-manager</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>

674
LICENSE.md Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

100
README.md
View File

@ -1,21 +1,43 @@
# Tomcat Clustering Redis Session Manager
Redis session manager is pluggable one. It uses to store sessions into Redis for easy distribution of HTTP Requests across a cluster of Tomcat servers. Sessions are implemented as as non-sticky i.e, each request is forwarded to any server in round-robin manner.
The Redis session manager is pluggable one. It stores session into Redis for easy distribution of HTTP Requests across a cluster of Tomcat servers.
The HTTP Requests session setAttribute(name, value) method stores the session into Redis (must be Serializable) immediately and the session getAttribute(name) method request directly from Redis. Also, the inactive sessions has been removed based on the session time-out configuration.
Here the Sessions are implemented as non-sticky (means, each request can able to go to any server in the cluster, unlike the Apache provided Tomcat clustering setup.)
It supports, both single redis master and redis cluster based on the RedisDataCache.properties configuration.
Request Sessions will be stored into Redis immediately (Session attributes must be Serializable), for the use of other servers. When tomcat receives a request from the client, Sessions are loaded directly from Redis.
Going forward, we no need to enable sticky session (JSESSIONID) in Load balancer.
Supports Redis default, sentinel and cluster mode, based on the configuration.
Going forward, we no need to enable sticky session (JSESSIONID) in Load Balancer.
## Supports:
* Apache Tomcat 7
* Apache Tomcat 8
* Apache Tomcat 9
- Apache Tomcat 7
- Apache Tomcat 8
- Apache Tomcat 9
- Apache Tomcat 10
## Downloads:
* [latest version (2.0.2)](https://github.com/ran-jit/tomcat-cluster-redis-session-manager/releases/tag/2.0.2)
* [older versions](https://github.com/ran-jit/tomcat-cluster-redis-session-manager/wiki)
## Downloads: [![Total Downloads](https://img.shields.io/github/downloads/ran-jit/tomcat-cluster-redis-session-manager/total.svg)](https://github.com/ran-jit/tomcat-cluster-redis-session-manager/wiki)
- [latest version (4.0)](https://github.com/ran-jit/tomcat-cluster-redis-session-manager/releases/tag/4.0)
- [older versions](https://github.com/ran-jit/tomcat-cluster-redis-session-manager/wiki)
<p align="center">
<a href="https://www.buymeacoffee.com/ranmanic" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-red.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
</p>
## Maven configuration
```
<repository>
<id>repsy</id>
<name>tomcat-cluster-redis-session-manager-repo</name>
<url>https://repo.repsy.io/mvn/ranmanic/tomcat-session-manager</url>
</repository>
<dependency>
<groupId>tomcat-session-manager</groupId>
<artifactId>redis</artifactId>
<version>4.0</version>
</dependency>
```
#### Pre-requisite:
1. jedis.jar
@ -26,23 +48,53 @@ more details.. https://github.com/ran-jit/tomcat-cluster-redis-session-manager/w
#### Steps to be done,
1. Move the downloaded jars to tomcat/lib directory
* **tomcat/lib/**
1. Copy the downloaded jars to your tomcat/lib directory.
```
tomcat/lib/
```
2. Add tomcat system property "catalina.base"
* **catalina.base="TOMCAT_LOCATION"**
2. Add tomcat system property "catalina.base".
```
catalina.base="TOMCAT_LOCATION"
example: env "catalina.base=/opt/tomcat" bash
```
3. Extract downloaded package (tomcat-cluster-redis-session-manager.zip) to configure Redis credentials in redis-data-cache.properties file and move the file to tomcat/conf directory
* **tomcat/conf/redis-data-cache.properties**
3. Copy the redis-data-cache.properties file to your tomcat/conf directory and update your Redis server details.
```
tomcat/conf/redis-data-cache.properties
```
4. Add the below two lines in tomcat/conf/context.xml
* **&#60;Valve className="tomcat.request.session.redis.SessionHandlerValve" &#47;&#62;**
* **&#60;Manager className="tomcat.request.session.redis.SessionManager" &#47;&#62;**
4. Add the below two lines in your tomcat/conf/context.xml file.
```
<Valve className="tomcat.request.session.redis.SessionHandlerValve" />
<Manager className="tomcat.request.session.redis.SessionManager" />
```
5. Verify the session expiration time in tomcat/conf/web.xml
* **&#60;session-config&#62;**
* **&#60;session-timeout&#62;60&#60;&#47;session-timeout&#62;**
* **&#60;&#47;session-config&#62;**
5. Verify the session expiration time in tomcat/conf/web.xml file.
```
<session-config>
<session-timeout>60</session-timeout>
</session-config>
```
### Note:
* This supports, both redis stand-alone and multiple node cluster based on the redis-data-cache.properties configuration.
- **All your session attribute values must implement java.io.Serializable.**
### Configuration Properties:
<html>
<body>
<table border="1px" style="width: 80%;margin-left: 10%;margin-right: 10%;line-height: 1.5;">
<tr><th style="width: 30%;">Property</th><th style="width: 50%;">Description</th></tr>
<tr><td>redis.hosts</td><td>Redis server running instance IP address and port number<br/>- ex: 127.0.0.1:6379, 127.0.0.2:6379, 127.0.0.2:6380, ..<br/>- default: 127.0.0.1:6379</td></tr>
<tr><td>redis.password</td><td>Redis protected password</td></tr>
<tr><td>redis.database</td><td>Redis database selection. (Numeric value)<br/>- default: 0</td></tr>
<tr><td>redis.timeout</td><td>Redis connection timeout<br/>- default: 2000 ms</td></tr>
<tr><td>redis.cluster.enabled</td><td>To enable redis cluster mode<br/>- default: false<br>- supported values: true/false</td></tr>
<tr><td>redis.sentinel.enabled</td><td>To enable redis sentinel mode<br/>- default: false<br>- supported values: true/false</td></tr>
<tr><td>redis.sentinel.master</td><td>Redis sentinel master name<br/>- default: mymaster</td></tr>
<tr><td>lb.sticky-session.enabled</td><td>To enable redis and standard session mode<br><br>If enabled,<ol><li>Must be enabled sticky session in your load balancer configuration. Else this manager may not return the updated session values</li><li>Session values are stored in local jvm and redis</li><li>If redis is down/not responding, requests uses jvm stored session values to process user requests. Redis comes back the values will be synced</li></ol>- default: false</td></tr>
<tr><td>session.persistent.policies</td><td>session persistent policies.<br/><br/>- policies - DEFAULT, SAVE_ON_CHANGE, ALWAYS_SAVE_AFTER_REQUEST <br/><ol><li>SAVE_ON_CHANGE: every time session.setAttribute() or session.removeAttribute() is called the session will be saved.</li><li>ALWAYS_SAVE_AFTER_REQUEST: force saving after every request, regardless of whether or not the manager has detected changes to the session.</li></ol>- default: DEFAULT</td></tr>
<tr><td>redis.sso.timeout</td><td>single-sign-on session timeout.<br/>- default: 0 ms (-no expiry)</td></tr>
</table>
</body>
</html>

148
pom.xml
View File

@ -1,68 +1,96 @@
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>tomcat-cluster-redis-session-manager</groupId>
<artifactId>tomcat-cluster-redis-session-manager</artifactId>
<version>2.0.3</version>
<packaging>jar</packaging>
<modelVersion>4.0.0</modelVersion>
<groupId>tomcat-session-manager</groupId>
<artifactId>redis</artifactId>
<version>4.0</version>
<packaging>jar</packaging>
<name>tomcat-cluster-redis-session-manager</name>
<url>http://maven.apache.org</url>
<name>tomcat-cluster-redis-session-manager</name>
<url>https://ranmanic.in</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<developers>
<developer>
<id>ranmanic</id>
<name>Ranjith Manickam</name>
<email>ranjith@ranmanic.in</email>
</developer>
</developers>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
<!-- For local development -->
<!-- <dependency>
<groupId>apache-tomcat</groupId>
<artifactId>catalina</artifactId>
<version>apache-tomcat-8.5.20</version>
</dependency>
<dependency>
<groupId>apache-tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>apache-tomcat-8.5.20</version>
</dependency>
<dependency>
<groupId>apache-tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>apache-tomcat-8.5.20</version>
</dependency> -->
<!-- For local development end.. -->
</dependencies>
<jedis.version>3.0.1</jedis.version>
<commons-pool2.version>2.6.2</commons-pool2.version>
<slf4j-api.version>1.7.26</slf4j-api.version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<maven-compiler.version>3.6.1</maven-compiler.version>
<source-java.version>1.7</source-java.version>
<target-java.version>${source-java.version}</target-java.version>
<!-- For local development properties begins.. -->
<tomcat.version>8.5.32</tomcat.version>
<!-- For local development properties end.. -->
</properties>
<distributionManagement>
<repository>
<id>repsy</id>
<name>tomcat-cluster-redis-session-manager-repo</name>
<url>https://repo.repsy.io/mvn/ranmanic/tomcat-session-manager</url>
</repository>
</distributionManagement>
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>${commons-pool2.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j-api.version}</version>
</dependency>
<!-- For local development dependency begins.. -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-api</artifactId>
<version>${tomcat.version}</version>
</dependency>
<!-- For local development dependency end.. -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler.version}</version>
<configuration>
<source>${source-java.version}</source>
<target>${target-java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,112 +0,0 @@
package tomcat.request.session;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.catalina.util.CustomObjectInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Session serialization utility.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class SerializationUtil {
private ClassLoader loader;
private Log log = LogFactory.getLog(SerializationUtil.class);
/**
* To set class loader
*
* @param loader
*/
public void setClassLoader(ClassLoader loader) {
this.loader = loader;
}
/**
* To get session attributes hash code
*
* @param session
* @return
* @throws IOException
*/
public byte[] getSessionAttributesHashCode(Session session) throws IOException {
byte[] serialized = null;
Map<String, Object> attributes = new HashMap<String, Object>();
for (Enumeration<String> enumerator = session.getAttributeNames(); enumerator.hasMoreElements();) {
String key = enumerator.nextElement();
attributes.put(key, session.getAttribute(key));
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));) {
oos.writeUnshared(attributes);
oos.flush();
serialized = bos.toByteArray();
}
MessageDigest digester = null;
try {
digester = MessageDigest.getInstance("MD5");
} catch (Exception ex) {
log.error("Unable to get MessageDigest instance for MD5", ex);
}
return digester.digest(serialized);
}
/**
* To serialize session object
*
* @param session
* @param metadata
* @return
* @throws IOException
*/
public byte[] serializeSessionData(Session session, SessionMetadata metadata) throws IOException {
byte[] serialized = null;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));) {
oos.writeObject(metadata);
session.writeObjectData(oos);
oos.flush();
serialized = bos.toByteArray();
}
return serialized;
}
/**
* To de-serialize session object
*
* @param data
* @param session
* @param metadata
* @throws IOException
* @throws ClassNotFoundException
*/
public void deserializeSessionData(byte[] data, Session session, SessionMetadata metadata)
throws IOException, ClassNotFoundException {
try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));
ObjectInputStream ois = new CustomObjectInputStream(bis, this.loader);) {
SessionMetadata serializedMetadata = (SessionMetadata) ois.readObject();
metadata.copyFieldsFrom(serializedMetadata);
session.readObjectData(ois);
}
}
}

View File

@ -1,139 +0,0 @@
package tomcat.request.session;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import org.apache.catalina.Manager;
import org.apache.catalina.session.StandardSession;
import tomcat.request.session.redis.SessionManager;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* This class is uses to store and retrieve the HTTP request session objects.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class Session extends StandardSession {
private static final long serialVersionUID = -6056744304016869278L;
protected Boolean dirty;
protected Map<String, Object> changedAttributes;
protected static Boolean manualDirtyTrackingSupportEnabled = false;
protected static String manualDirtyTrackingAttributeKey = "__changed__";
public Session(Manager manager) {
super(manager);
resetDirtyTracking();
}
public void resetDirtyTracking() {
this.changedAttributes = new HashMap<>();
this.dirty = false;
}
public static void setManualDirtyTrackingSupportEnabled(boolean enabled) {
manualDirtyTrackingSupportEnabled = enabled;
}
public static void setManualDirtyTrackingAttributeKey(String key) {
manualDirtyTrackingAttributeKey = key;
}
public Boolean isDirty() {
return this.dirty || !this.changedAttributes.isEmpty();
}
public Map<String, Object> getChangedAttributes() {
return this.changedAttributes;
}
/** {@inheritDoc} */
@Override
public void setId(String id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public void setAttribute(String key, Object value) {
if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) {
this.dirty = true;
return;
}
Object oldValue = getAttribute(key);
super.setAttribute(key, value);
if ((value != null || oldValue != null)
&& (value == null && oldValue != null || oldValue == null && value != null
|| !value.getClass().isInstance(oldValue) || !value.equals(oldValue))) {
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) {
((SessionManager) this.manager).save(this, true);
} else {
this.changedAttributes.put(key, value);
}
}
}
/** {@inheritDoc} */
@Override
public Object getAttribute(String name) {
return super.getAttribute(name);
}
/** {@inheritDoc} */
@Override
public Enumeration<String> getAttributeNames() {
return super.getAttributeNames();
}
/** {@inheritDoc} */
@Override
public void removeAttribute(String name) {
super.removeAttribute(name);
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) {
((SessionManager) this.manager).save(this, true);
} else {
this.dirty = true;
}
}
/** {@inheritDoc} */
@Override
public void setPrincipal(Principal principal) {
super.setPrincipal(principal);
this.dirty = true;
}
/** {@inheritDoc} */
@Override
public void writeObjectData(ObjectOutputStream out) throws IOException {
super.writeObjectData(out);
out.writeLong(this.getCreationTime());
}
/** {@inheritDoc} */
@Override
public void readObjectData(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.readObjectData(in);
this.setCreationTime(in.readLong());
}
/** {@inheritDoc} */
@Override
public void invalidate() {
super.invalidate();
}
}

View File

@ -1,18 +0,0 @@
package tomcat.request.session;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Session constants.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class SessionConstants {
public static final byte[] NULL_SESSION = "null".getBytes();
public static final String CATALINA_BASE = "catalina.base";
public static final String CONF = "conf";
}

View File

@ -1,99 +0,0 @@
package tomcat.request.session;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Session context uses to manage current session data.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class SessionContext {
private String id;
private Session session;
private boolean persisted;
private SessionMetadata metadata;
/**
* To get session id
*
* @return
*/
public String getId() {
return id;
}
/**
* To set session id
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* To get session
*
* @return
*/
public Session getSession() {
return session;
}
/**
* To set session
*
* @param session
*/
public void setSession(Session session) {
this.session = session;
}
/**
* To check session is persisted
*
* @return
*/
public boolean isPersisted() {
return persisted;
}
/**
* To set session persisted
*
* @param persisted
*/
public void setPersisted(boolean persisted) {
this.persisted = persisted;
}
/**
* To get session meta-data
*
* @return
*/
public SessionMetadata getMetadata() {
return metadata;
}
/**
* To set session meta-data
*
* @param metadata
*/
public void setMetadata(SessionMetadata metadata) {
this.metadata = metadata;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "SessionContext [id=" + id + "]";
}
}

View File

@ -1,78 +0,0 @@
package tomcat.request.session;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* This class is uses to store and retrieve the HTTP request session object
* meta-data.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class SessionMetadata implements Serializable {
private static final long serialVersionUID = 124438185184833546L;
private byte[] attributesHash;
public SessionMetadata() {
this.attributesHash = new byte[0];
}
/**
* To get session meta-data hash
*
* @return
*/
public byte[] getAttributesHash() {
return this.attributesHash;
}
/**
* To set session meta-data hash
*
* @param attributesHash
*/
public void setAttributesHash(byte[] attributesHash) {
this.attributesHash = attributesHash;
}
/**
* To copy session meta-data
*
* @param metadata
*/
public void copyFieldsFrom(SessionMetadata metadata) {
this.setAttributesHash(metadata.getAttributesHash());
}
/**
* To write session meta-data to output stream
*
* @param out
* @throws IOException
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(this.attributesHash.length);
out.write(this.attributesHash);
}
/**
* To read session meta-data from input stream
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
int hashLength = in.readInt();
byte[] attributesHash = new byte[hashLength];
in.read(attributesHash, 0, hashLength);
this.attributesHash = attributesHash;
}
}

View File

@ -0,0 +1,24 @@
package tomcat.request.session.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/** author: Ranjith Manickam @ 5 Feb' 2020 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String name() default "";
String defaultValue() default "";
PropertyType type() default PropertyType.STRING;
enum PropertyType {
STRING,
BOOLEAN,
INTEGER,
LONG
}
}

View File

@ -0,0 +1,19 @@
package tomcat.request.session.constant;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public interface SessionConstants {
byte[] NULL_SESSION = "null".getBytes();
enum SessionPolicy {
DEFAULT, SAVE_ON_CHANGE, ALWAYS_SAVE_AFTER_REQUEST;
public static SessionPolicy fromName(String name) {
for (SessionPolicy policy : SessionPolicy.values()) {
if (policy.name().equalsIgnoreCase(name)) {
return policy;
}
}
throw new IllegalArgumentException("Invalid session policy [" + name + "]");
}
}
}

View File

@ -1,58 +1,56 @@
package tomcat.request.session.data.cache;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* API for Data cache.
*
* @author Ranjith Manickam
* @since 2.0
*/
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public interface DataCache {
/**
* To set value in data-cache
*
* @param key
* @param value
* @return
*/
byte[] set(String key, byte[] value);
/**
* Set value in data-cache.
*
* @param key - key with which the specified value is to be associated.
* @param value - value to be associated with the specified key.
* @return - Returns the value.
*/
byte[] set(String key, byte[] value);
/**
* To set value if key not exists in data-cache
*
* Returns If key exists = 0 else 1
*
* @param key
* @param value
* @return
*/
Long setnx(String key, byte[] value);
/**
* Set value if key not exists in data-cache.
*
* @param key - key with which the specified value is to be associated.
* @param value - value to be associated with the specified key.
* @return - Returns '0' if key already exists else '1'.
*/
Long setnx(String key, byte[] value);
/**
* To expire the value based on key in data-cache
*
* @param key
* @param seconds
* @return
*/
Long expire(String key, int seconds);
/**
* Set expiry in data-cache.
*
* @param key - key with which the specified value is to be associated.
* @param seconds - expiration time in seconds.
* @return - Returns the expiration time in seconds.
*/
Long expire(String key, int seconds);
/**
* To get the value based on key from data-cache
*
* @param key
* @return
*/
byte[] get(String key);
/**
* Get value from data-cache.
*
* @param key - key with which the specified value is to be associated.
* @return - Returns the value.
*/
byte[] get(String key);
/**
* To delete the value based on key from data-cache
*
* @param key
* @return
*/
Long delete(String key);
/**
* Delete value from data-cache.
*
* @param key - key with which the specified value is to be associated.
* @return - Returns the number of keys that were removed.
*/
Long delete(String key);
/**
* Check the key exists in data-cache.
*
* @param key - key with which the specified value is to be associated.
* @return - Returns true, if the key exists.
*/
Boolean exists(String key);
}

View File

@ -0,0 +1,25 @@
package tomcat.request.session.data.cache;
import tomcat.request.session.data.cache.impl.StandardDataCache;
import tomcat.request.session.data.cache.impl.redis.RedisCache;
import tomcat.request.session.model.Config;
/** author: Ranjith Manickam @ 3 Dec' 2018 */
public class DataCacheFactory {
private final Config config;
private final int sessionExpiryTime;
public DataCacheFactory(Config config, int sessionExpiryTime) {
this.config = config;
this.sessionExpiryTime = sessionExpiryTime;
}
/** To get data cache. */
public DataCache getDataCache() {
if (this.config.getLbStickySessionEnabled()) {
return new StandardDataCache(this.config, this.sessionExpiryTime);
}
return new RedisCache(this.config);
}
}

View File

@ -1,45 +0,0 @@
package tomcat.request.session.data.cache.impl;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Redis data-cache constants.
*
* @author Ranjith Manickam
* @since 2.0
*/
interface RedisConstants {
// redis properties file name
final String PROPERTIES_FILE = "redis-data-cache.properties";
// redis properties
final String HOSTS = "redis.hosts";
final String CLUSTER_ENABLED = "redis.cluster.enabled";
final String MAX_ACTIVE = "redis.max.active";
final String TEST_ONBORROW = "redis.test.onBorrow";
final String TEST_ONRETURN = "redis.test.onReturn";
final String MAX_IDLE = "redis.max.idle";
final String MIN_IDLE = "redis.min.idle";
final String TEST_WHILEIDLE = "redis.test.whileIdle";
final String TEST_NUMPEREVICTION = "redis.test.numPerEviction";
final String TIME_BETWEENEVICTION = "redis.time.betweenEviction";
final String PASSWORD = "redis.password";
final String DATABASE = "redis.database";
final String TIMEOUT = "redis.timeout";
// redis property default values
final String DEFAULT_MAX_ACTIVE_VALUE = "10";
final String DEFAULT_TEST_ONBORROW_VALUE = "true";
final String DEFAULT_TEST_ONRETURN_VALUE = "true";
final String DEFAULT_MAX_IDLE_VALUE = "5";
final String DEFAULT_MIN_IDLE_VALUE = "1";
final String DEFAULT_TEST_WHILEIDLE_VALUE = "true";
final String DEFAULT_TEST_NUMPEREVICTION_VALUE = "10";
final String DEFAULT_TIME_BETWEENEVICTION_VALUE = "60000";
final String DEFAULT_CLUSTER_ENABLED = "false";
final String CONN_FAILED_RETRY_MSG = "Jedis connection failed, retrying...";
}

View File

@ -1,493 +0,0 @@
package tomcat.request.session.data.cache.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisClusterMaxRedirectionsException;
import redis.clients.jedis.exceptions.JedisConnectionException;
import tomcat.request.session.SessionConstants;
import tomcat.request.session.data.cache.DataCache;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Redis data-cache implementation to store/retrieve session objects.
*
* @author Ranjith Manickam
* @since 2.0
*/
public class RedisDataCache implements DataCache {
private static DataCache dataCache;
private Log log = LogFactory.getLog(RedisDataCache.class);
public RedisDataCache() {
initialize();
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
return dataCache.set(key, value);
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
return dataCache.setnx(key, value);
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
return dataCache.expire(key, seconds);
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
return (key != null) ? dataCache.get(key) : null;
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
return dataCache.delete(key);
}
/**
* To parse data-cache key
*
* @param key
* @return
*/
public static String parseDataCacheKey(String key) {
return key.replaceAll("\\s", "_");
}
/**
* To initialize the data-cache
*
* @param properties
* @param filePath
*/
@SuppressWarnings("unchecked")
private void initialize() {
if (dataCache != null) {
return;
}
Properties properties = loadProperties();
boolean clusterEnabled = Boolean.valueOf(properties.getProperty(RedisConstants.CLUSTER_ENABLED, RedisConstants.DEFAULT_CLUSTER_ENABLED));
String hosts = properties.getProperty(RedisConstants.HOSTS, Protocol.DEFAULT_HOST.concat(":").concat(String.valueOf(Protocol.DEFAULT_PORT)));
Collection<? extends Serializable> nodes = getJedisNodes(hosts, clusterEnabled);
String password = properties.getProperty(RedisConstants.PASSWORD);
password = (password != null && !password.isEmpty()) ? password : null;
int database = Integer.parseInt(properties.getProperty(RedisConstants.DATABASE, String.valueOf(Protocol.DEFAULT_DATABASE)));
int timeout = Integer.parseInt(properties.getProperty(RedisConstants.TIMEOUT, String.valueOf(Protocol.DEFAULT_TIMEOUT)));
timeout = (timeout < Protocol.DEFAULT_TIMEOUT) ? Protocol.DEFAULT_TIMEOUT : timeout;
if (clusterEnabled) {
dataCache = new RedisClusterCacheUtil((Set<HostAndPort>) nodes, password, timeout, getPoolConfig(properties));
} else {
dataCache = new RedisCacheUtil(((List<String>) nodes).get(0),
Integer.parseInt(((List<String>) nodes).get(1)), password, database, timeout, getPoolConfig(properties));
}
}
/**
* To get jedis pool configuration
*
* @param properties
* @return
*/
private JedisPoolConfig getPoolConfig(Properties properties) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
int maxActive = Integer.parseInt(properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE));
poolConfig.setMaxTotal(maxActive);
boolean testOnBorrow = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_ONBORROW, RedisConstants.DEFAULT_TEST_ONBORROW_VALUE));
poolConfig.setTestOnBorrow(testOnBorrow);
boolean testOnReturn = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_ONRETURN, RedisConstants.DEFAULT_TEST_ONRETURN_VALUE));
poolConfig.setTestOnReturn(testOnReturn);
int maxIdle = Integer.parseInt(properties.getProperty(RedisConstants.MAX_ACTIVE, RedisConstants.DEFAULT_MAX_ACTIVE_VALUE));
poolConfig.setMaxIdle(maxIdle);
int minIdle = Integer.parseInt(properties.getProperty(RedisConstants.MIN_IDLE, RedisConstants.DEFAULT_MIN_IDLE_VALUE));
poolConfig.setMinIdle(minIdle);
boolean testWhileIdle = Boolean.parseBoolean(properties.getProperty(RedisConstants.TEST_WHILEIDLE, RedisConstants.DEFAULT_TEST_WHILEIDLE_VALUE));
poolConfig.setTestWhileIdle(testWhileIdle);
int testNumPerEviction = Integer.parseInt(properties.getProperty(RedisConstants.TEST_NUMPEREVICTION, RedisConstants.DEFAULT_TEST_NUMPEREVICTION_VALUE));
poolConfig.setNumTestsPerEvictionRun(testNumPerEviction);
long timeBetweenEviction = Long.parseLong(properties.getProperty(RedisConstants.TIME_BETWEENEVICTION, RedisConstants.DEFAULT_TIME_BETWEENEVICTION_VALUE));
poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEviction);
return poolConfig;
}
/**
* To get jedis nodes
*
* @param hosts
* @param clusterEnabled
* @return
*/
private Collection<? extends Serializable> getJedisNodes(String hosts, boolean clusterEnabled) {
hosts = hosts.replaceAll("\\s", "");
String[] hostPorts = hosts.split(",");
List<String> node = null;
Set<HostAndPort> nodes = null;
for (String hostPort : hostPorts) {
String[] hostPortArr = hostPort.split(":");
if (clusterEnabled) {
nodes = (nodes == null) ? new HashSet<HostAndPort>() : nodes;
nodes.add(new HostAndPort(hostPortArr[0], Integer.valueOf(hostPortArr[1])));
} else {
int port = Integer.valueOf(hostPortArr[1]);
if (!hostPortArr[0].isEmpty() && port > 0) {
node = (node == null) ? new ArrayList<String>() : node;
node.add(hostPortArr[0]);
node.add(String.valueOf(port));
break;
}
}
}
return clusterEnabled ? nodes : node;
}
/**
* To load data-cache properties
*
* @param filePath
* @return
*/
private Properties loadProperties() {
Properties properties = new Properties();
try {
String filePath = System.getProperty(SessionConstants.CATALINA_BASE).concat(File.separator)
.concat(SessionConstants.CONF).concat(File.separator).concat(RedisConstants.PROPERTIES_FILE);
InputStream resourceStream = null;
try {
resourceStream = (filePath != null && !filePath.isEmpty() && new File(filePath).exists())
? new FileInputStream(filePath) : null;
if (resourceStream == null) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
resourceStream = loader.getResourceAsStream(RedisConstants.PROPERTIES_FILE);
}
properties.load(resourceStream);
} finally {
resourceStream.close();
}
} catch (IOException ex) {
log.error("Error while loading task scheduler properties", ex);
}
return properties;
}
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Redis stand-alone mode data-cache implementation.
*
* @author Ranjith Manickam
* @since 2.0
*/
private class RedisCacheUtil implements DataCache {
private JedisPool pool;
private static final int NUM_RETRIES = 3;
private Log log = LogFactory.getLog(RedisCacheUtil.class);
public RedisCacheUtil(String host, int port, String password, int database, int timeout,
JedisPoolConfig poolConfig) {
pool = new JedisPool(poolConfig, host, port, timeout, password, database);
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
int tries = 0;
boolean sucess = false;
String retVal = null;
do {
tries++;
try {
Jedis jedis = pool.getResource();
retVal = jedis.set(key.getBytes(), value);
jedis.close();
sucess = true;
} catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES)
throw ex;
}
} while (!sucess && tries <= NUM_RETRIES);
return (retVal != null) ? retVal.getBytes() : null;
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
Jedis jedis = pool.getResource();
retVal = jedis.setnx(key.getBytes(), value);
jedis.close();
sucess = true;
} catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES)
throw ex;
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
Jedis jedis = pool.getResource();
retVal = jedis.expire(key, seconds);
jedis.close();
sucess = true;
} catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES)
throw ex;
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
int tries = 0;
boolean sucess = false;
byte[] retVal = null;
do {
tries++;
try {
Jedis jedis = pool.getResource();
retVal = jedis.get(key.getBytes());
jedis.close();
sucess = true;
} catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES)
throw ex;
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
Jedis jedis = pool.getResource();
retVal = jedis.del(key);
jedis.close();
sucess = true;
} catch (JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES)
throw ex;
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
}
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Redis multiple node cluster data-cache implementation.
*
* @author Ranjith Manickam
* @since 2.0
*/
private class RedisClusterCacheUtil implements DataCache {
private JedisCluster cluster;
private static final int NUM_RETRIES = 30;
private static final int DEFAULT_MAX_REDIRECTIONS = 5;
private Log log = LogFactory.getLog(RedisClusterCacheUtil.class);
public RedisClusterCacheUtil(Set<HostAndPort> nodes, String password, int timeout, JedisPoolConfig poolConfig) {
cluster = new JedisCluster(nodes, timeout, Protocol.DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, password, poolConfig);
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
int tries = 0;
boolean sucess = false;
String retVal = null;
do {
tries++;
try {
retVal = cluster.set(key.getBytes(), value);
sucess = true;
} catch (JedisClusterMaxRedirectionsException | JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
waitforFailover();
}
} while (!sucess && tries <= NUM_RETRIES);
return (retVal != null) ? retVal.getBytes() : null;
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
retVal = cluster.setnx(key.getBytes(), value);
sucess = true;
} catch (JedisClusterMaxRedirectionsException | JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
waitforFailover();
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
retVal = cluster.expire(key, seconds);
sucess = true;
} catch (JedisClusterMaxRedirectionsException | JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
waitforFailover();
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
int tries = 0;
boolean sucess = false;
byte[] retVal = null;
do {
tries++;
try {
retVal = cluster.get(key.getBytes());
sucess = true;
} catch (JedisClusterMaxRedirectionsException | JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
waitforFailover();
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
int tries = 0;
boolean sucess = false;
Long retVal = null;
do {
tries++;
try {
retVal = cluster.del(key);
sucess = true;
} catch (JedisClusterMaxRedirectionsException | JedisConnectionException ex) {
log.error(RedisConstants.CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
waitforFailover();
}
} while (!sucess && tries <= NUM_RETRIES);
return retVal;
}
/**
* To wait for handling redis fail-over
*/
private void waitforFailover() {
try {
Thread.sleep(4000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}

View File

@ -0,0 +1,229 @@
package tomcat.request.session.data.cache.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tomcat.request.session.data.cache.DataCache;
import tomcat.request.session.data.cache.impl.redis.RedisCache;
import tomcat.request.session.model.Config;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/** author: Ranjith Manickam @ 3 Dec' 2018 */
public class StandardDataCache extends RedisCache {
private boolean processDataSync;
private long expiryJob;
private long dataSyncJob;
private final int sessionExpiryTime;
private final long expiryJobTriggerInterval;
private final long dataSyncJobTriggerInterval;
private final Map<String, SessionData> sessionData;
private final Executor expiryJobExecutor;
private final Executor dataSyncJobExecutor;
public StandardDataCache(Config config, int sessionExpiryTime) {
super(config);
this.sessionExpiryTime = sessionExpiryTime;
this.sessionData = new ConcurrentHashMap<>();
this.expiryJob = new Date().getTime();
this.dataSyncJob = new Date().getTime();
this.processDataSync = false;
this.expiryJobTriggerInterval = TimeUnit.MINUTES.toMillis(config.getRedisSessionExpiryJobInterval());
this.dataSyncJobTriggerInterval = TimeUnit.MINUTES.toMillis(config.getRedisSessionDataSyncJobInterval());
this.expiryJobExecutor = Executors.newSingleThreadExecutor();
this.dataSyncJobExecutor = Executors.newSingleThreadExecutor();
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
this.sessionData.put(key, new SessionData(value));
try {
return super.set(key, value);
} catch (RuntimeException ex) {
this.processDataSync = true;
}
return value;
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
Long retValue;
try {
retValue = super.setnx(key, value);
} catch (RuntimeException ex) {
retValue = this.sessionData.containsKey(key) ? 0L : 1L;
this.processDataSync = true;
}
if (retValue == 1L) {
this.sessionData.put(key, new SessionData(value));
}
return retValue;
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
try {
return super.expire(key, seconds);
} catch (RuntimeException ex) {
this.processDataSync = true;
}
return null;
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
handleSessionData();
if (this.sessionData.containsKey(key)) {
return this.sessionData.get(key).getValue();
}
try {
return super.get(key);
} catch (RuntimeException ex) {
this.processDataSync = true;
throw ex;
}
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
Object value = this.sessionData.remove(key);
try {
return super.delete(key);
} catch (RuntimeException ex) {
this.processDataSync = true;
}
return (value == null) ? 0L : 1L;
}
/** {@inheritDoc} */
@Override
public Boolean exists(String key) {
return this.sessionData.containsKey(key);
}
/** Session data. */
private static class SessionData implements Serializable {
private byte[] value;
private long lastAccessedOn;
SessionData(byte[] value) {
this.value = value;
updatedLastAccessedOn();
}
void updatedLastAccessedOn() {
this.lastAccessedOn = new Date().getTime();
}
byte[] getValue() {
updatedLastAccessedOn();
return this.value;
}
long getLastAccessedOn() {
return this.lastAccessedOn;
}
}
/** To handle session data. */
private synchronized void handleSessionData() {
// redis sync
long now = new Date().getTime();
long difference = now - this.dataSyncJob;
if (this.processDataSync && difference >= this.dataSyncJobTriggerInterval) {
this.dataSyncJobExecutor.execute(new SessionDataSyncThread(this, this.sessionData, this.sessionExpiryTime));
this.dataSyncJob = (this.processDataSync) ? new Date().getTime() : this.dataSyncJob;
this.processDataSync = false;
}
// session expiry
difference = now - this.expiryJob;
if (difference >= this.expiryJobTriggerInterval) {
this.expiryJobExecutor.execute(new SessionDataExpiryThread(this.sessionData, this.sessionExpiryTime));
this.expiryJob = new Date().getTime();
}
}
/** Session data redis sync thread. */
private static class SessionDataSyncThread implements Runnable {
private final Logger LOGGER = LoggerFactory.getLogger(SessionDataSyncThread.class);
private final DataCache dataCache;
private final int sessionExpiryTime;
private final Map<String, SessionData> sessionData;
SessionDataSyncThread(DataCache dataCache, Map<String, SessionData> sessionData, int sessionExpiryTime) {
this.dataCache = dataCache;
this.sessionData = sessionData;
this.sessionExpiryTime = sessionExpiryTime;
}
/** {@inheritDoc} */
@Override
public void run() {
try {
for (String key : this.sessionData.keySet()) {
SessionData data = this.sessionData.get(key);
if (data == null) {
continue;
}
this.dataCache.set(key, data.getValue());
this.dataCache.expire(key, this.sessionExpiryTime);
}
} catch (Exception ex) {
LOGGER.error("Error processing session data expiry thread", ex);
}
}
}
/** Session data expiry thread. This will takes care of the session expired data removal. */
private static class SessionDataExpiryThread implements Runnable {
private final Logger LOGGER = LoggerFactory.getLogger(SessionDataExpiryThread.class);
private final long expiry;
private final Map<String, SessionData> sessionData;
SessionDataExpiryThread(Map<String, SessionData> sessionData, int sessionExpiryTime) {
this.sessionData = sessionData;
this.expiry = TimeUnit.SECONDS.toMillis(sessionExpiryTime + 60);
}
/** {@inheritDoc} */
@Override
public void run() {
try {
for (String key : this.sessionData.keySet()) {
SessionData data = this.sessionData.get(key);
if (data == null) {
continue;
}
long difference = new Date().getTime() - data.getLastAccessedOn();
if (difference >= this.expiry) {
this.sessionData.remove(key);
}
}
} catch (Exception ex) {
LOGGER.error("Error processing session data expiry thread", ex);
}
}
}
}

View File

@ -0,0 +1,145 @@
package tomcat.request.session.data.cache.impl.redis;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPoolConfig;
import tomcat.request.session.data.cache.DataCache;
import tomcat.request.session.model.Config;
import tomcat.request.session.model.Config.RedisConfigType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class RedisCache implements DataCache {
private DataCache dataCache;
public RedisCache(Config config) {
initialize(config);
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
return this.dataCache.set(key, value);
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
return this.dataCache.setnx(key, value);
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
return this.dataCache.expire(key, seconds);
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
return this.dataCache.get(key);
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
return this.dataCache.delete(key);
}
/** {@inheritDoc} */
@Override
public Boolean exists(String key) {
return this.dataCache.exists(key);
}
private void initialize(Config config) {
Collection<?> nodes = getJedisNodes(config.getRedisHosts(), config.getRedisConfigType());
JedisPoolConfig poolConfig = getPoolConfig(config);
switch (config.getRedisConfigType()) {
case CLUSTER:
this.dataCache = new RedisClusterManager((Set<HostAndPort>) nodes,
config.getRedisPassword(),
config.getRedisTimeout(),
poolConfig);
break;
case SENTINEL:
this.dataCache = new RedisSentinelManager((Set<String>) nodes,
config.getRedisSentinelMaster(),
config.getRedisPassword(),
config.getRedisDatabase(),
config.getRedisTimeout(),
poolConfig);
break;
default:
this.dataCache = new RedisStandardManager(((List<String>) nodes).get(0),
Integer.parseInt(((List<String>) nodes).get(1)),
config.getRedisPassword(),
config.getRedisDatabase(),
config.getRedisTimeout(),
poolConfig);
break;
}
}
/**
* To get redis pool config.
*
* @param config - Application config.
* @return - Returns the redis pool config.
*/
private JedisPoolConfig getPoolConfig(Config config) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(config.getRedisMaxActive());
poolConfig.setTestOnBorrow(config.getRedisTestOnBorrow());
poolConfig.setTestOnReturn(config.getRedisTestOnReturn());
poolConfig.setMaxIdle(config.getRedisMaxIdle());
poolConfig.setMinIdle(config.getRedisMinIdle());
poolConfig.setTestWhileIdle(config.getRedisTestWhileIdle());
poolConfig.setNumTestsPerEvictionRun(config.getRedisTestNumPerEviction());
poolConfig.setTimeBetweenEvictionRunsMillis(config.getRedisTimeBetweenEviction());
return poolConfig;
}
/**
* To get redis data cache nodes.
*
* @param hosts - redis server hosts.
* @param configType - redis data config type.
* @return - Returns the redis nodes.
*/
private Collection<?> getJedisNodes(String hosts, RedisConfigType configType) {
hosts = hosts.replaceAll("\\s", "");
String[] hostPorts = hosts.split(",");
Set<Object> nodes = null;
for (String hostPort : hostPorts) {
String[] hostPortArr = hostPort.split(":");
switch (configType) {
case CLUSTER:
nodes = (nodes == null) ? new HashSet<>() : nodes;
nodes.add(new HostAndPort(hostPortArr[0], Integer.parseInt(hostPortArr[1])));
break;
case SENTINEL:
nodes = (nodes == null) ? new HashSet<>() : nodes;
nodes.add(new HostAndPort(hostPortArr[0], Integer.parseInt(hostPortArr[1])).toString());
break;
default:
int port = Integer.parseInt(hostPortArr[1]);
if (!hostPortArr[0].isEmpty() && port > 0) {
List<String> node = new ArrayList<>();
node.add(hostPortArr[0]);
node.add(String.valueOf(port));
return node;
}
}
}
return nodes;
}
}

View File

@ -0,0 +1,136 @@
package tomcat.request.session.data.cache.impl.redis;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisRedirectionException;
import java.util.Set;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
class RedisClusterManager extends RedisManager {
private final JedisCluster cluster;
private static final int NUM_RETRIES = 30;
private static final int DEFAULT_MAX_RE_DIRECTIONS = 5;
private static final long FAILURE_WAIT_TIME = 4000L;
RedisClusterManager(Set<HostAndPort> nodes,
String password,
int timeout,
JedisPoolConfig poolConfig) {
super(null, FAILURE_WAIT_TIME);
this.cluster = new JedisCluster(nodes, timeout, Protocol.DEFAULT_TIMEOUT, DEFAULT_MAX_RE_DIRECTIONS, password, poolConfig);
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
int tries = 0;
boolean retry = true;
String retVal = null;
do {
tries++;
try {
retVal = this.cluster.set(key.getBytes(), value);
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return (retVal != null) ? retVal.getBytes() : null;
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try {
retVal = this.cluster.setnx(key.getBytes(), value);
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try {
retVal = this.cluster.expire(key, seconds);
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
int tries = 0;
boolean retry = true;
byte[] retVal = null;
do {
tries++;
try {
retVal = this.cluster.get(key.getBytes());
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try {
retVal = this.cluster.del(key);
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Boolean exists(String key) {
int tries = 0;
boolean retry = true;
Boolean retVal = null;
do {
tries++;
try {
retVal = this.cluster.exists(key);
retry = false;
} catch (JedisRedirectionException | JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
}

View File

@ -0,0 +1,151 @@
package tomcat.request.session.data.cache.impl.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.util.Pool;
import tomcat.request.session.data.cache.DataCache;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
abstract class RedisManager implements DataCache {
private static final int NUM_RETRIES = 3;
private static final Logger LOGGER = LoggerFactory.getLogger(RedisManager.class);
private static final String REDIS_CONN_FAILED_RETRY_MSG = "Jedis connection failed, retrying...";
private final Pool<Jedis> pool;
private final long failureWaitTime;
RedisManager(Pool<Jedis> pool, long failureWaitTime) {
this.pool = pool;
this.failureWaitTime = failureWaitTime;
}
/** {@inheritDoc} */
@Override
public byte[] set(String key, byte[] value) {
int tries = 0;
boolean retry = true;
String retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.set(key.getBytes(), value);
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return (retVal != null) ? retVal.getBytes() : null;
}
/** {@inheritDoc} */
@Override
public Long setnx(String key, byte[] value) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.setnx(key.getBytes(), value);
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long expire(String key, int seconds) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.expire(key, seconds);
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public byte[] get(String key) {
int tries = 0;
boolean retry = true;
byte[] retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.get(key.getBytes());
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Long delete(String key) {
int tries = 0;
boolean retry = true;
Long retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.del(key);
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/** {@inheritDoc} */
@Override
public Boolean exists(String key) {
int tries = 0;
boolean retry = true;
Boolean retVal = null;
do {
tries++;
try (Jedis jedis = this.pool.getResource()) {
retVal = jedis.exists(key);
retry = false;
} catch (JedisConnectionException ex) {
handleException(tries, ex);
}
} while (retry && tries <= NUM_RETRIES);
return retVal;
}
/**
* To handle jedis exception.
*
* @param tries - exception occurred in tries.
* @param ex - jedis exception.
*/
void handleException(int tries, RuntimeException ex) {
LOGGER.error(REDIS_CONN_FAILED_RETRY_MSG + tries);
if (tries == NUM_RETRIES) {
throw ex;
}
try {
Thread.sleep(this.failureWaitTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

View File

@ -0,0 +1,21 @@
package tomcat.request.session.data.cache.impl.redis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import java.util.Set;
/** author: Ranjith Manickam @ 3 Dec' 2018 */
class RedisSentinelManager extends RedisManager {
private static final long FAILURE_WAIT_TIME = 2000L;
RedisSentinelManager(Set<String> nodes,
String masterName,
String password,
int database,
int timeout,
JedisPoolConfig poolConfig) {
super(new JedisSentinelPool(masterName, nodes, poolConfig, timeout, password, database), FAILURE_WAIT_TIME);
}
}

View File

@ -0,0 +1,19 @@
package tomcat.request.session.data.cache.impl.redis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
class RedisStandardManager extends RedisManager {
private static final long FAILURE_WAIT_TIME = 2000L;
RedisStandardManager(String host,
int port,
String password,
int database,
int timeout,
JedisPoolConfig poolConfig) {
super(new JedisPool(poolConfig, host, port, timeout, password, database), FAILURE_WAIT_TIME);
}
}

View File

@ -0,0 +1,11 @@
package tomcat.request.session.exception;
/** author: Ranjith Manickam @ 3 Dec' 2018 */
public class BackendException extends RuntimeException {
private static final String ERROR_MESSAGE = "For some reason we couldn't process your request. Please contact system administrator for more details.";
public BackendException() {
super(ERROR_MESSAGE, null, false, false);
}
}

View File

@ -0,0 +1,266 @@
package tomcat.request.session.model;
import redis.clients.jedis.Protocol;
import tomcat.request.session.annotation.Property;
import java.io.Serializable;
import static tomcat.request.session.annotation.Property.PropertyType.BOOLEAN;
import static tomcat.request.session.annotation.Property.PropertyType.INTEGER;
/** author: Ranjith Manickam @ 5 Feb' 2020 */
public class Config implements Serializable {
private static final long serialVersionUID = 3480402257971437776L;
public static final String APPLICATION_PROPERTIES_FILE = "redis-data-cache.properties";
/** Redis config type. */
public enum RedisConfigType {
DEFAULT,
SENTINEL,
CLUSTER
}
@Property(name = "redis.hosts", defaultValue = "127.0.0.1:6379")
private String redisHosts;
@Property(name = "redis.cluster.enabled", type = BOOLEAN, defaultValue = "false")
private Boolean redisClusterEnabled;
@Property(name = "redis.sentinel.enabled", type = BOOLEAN, defaultValue = "false")
private Boolean redisSentinelEnabled;
@Property(name = "lb.sticky-session.enabled", type = BOOLEAN, defaultValue = "false")
private Boolean lbStickySessionEnabled;
@Property(name = "redis.max.active", type = INTEGER, defaultValue = "10")
private Integer redisMaxActive;
@Property(name = "redis.test.onBorrow", type = BOOLEAN, defaultValue = "true")
private Boolean redisTestOnBorrow;
@Property(name = "redis.test.onReturn", type = BOOLEAN, defaultValue = "true")
private Boolean redisTestOnReturn;
@Property(name = "redis.max.idle", type = INTEGER, defaultValue = "5")
private Integer redisMaxIdle;
@Property(name = "redis.min.idle", type = INTEGER, defaultValue = "1")
private Integer redisMinIdle;
@Property(name = "redis.test.whileIdle", type = BOOLEAN, defaultValue = "true")
private Boolean redisTestWhileIdle;
@Property(name = "redis.test.numPerEviction", type = INTEGER, defaultValue = "10")
private Integer redisTestNumPerEviction;
@Property(name = "redis.time.betweenEviction", type = INTEGER, defaultValue = "60000")
private Integer redisTimeBetweenEviction;
@Property(name = "redis.password")
private String redisPassword;
@Property(name = "redis.database", type = INTEGER, defaultValue = "0")
private Integer redisDatabase;
@Property(name = "redis.timeout", type = INTEGER, defaultValue = "2000")
private Integer redisTimeout;
@Property(name = "redis.sentinel.master", defaultValue = "mymaster")
private String redisSentinelMaster;
@Property(name = "redis.session.expiry.job.interval", type = INTEGER, defaultValue = "60")
private Integer redisSessionExpiryJobInterval;
@Property(name = "redis.session.data-sync.job.interval", type = INTEGER, defaultValue = "10")
private Integer redisSessionDataSyncJobInterval;
@Property(name = "session.persistent.policies", defaultValue = "DEFAULT")
private String sessionPersistentPolicies;
@Property(name = "redis.sso.timeout", type = INTEGER, defaultValue = "0")
private Integer redisSSOTimeout;
public Config() {
}
public Config(String redisHosts,
Boolean redisClusterEnabled,
Boolean redisSentinelEnabled,
Boolean lbStickySessionEnabled,
Integer redisMaxActive,
Boolean redisTestOnBorrow,
Boolean redisTestOnReturn,
Integer redisMaxIdle,
Integer redisMinIdle,
Boolean redisTestWhileIdle,
Integer redisTestNumPerEviction,
Integer redisTimeBetweenEviction,
String redisPassword,
Integer redisDatabase,
Integer redisTimeout,
String redisSentinelMaster,
Integer redisSessionExpiryJobInterval,
Integer redisSessionDataSyncJobInterval,
String sessionPersistentPolicies,
Integer redisSSOTimeout) {
this.redisHosts = redisHosts;
this.redisClusterEnabled = redisClusterEnabled;
this.redisSentinelEnabled = redisSentinelEnabled;
this.lbStickySessionEnabled = lbStickySessionEnabled;
this.redisMaxActive = redisMaxActive;
this.redisTestOnBorrow = redisTestOnBorrow;
this.redisTestOnReturn = redisTestOnReturn;
this.redisMaxIdle = redisMaxIdle;
this.redisMinIdle = redisMinIdle;
this.redisTestWhileIdle = redisTestWhileIdle;
this.redisTestNumPerEviction = redisTestNumPerEviction;
this.redisTimeBetweenEviction = redisTimeBetweenEviction;
this.redisPassword = redisPassword;
this.redisDatabase = redisDatabase;
this.redisTimeout = redisTimeout;
this.redisSentinelMaster = redisSentinelMaster;
this.redisSessionExpiryJobInterval = redisSessionExpiryJobInterval;
this.redisSessionDataSyncJobInterval = redisSessionDataSyncJobInterval;
this.sessionPersistentPolicies = sessionPersistentPolicies;
this.redisSSOTimeout = redisSSOTimeout;
}
/** To get 'redis.hosts' value. */
public String getRedisHosts() {
return redisHosts;
}
/** To get 'redis.cluster.enabled' value. */
public Boolean getRedisClusterEnabled() {
return redisClusterEnabled;
}
/** To get 'redis.sentinel.enabled' value. */
public Boolean getRedisSentinelEnabled() {
return redisSentinelEnabled;
}
/** To get 'lb.sticky-session.enabled' value. */
public Boolean getLbStickySessionEnabled() {
return lbStickySessionEnabled;
}
/** To get 'redis.max.active' value. */
public Integer getRedisMaxActive() {
return redisMaxActive;
}
/** To get 'redis.test.onBorrow' value. */
public Boolean getRedisTestOnBorrow() {
return redisTestOnBorrow;
}
/** To get 'redis.test.onReturn' value. */
public Boolean getRedisTestOnReturn() {
return redisTestOnReturn;
}
/** To get 'redis.max.idle' value. */
public Integer getRedisMaxIdle() {
return redisMaxIdle;
}
/** To get 'redis.min.idle' value. */
public Integer getRedisMinIdle() {
return redisMinIdle;
}
/** To get 'redis.test.whileIdle' value. */
public Boolean getRedisTestWhileIdle() {
return redisTestWhileIdle;
}
/** To get 'redis.test.numPerEviction' value. */
public Integer getRedisTestNumPerEviction() {
return redisTestNumPerEviction;
}
/** To get 'redis.time.betweenEviction' value. */
public Integer getRedisTimeBetweenEviction() {
return redisTimeBetweenEviction;
}
/** To get 'redis.password' value. */
public String getRedisPassword() {
return (redisPassword == null || redisPassword.isEmpty()) ? null : redisPassword;
}
/** To get 'redis.database' value. */
public Integer getRedisDatabase() {
return redisDatabase;
}
/** To get 'redis.timeout' value. */
public Integer getRedisTimeout() {
return Math.max(redisTimeout, Protocol.DEFAULT_TIMEOUT);
}
/** To get 'redis.sentinel.master' value. */
public String getRedisSentinelMaster() {
return redisSentinelMaster;
}
/** To get 'redis.session.expiry.job.interval' value. */
public Integer getRedisSessionExpiryJobInterval() {
return redisSessionExpiryJobInterval;
}
/** To get 'redis.session.data-sync.job.interval' value. */
public Integer getRedisSessionDataSyncJobInterval() {
return redisSessionDataSyncJobInterval;
}
/** To get 'session.persistent.policies' value */
public String getSessionPersistentPolicies() {
return sessionPersistentPolicies;
}
/** To get 'redis.sso.timeout' value */
public Integer getRedisSSOTimeout() {
return redisSSOTimeout;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "Config{" +
"redisHosts='" + redisHosts + '\'' +
", redisClusterEnabled=" + redisClusterEnabled +
", redisSentinelEnabled=" + redisSentinelEnabled +
", lbStickySessionEnabled=" + lbStickySessionEnabled +
", redisMaxActive=" + redisMaxActive +
", redisTestOnBorrow=" + redisTestOnBorrow +
", redisTestOnReturn=" + redisTestOnReturn +
", redisMaxIdle=" + redisMaxIdle +
", redisMinIdle=" + redisMinIdle +
", redisTestWhileIdle=" + redisTestWhileIdle +
", redisTestNumPerEviction=" + redisTestNumPerEviction +
", redisTimeBetweenEviction=" + redisTimeBetweenEviction +
", redisPassword='" + redisPassword + '\'' +
", redisDatabase=" + redisDatabase +
", redisTimeout=" + redisTimeout +
", redisSentinelMaster='" + redisSentinelMaster + '\'' +
", redisSessionExpiryJobInterval=" + redisSessionExpiryJobInterval +
", redisSessionDataSyncJobInterval=" + redisSessionDataSyncJobInterval +
", sessionPersistentPolicies='" + sessionPersistentPolicies + '\'' +
", redisSSOTimeout='" + redisSSOTimeout + '\'' +
'}';
}
/** To get redis config type. */
public RedisConfigType getRedisConfigType() {
if (this.getRedisClusterEnabled()) {
return RedisConfigType.CLUSTER;
} else if (this.getRedisSentinelEnabled()) {
return RedisConfigType.SENTINEL;
}
return RedisConfigType.DEFAULT;
}
}

View File

@ -0,0 +1,133 @@
package tomcat.request.session.model;
import org.apache.catalina.Manager;
import org.apache.catalina.session.StandardSession;
import tomcat.request.session.redis.SessionManager;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class Session extends StandardSession {
private static final long serialVersionUID = -6056744304016869278L;
private Boolean dirty;
private Map<String, Object> changedAttributes;
private static Boolean manualDirtyTrackingSupportEnabled = false;
private static String manualDirtyTrackingAttributeKey = "__changed__";
public Session(Manager manager) {
super(manager);
resetDirtyTracking();
}
/** To reset dirty tracking. */
public void resetDirtyTracking() {
this.changedAttributes = new HashMap<>();
this.dirty = false;
}
/** To set manual dirty tracking support enabled. */
public static void setManualDirtyTrackingSupportEnabled(boolean enabled) {
manualDirtyTrackingSupportEnabled = enabled;
}
/** To set manual dirty tracking attribute key. */
public static void setManualDirtyTrackingAttributeKey(String key) {
manualDirtyTrackingAttributeKey = key;
}
/** Returns dirty check. */
public Boolean isDirty() {
return this.dirty || !this.changedAttributes.isEmpty();
}
/** To get changed attributes. */
public Map<String, Object> getChangedAttributes() {
return this.changedAttributes;
}
/** {@inheritDoc} */
@Override
public void setId(String id) {
this.id = id;
}
/** {@inheritDoc} */
@Override
public void setAttribute(String key, Object value) {
if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) {
this.dirty = true;
return;
}
Object oldValue = getAttribute(key);
super.setAttribute(key, value);
if ((value != null || oldValue != null)
&& (value == null && oldValue != null || oldValue == null && value != null || !value.getClass().isInstance(oldValue) || !value.equals(oldValue))) {
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) {
((SessionManager) this.manager).save(this, true);
} else {
this.changedAttributes.put(key, value);
}
}
}
/** {@inheritDoc} */
@Override
public Object getAttribute(String name) {
return super.getAttribute(name);
}
/** {@inheritDoc} */
@Override
public Enumeration<String> getAttributeNames() {
return super.getAttributeNames();
}
/** {@inheritDoc} */
@Override
public void removeAttribute(String name) {
super.removeAttribute(name);
if (this.manager instanceof SessionManager && ((SessionManager) this.manager).getSaveOnChange()) {
((SessionManager) this.manager).save(this, true);
} else {
this.dirty = true;
}
}
/** {@inheritDoc} */
@Override
public void setPrincipal(Principal principal) {
super.setPrincipal(principal);
this.dirty = true;
}
/** {@inheritDoc} */
@Override
public void writeObjectData(ObjectOutputStream out) throws IOException {
super.writeObjectData(out);
out.writeLong(this.getCreationTime());
}
/** {@inheritDoc} */
@Override
public void readObjectData(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.readObjectData(in);
this.setCreationTime(in.readLong());
}
/** {@inheritDoc} */
@Override
public void invalidate() {
super.invalidate();
}
}

View File

@ -0,0 +1,56 @@
package tomcat.request.session.model;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class SessionContext {
private String id;
private Session session;
private boolean persisted;
private SessionMetadata metadata;
/** To get session id. */
public String getId() {
return id;
}
/** To set session id. */
public void setId(String id) {
this.id = id;
}
/** To get session. */
public Session getSession() {
return session;
}
/** To set session. */
public void setSession(Session session) {
this.session = session;
}
/** To check session is persisted. */
public boolean isPersisted() {
return persisted;
}
/** To set session persisted. */
public void setPersisted(boolean persisted) {
this.persisted = persisted;
}
/** To get session meta-data. */
public SessionMetadata getMetadata() {
return metadata;
}
/** To set session meta-data. */
public void setMetadata(SessionMetadata metadata) {
this.metadata = metadata;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "SessionContext [id=" + id + "]";
}
}

View File

@ -0,0 +1,47 @@
package tomcat.request.session.model;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class SessionMetadata implements Serializable {
private static final long serialVersionUID = 124438185184833546L;
private byte[] attributesHash;
public SessionMetadata() {
this.attributesHash = new byte[0];
}
/** To get session meta-data hash. */
public byte[] getAttributesHash() {
return this.attributesHash;
}
/** To set session meta-data hash. */
public void setAttributesHash(byte[] attributesHash) {
this.attributesHash = attributesHash;
}
/** To copy session meta-data. */
public void copyFieldsFrom(SessionMetadata metadata) {
this.setAttributesHash(metadata.getAttributesHash());
}
/** To write session meta-data to output stream. */
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(this.attributesHash.length);
out.write(this.attributesHash);
}
/** To read session meta-data from input stream. */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
int hashLength = in.readInt();
byte[] attributesHash = new byte[hashLength];
in.read(attributesHash, 0, hashLength);
this.attributesHash = attributesHash;
}
}

View File

@ -0,0 +1,100 @@
package tomcat.request.session.model;
import org.apache.catalina.Session;
import org.apache.catalina.authenticator.SingleSignOnListener;
import org.apache.catalina.authenticator.SingleSignOnSessionKey;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.security.Principal;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/** author: Ranjith Manickam @ 20 Mar' 2020 */
public class SingleSignOnEntry implements Serializable {
private static final long serialVersionUID = 4590485271396917062L;
private String authType;
private String password;
private Principal principal;
private String username;
private boolean canReauthenticate = false;
private final ConcurrentMap<SingleSignOnSessionKey, SingleSignOnSessionKey> sessionKeys;
public SingleSignOnEntry() {
this.sessionKeys = new ConcurrentHashMap<>();
}
public SingleSignOnEntry(Principal principal, String authType, String username, String password) {
this.sessionKeys = new ConcurrentHashMap<>();
this.updateCredentials(principal, authType, username, password);
}
public void addSession(String ssoId, Session session) {
SingleSignOnSessionKey key = new SingleSignOnSessionKey(session);
SingleSignOnSessionKey currentKey = this.sessionKeys.putIfAbsent(key, key);
if (currentKey == null) {
session.addSessionListener(new SingleSignOnListener(ssoId));
}
}
public void removeSession(Session session) {
SingleSignOnSessionKey key = new SingleSignOnSessionKey(session);
this.sessionKeys.remove(key);
}
public Set<SingleSignOnSessionKey> findSessions() {
return this.sessionKeys.keySet();
}
public String getAuthType() {
return this.authType;
}
public boolean getCanReauthenticate() {
return this.canReauthenticate;
}
public String getPassword() {
return this.password;
}
public Principal getPrincipal() {
return this.principal;
}
public String getUsername() {
return this.username;
}
public synchronized void updateCredentials(Principal principal, String authType, String username, String password) {
this.principal = principal;
this.authType = authType;
this.username = username;
this.password = password;
this.canReauthenticate = "BASIC".equals(authType) || "FORM".equals(authType);
}
public void writeObjectData(ObjectOutputStream out) throws IOException {
try (ObjectOutputStream outputStream = new ObjectOutputStream(out)) {
outputStream.writeObject(this);
outputStream.flush();
}
}
public void readObjectData(ObjectInputStream in) throws IOException, ClassNotFoundException {
try (ObjectInputStream inputStream = new ObjectInputStream(in)) {
SingleSignOnEntry entry = (SingleSignOnEntry) inputStream.readObject();
this.authType = entry.authType;
this.password = entry.password;
this.principal = entry.principal;
this.username = entry.username;
this.canReauthenticate = entry.canReauthenticate;
this.sessionKeys.putAll(entry.sessionKeys);
}
}
}

View File

@ -1,42 +1,39 @@
package tomcat.request.session.redis;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tomcat.request.session.exception.BackendException;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Valve that implements per-request session persistence. It is intended to be
* used with non-sticky load-balancers.
*
* @author Ranjith Manickam
* @since 2.0
*/
import javax.servlet.ServletException;
import java.io.IOException;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class SessionHandlerValve extends ValveBase {
private SessionManager manager;
private static final Logger LOGGER = LoggerFactory.getLogger(SessionHandlerValve.class);
/**
* To set session manager
*
* @param manager
*/
public void setSessionManager(SessionManager manager) {
this.manager = manager;
}
private SessionManager manager;
/** {@inheritDoc} */
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
try {
getNext().invoke(request, response);
} finally {
manager.afterRequest(request);
}
}
/** To set session manager */
void setSessionManager(SessionManager manager) {
this.manager = manager;
}
/** {@inheritDoc} */
@Override
public void invoke(Request request, Response response) throws BackendException {
try {
getNext().invoke(request, response);
} catch (IOException | ServletException | RuntimeException ex) {
LOGGER.error("Error processing request", ex);
throw new BackendException();
} finally {
if (this.manager != null) {
this.manager.afterRequest();
}
}
}
}

View File

@ -1,407 +1,384 @@
package tomcat.request.session.redis;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.session.ManagerBase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import tomcat.request.session.SerializationUtil;
import tomcat.request.session.Session;
import tomcat.request.session.SessionConstants;
import tomcat.request.session.SessionContext;
import tomcat.request.session.SessionMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tomcat.request.session.constant.SessionConstants;
import tomcat.request.session.constant.SessionConstants.SessionPolicy;
import tomcat.request.session.data.cache.DataCache;
import tomcat.request.session.data.cache.impl.RedisDataCache;
import tomcat.request.session.data.cache.DataCacheFactory;
import tomcat.request.session.model.Config;
import tomcat.request.session.model.Session;
import tomcat.request.session.model.SessionContext;
import tomcat.request.session.model.SessionMetadata;
import tomcat.request.session.model.SingleSignOnEntry;
import tomcat.request.session.util.ConfigUtil;
import tomcat.request.session.util.SerializationUtil;
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Manager that implements per-request session persistence. It is intended to be
* used with non-sticky load-balancers.
*
* @author Ranjith Manickam
* @since 2.0
*/
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class SessionManager extends ManagerBase implements Lifecycle {
private DataCache dataCache;
private static final Logger LOGGER = LoggerFactory.getLogger(SessionManager.class);
protected SerializationUtil serializer;
private Integer ssoTimeout;
private DataCache dataCache;
private SerializationUtil serializer;
private final ThreadLocal<SessionContext> sessionContext = new ThreadLocal<>();
private final Set<SessionPolicy> sessionPolicy = EnumSet.of(SessionPolicy.DEFAULT);
protected ThreadLocal<SessionContext> sessionContext = new ThreadLocal<>();
public boolean getSaveOnChange() {
return this.sessionPolicy.contains(SessionPolicy.SAVE_ON_CHANGE);
}
protected SessionHandlerValve handlerValve;
private boolean getAlwaysSaveAfterRequest() {
return this.sessionPolicy.contains(SessionPolicy.ALWAYS_SAVE_AFTER_REQUEST);
}
protected Set<SessionPolicy> sessionPolicy = EnumSet.of(SessionPolicy.DEFAULT);
/** {@inheritDoc} */
@Override
public void addLifecycleListener(LifecycleListener listener) {
super.addLifecycleListener(listener);
}
private Log log = LogFactory.getLog(SessionManager.class);
/** {@inheritDoc} */
@Override
public LifecycleListener[] findLifecycleListeners() {
return super.findLifecycleListeners();
}
enum SessionPolicy {
DEFAULT, SAVE_ON_CHANGE, ALWAYS_SAVE_AFTER_REQUEST;
/** {@inheritDoc} */
@Override
public void removeLifecycleListener(LifecycleListener listener) {
super.removeLifecycleListener(listener);
}
static SessionPolicy fromName(String name) {
for (SessionPolicy policy : SessionPolicy.values()) {
if (policy.name().equalsIgnoreCase(name)) {
return policy;
}
}
throw new IllegalArgumentException("Invalid session policy [" + name + "]");
}
}
/** {@inheritDoc} */
@Override
protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
super.setState(LifecycleState.STARTING);
/**
* To get session persist policies
*
* @return
*/
public String getSessionPersistPolicies() {
String policyStr = null;
for (SessionPolicy policy : this.sessionPolicy) {
policyStr = (policyStr == null) ? policy.name() : policyStr.concat(",").concat(policy.name());
}
return policyStr;
}
boolean initializedValve = false;
Context context = getContextIns();
for (Valve valve : context.getPipeline().getValves()) {
if (valve instanceof SessionHandlerValve) {
SessionHandlerValve handlerValve = (SessionHandlerValve) valve;
handlerValve.setSessionManager(this);
initializedValve = true;
break;
}
}
/**
* To set session persist policies
*
* @param policyStr
*/
public void setSessionPersistPolicies(String policyStr) {
Set<SessionPolicy> policySet = EnumSet.of(SessionPolicy.DEFAULT);
String[] policyArray = policyStr.split(",");
if (!initializedValve) {
throw new LifecycleException("Session handling valve is not initialized..");
}
initialize();
LOGGER.info("The sessions will expire after " + (getSessionTimeout(null)) + " seconds.");
context.setDistributable(true);
}
for (String policy : policyArray) {
policySet.add(SessionPolicy.fromName(policy));
}
this.sessionPolicy = policySet;
}
/** {@inheritDoc} */
@Override
protected synchronized void stopInternal() throws LifecycleException {
super.setState(LifecycleState.STOPPING);
super.stopInternal();
}
/**
* @return
*/
public boolean getSaveOnChange() {
return this.sessionPolicy.contains(SessionPolicy.SAVE_ON_CHANGE);
}
/** {@inheritDoc} */
@Override
public Session createSession(String sessionId) {
if (sessionId != null) {
sessionId = (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L) ? null : sessionId;
} else {
do {
sessionId = generateSessionId();
} while (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L);
}
/**
* @return
*/
public boolean getAlwaysSaveAfterRequest() {
return this.sessionPolicy.contains(SessionPolicy.ALWAYS_SAVE_AFTER_REQUEST);
}
Session session = (sessionId != null) ? createEmptySession() : null;
if (session != null) {
session.setId(sessionId);
session.setNew(true);
session.setValid(true);
session.setCreationTime(System.currentTimeMillis());
session.setMaxInactiveInterval(getSessionTimeout(session));
session.tellNew();
}
setValues(sessionId, session, false, new SessionMetadata());
/** {@inheritDoc} */
@Override
public void addLifecycleListener(LifecycleListener listener) {
super.addLifecycleListener(listener);
}
if (session != null) {
try {
save(session, true);
} catch (Exception ex) {
LOGGER.error("Error occurred while creating session..", ex);
setValues(null, null);
session = null;
}
}
return session;
}
/** {@inheritDoc} */
@Override
public LifecycleListener[] findLifecycleListeners() {
return super.findLifecycleListeners();
}
/** {@inheritDoc} */
@Override
public Session createEmptySession() {
return new Session(this);
}
/** {@inheritDoc} */
@Override
public void removeLifecycleListener(LifecycleListener listener) {
super.removeLifecycleListener(listener);
}
/** {@inheritDoc} */
@Override
public void add(org.apache.catalina.Session session) {
save(session, false);
}
/** {@inheritDoc} */
@Override
protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
super.setState(LifecycleState.STARTING);
/** {@inheritDoc} */
@Override
public Session findSession(String sessionId) throws IOException {
if (sessionId != null && this.sessionContext.get() != null && sessionId.equals(this.sessionContext.get().getId())) {
return this.sessionContext.get().getSession();
}
boolean initializedValve = false;
Context context = getContextIns();
for (Valve valve : context.getPipeline().getValves()) {
if (valve instanceof SessionHandlerValve) {
this.handlerValve = (SessionHandlerValve) valve;
this.handlerValve.setSessionManager(this);
initializedValve = true;
break;
}
}
Session session = null;
boolean isPersisted = false;
SessionMetadata metadata = null;
if (!initializedValve)
throw new LifecycleException("Session handling valve is not initialized..");
byte[] data = this.dataCache.get(sessionId);
if (data == null) {
sessionId = null;
isPersisted = false;
} else {
if (Arrays.equals(SessionConstants.NULL_SESSION, data)) {
throw new IOException("NULL session data");
}
try {
metadata = new SessionMetadata();
Session newSession = createEmptySession();
this.serializer.deserializeSessionData(data, newSession, metadata);
initialize();
newSession.setId(sessionId);
newSession.access();
newSession.setNew(false);
newSession.setValid(true);
newSession.resetDirtyTracking();
newSession.setMaxInactiveInterval(getSessionTimeout(newSession));
log.info("The sessions will expire after " + (getSessionTimeout(null)) + " seconds.");
context.setDistributable(true);
}
session = newSession;
isPersisted = true;
} catch (Exception ex) {
LOGGER.error("Error occurred while de-serializing the session object..", ex);
}
}
setValues(sessionId, session, isPersisted, metadata);
return session;
}
/** {@inheritDoc} */
@Override
protected synchronized void stopInternal() throws LifecycleException {
super.setState(LifecycleState.STOPPING);
super.stopInternal();
}
/** {@inheritDoc} */
@Override
public void remove(org.apache.catalina.Session session) {
remove(session, false);
}
/** {@inheritDoc} */
@Override
public Session createSession(String sessionId) {
if (sessionId != null) {
sessionId = (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L) ? null : sessionId;
} else {
do {
sessionId = generateSessionId();
} while (this.dataCache.setnx(sessionId, SessionConstants.NULL_SESSION) == 0L);
}
/** {@inheritDoc} */
@Override
public void remove(org.apache.catalina.Session session, boolean update) {
this.dataCache.delete(session.getId());
}
Session session = (sessionId != null) ? (Session) createEmptySession() : null;
if (session != null) {
session.setId(sessionId);
session.setNew(true);
session.setValid(true);
session.setCreationTime(System.currentTimeMillis());
session.setMaxInactiveInterval(getSessionTimeout(session));
session.tellNew();
}
setValues(sessionId, session, false, new SessionMetadata());
/** {@inheritDoc} */
@Override
public void load() {
// Auto-generated method stub
}
if (session != null) {
try {
save(session, true);
} catch (Exception ex) {
log.error("Error occured while creating session..", ex);
setValues(null, null);
session = null;
}
}
return session;
}
/** {@inheritDoc} */
@Override
public void unload() {
// Auto-generated method stub
}
/** {@inheritDoc} */
@Override
public Session createEmptySession() {
return new Session(this);
}
/** To initialize the session manager. */
private void initialize() {
try {
Config config = ConfigUtil.getConfig();
this.ssoTimeout = config.getRedisSSOTimeout();
this.dataCache = new DataCacheFactory(config, getSessionTimeout(null)).getDataCache();
this.serializer = new SerializationUtil();
/** {@inheritDoc} */
@Override
public void add(org.apache.catalina.Session session) {
save(session, false);
}
Context context = getContextIns();
ClassLoader loader = (context != null && context.getLoader() != null) ? context.getLoader().getClassLoader() : null;
this.serializer.setClassLoader(loader);
/** {@inheritDoc} */
@Override
public Session findSession(String sessionId) throws IOException {
Session session = null;
if (sessionId != null && this.sessionContext.get() != null && sessionId.equals(this.sessionContext.get().getId())) {
session = this.sessionContext.get().getSession();
} else {
byte[] data = this.dataCache.get(sessionId);
setSessionPersistentPolicies(config);
} catch (Exception ex) {
LOGGER.error("Error occurred while initializing the session manager..", ex);
throw ex;
}
}
boolean isPersisted = false;
SessionMetadata metadata = null;
if (data == null) {
session = null;
metadata = null;
sessionId = null;
isPersisted = false;
} else {
if (Arrays.equals(SessionConstants.NULL_SESSION, data)) {
throw new IOException("NULL session data");
}
try {
metadata = new SessionMetadata();
Session newSession = (Session) createEmptySession();
this.serializer.deserializeSessionData(data, newSession, metadata);
/** To save session object to data cache. */
public void save(org.apache.catalina.Session session, boolean forceSave) {
try {
Boolean isPersisted;
Session newSession = (Session) session;
byte[] hash = (this.sessionContext.get() != null && this.sessionContext.get().getMetadata() != null)
? this.sessionContext.get().getMetadata().getAttributesHash() : null;
byte[] currentHash = this.serializer.getSessionAttributesHashCode(newSession);
newSession.setId(sessionId);
newSession.access();
newSession.setNew(false);
newSession.setValid(true);
newSession.resetDirtyTracking();
newSession.setMaxInactiveInterval(getSessionTimeout(newSession));
if (forceSave
|| newSession.isDirty()
|| (isPersisted = (this.sessionContext.get() != null) ? this.sessionContext.get().isPersisted() : null) == null
|| !isPersisted || !Arrays.equals(hash, currentHash)) {
session = newSession;
isPersisted = true;
} catch (Exception ex) {
log.error("Error occured while de-serializing the session object..", ex);
}
}
setValues(sessionId, session, isPersisted, metadata);
}
return session;
}
SessionMetadata metadata = new SessionMetadata();
metadata.setAttributesHash(currentHash);
/** {@inheritDoc} */
@Override
public void remove(org.apache.catalina.Session session) {
remove(session, false);
}
this.dataCache.set(newSession.getId(), this.serializer.serializeSessionData(newSession, metadata));
newSession.resetDirtyTracking();
setValues(true, metadata);
}
/** {@inheritDoc} */
@Override
public void remove(org.apache.catalina.Session session, boolean update) {
this.dataCache.expire(session.getId(), 10);
}
int timeout = getSessionTimeout(newSession);
this.dataCache.expire(newSession.getId(), timeout);
LOGGER.debug("Session [" + newSession.getId() + "] expire in [" + timeout + "] seconds.");
/** {@inheritDoc} */
@Override
public void load() throws ClassNotFoundException, IOException {
// Auto-generated method stub
}
} catch (IOException ex) {
LOGGER.error("Error occurred while saving the session object in data cache..", ex);
}
}
/** {@inheritDoc} */
@Override
public void unload() throws IOException {
// Auto-generated method stub
}
/** To process post request process. */
void afterRequest() {
Session session = null;
try {
session = (this.sessionContext.get() != null) ? this.sessionContext.get().getSession() : null;
if (session != null) {
if (session.isValid()) {
save(session, getAlwaysSaveAfterRequest());
} else {
remove(session);
}
LOGGER.debug("Session object " + (session.isValid() ? "saved: " : "removed: ") + session.getId());
}
} catch (Exception ex) {
LOGGER.error("Error occurred while processing post request process..", ex);
} finally {
this.sessionContext.remove();
LOGGER.debug("Session removed from ThreadLocal:" + ((session != null) ? session.getIdInternal() : ""));
}
}
/**
* To initialize the session manager
*/
private void initialize() {
try {
this.dataCache = new RedisDataCache();
/** To get session timeout. */
private int getSessionTimeout(Session session) {
int timeout = getContextIns().getSessionTimeout() * 60;
int sessionTimeout = (session == null) ? 0 : session.getMaxInactiveInterval();
return (sessionTimeout < timeout) ? (Math.max(timeout, 1800)) : sessionTimeout;
}
this.serializer = new SerializationUtil();
Context context = getContextIns();
ClassLoader loader = (context != null && context.getLoader() != null) ? context.getLoader().getClassLoader() : null;
this.serializer.setClassLoader(loader);
} catch (Exception ex) {
log.error("Error occured while initializing the session manager..", ex);
throw ex;
}
}
/** To set values to session context. */
private void setValues(String sessionId, Session session) {
if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext());
}
this.sessionContext.get().setId(sessionId);
this.sessionContext.get().setSession(session);
}
/**
* To save session object to data-cache
*
* @param session
* @param forceSave
*/
public void save(org.apache.catalina.Session session, boolean forceSave) {
try {
Boolean isPersisted;
Session newSession = (Session) session;
byte[] hash = (this.sessionContext.get() != null && this.sessionContext.get().getMetadata() != null)
? this.sessionContext.get().getMetadata().getAttributesHash() : null;
byte[] currentHash = serializer.getSessionAttributesHashCode(newSession);
/** To set values to session context. */
private void setValues(boolean isPersisted, SessionMetadata metadata) {
if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext());
}
this.sessionContext.get().setMetadata(metadata);
this.sessionContext.get().setPersisted(isPersisted);
}
if (forceSave || newSession.isDirty()
|| (isPersisted = (this.sessionContext.get() != null) ? this.sessionContext.get().isPersisted() : null) == null
|| !isPersisted || !Arrays.equals(hash, currentHash)) {
/** To set values to session context. */
private void setValues(String sessionId, Session session, boolean isPersisted, SessionMetadata metadata) {
setValues(sessionId, session);
setValues(isPersisted, metadata);
}
SessionMetadata metadata = new SessionMetadata();
metadata.setAttributesHash(currentHash);
/** To get catalina context instance. */
private Context getContextIns() {
try {
Method method = this.getClass().getSuperclass().getDeclaredMethod("getContext");
return (Context) method.invoke(this);
} catch (Exception ex) {
try {
Method method = this.getClass().getSuperclass().getDeclaredMethod("getContainer");
return (Context) method.invoke(this);
} catch (Exception ex2) {
// skip
}
}
throw new RuntimeException("Error occurred while creating container instance");
}
this.dataCache.set(newSession.getId(), serializer.serializeSessionData(newSession, metadata));
newSession.resetDirtyTracking();
setValues(true, metadata);
}
/** To set session persistent policies */
private void setSessionPersistentPolicies(Config config) {
String sessionPolicies = config.getSessionPersistentPolicies();
if (sessionPolicies == null || sessionPolicies.isEmpty()) {
return;
}
int timeout = getSessionTimeout(newSession);
this.dataCache.expire(newSession.getId(), timeout);
log.trace("Session [" + newSession.getId() + "] expire in [" + timeout + "] seconds.");
sessionPolicies = sessionPolicies.replaceAll("\\s", "");
String[] sessionPolicyNames = sessionPolicies.split(",");
for (String sessionPolicyName : sessionPolicyNames) {
this.sessionPolicy.add(SessionPolicy.fromName(sessionPolicyName));
}
}
} catch (IOException ex) {
log.error("Error occured while saving the session object in data cache..", ex);
}
}
/** To set single-sign-on entry to cache. */
void setSingleSignOnEntry(String ssoId, SingleSignOnEntry entry) {
if (entry == null) {
return;
}
try {
byte[] data = this.serializer.serializeSingleSignOnEntry(entry);
this.dataCache.set(ssoId, data);
if (this.ssoTimeout > 0) {
this.dataCache.expire(ssoId, this.ssoTimeout);
}
} catch (IOException ex) {
LOGGER.error("Error occurred while serializing the single-sign-on entry..", ex);
}
}
/**
* To process post request process
*
* @param request
*/
public void afterRequest(Request request) {
Session session = null;
try {
session = (this.sessionContext.get() != null) ? this.sessionContext.get().getSession() : null;
if (session != null) {
if (session.isValid())
save(session, getAlwaysSaveAfterRequest());
else
remove(session);
log.trace("Session object " + (session.isValid() ? "saved: " : "removed: ") + session.getId());
}
} catch (Exception ex) {
log.error("Error occured while processing post request process..", ex);
} finally {
this.sessionContext.remove();
log.trace("Session removed from ThreadLocal:" + ((session != null) ? session.getIdInternal() : ""));
}
}
/** To get single-sign-on entry from cache. */
SingleSignOnEntry getSingleSignOnEntry(String ssoId) {
byte[] data = this.dataCache.get(ssoId);
if (data == null) {
return null;
}
/**
* @return
*/
private int getSessionTimeout(Session session) {
int timeout = getContextIns().getSessionTimeout();
int sessionTimeout = (session == null) ? 0 : session.getMaxInactiveInterval();
return (sessionTimeout < timeout) ? ((timeout < 1800) ? 1800 : timeout) : sessionTimeout;
}
SingleSignOnEntry entry = new SingleSignOnEntry();
try {
this.serializer.deserializeSingleSignOnEntry(data, entry);
} catch (IOException | ClassNotFoundException ex) {
LOGGER.error("Error occurred while de-serializing the single-sign-on entry..", ex);
return null;
}
return entry;
}
/**
* @param sessionId
* @param session
*/
private void setValues(String sessionId, Session session) {
if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext());
}
this.sessionContext.get().setId(sessionId);
this.sessionContext.get().setSession(session);
}
/** To check single-sign-on entry exists from cache. */
Boolean singleSignOnEntryExists(String ssoId) {
return this.dataCache.exists(ssoId);
}
/**
* @param isPersisted
* @param metadata
*/
private void setValues(boolean isPersisted, SessionMetadata metadata) {
if (this.sessionContext.get() == null) {
this.sessionContext.set(new SessionContext());
}
this.sessionContext.get().setMetadata(metadata);
this.sessionContext.get().setPersisted(isPersisted);
}
/**
* @param sessionId
* @param session
* @param isPersisted
* @param metadata
*/
private void setValues(String sessionId, Session session, boolean isPersisted, SessionMetadata metadata) {
setValues(sessionId, session);
setValues(isPersisted, metadata);
}
/**
* @return
*/
private Context getContextIns() {
try {
Method method = this.getClass().getSuperclass().getDeclaredMethod("getContext");
return (Context) method.invoke(this);
} catch (Exception ex) {
try {
Method method = this.getClass().getSuperclass().getDeclaredMethod("getContainer");
return (Context) method.invoke(this);
} catch (Exception ex2) {
log.error("Error in getContext", ex2);
}
}
return null;
}
/** To delete single-sign-on entry from cache. */
void deleteSingleSignOnEntry(String ssoId) {
this.dataCache.delete(ssoId);
}
}

View File

@ -0,0 +1,263 @@
package tomcat.request.session.redis;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Manager;
import org.apache.catalina.Realm;
import org.apache.catalina.Session;
import org.apache.catalina.authenticator.Constants;
import org.apache.catalina.authenticator.SingleSignOn;
import org.apache.catalina.authenticator.SingleSignOnSessionKey;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tomcat.request.session.exception.BackendException;
import tomcat.request.session.model.SingleSignOnEntry;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.security.Principal;
import java.util.Set;
/** author: Ranjith Manickam @ 20 Mar' 2020 */
public class SingleSignOnValve extends SingleSignOn {
private static final Logger LOGGER = LoggerFactory.getLogger(SingleSignOnValve.class);
private Engine engine;
private SessionManager manager;
/** {@inheritDoc} */
@Override
protected synchronized void startInternal() throws LifecycleException {
Container c;
for (c = this.getContainer(); c != null && !(c instanceof Engine); c = c.getParent()) {
}
if (c instanceof Engine) {
this.engine = (Engine) c;
}
super.startInternal();
}
/** {@inheritDoc} */
@Override
public void invoke(Request request, Response response) throws BackendException {
try {
this.setSessionManager(request.getContext().getManager());
request.removeNote("org.apache.catalina.request.SSOID");
LOGGER.debug("singleSignOn.debug.invoke, requestURI: {}", request.getRequestURI());
if (request.getUserPrincipal() == null) {
LOGGER.debug("singleSignOn.debug.cookieCheck");
Cookie cookie = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie value : cookies) {
if (Constants.SINGLE_SIGN_ON_COOKIE.equals(value.getName())) {
cookie = value;
break;
}
}
}
if (cookie == null) {
LOGGER.debug("singleSignOn.debug.cookieNotFound");
} else {
LOGGER.debug("singleSignOn.debug.principalCheck, ssoId: {}", cookie.getValue());
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(cookie.getValue());
if (entry == null) {
LOGGER.debug("singleSignOn.debug.principalNotFound, ssoId: {}", cookie.getValue());
cookie.setValue("REMOVE");
cookie.setMaxAge(0);
cookie.setPath("/");
String domain = this.getCookieDomain();
if (domain != null) {
cookie.setDomain(domain);
}
cookie.setSecure(request.isSecure());
if (request.getServletContext().getSessionCookieConfig().isHttpOnly() || request.getContext().getUseHttpOnly()) {
cookie.setHttpOnly(true);
}
response.addCookie(cookie);
} else {
LOGGER.debug("singleSignOn.debug.principalFound, principal: {}, authType: {}", (entry.getPrincipal() != null ? entry.getPrincipal().getName() : ""), entry.getAuthType());
request.setNote("org.apache.catalina.request.SSOID", cookie.getValue());
if (!this.getRequireReauthentication()) {
request.setAuthType(entry.getAuthType());
request.setUserPrincipal(entry.getPrincipal());
}
}
}
} else {
LOGGER.debug("singleSignOn.debug.hasPrincipal, principal: {}", request.getUserPrincipal().getName());
}
this.getNext().invoke(request, response);
} catch (IOException | ServletException | RuntimeException ex) {
LOGGER.error("Error processing request", ex);
throw new BackendException();
}
}
/** {@inheritDoc} */
@Override
public void sessionDestroyed(String ssoId, Session session) {
if (this.getState().isAvailable()) {
if ((session.getMaxInactiveInterval() <= 0 ||
session.getIdleTimeInternal() < (long) (session.getMaxInactiveInterval() * 1000))
&& session.getManager().getContext().getState().isAvailable()) {
LOGGER.debug("singleSignOn.debug.sessionLogout, session: {}", session);
this.removeSession(ssoId, session);
if (this.manager.singleSignOnEntryExists(ssoId)) {
this.deregister(ssoId);
}
return;
}
LOGGER.debug("singleSignOn.debug.sessionTimeout, ssoId: {}, session: {}", ssoId, session);
this.removeSession(ssoId, session);
}
}
/** {@inheritDoc} */
@Override
protected boolean associate(String ssoId, Session session) {
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(ssoId);
if (entry == null) {
LOGGER.debug("singleSignOn.debug.associateFail, ssoId: {}, session: {}", ssoId, session);
return false;
}
LOGGER.debug("singleSignOn.debug.associate, ssoId: {}, session: {}", ssoId, session);
entry.addSession(ssoId, session);
this.manager.setSingleSignOnEntry(ssoId, entry);
return true;
}
/** {@inheritDoc} */
@Override
protected void deregister(String ssoId) {
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(ssoId);
this.manager.deleteSingleSignOnEntry(ssoId);
if (entry == null) {
LOGGER.debug("singleSignOn.debug.deregisterFail, ssoId: {}", ssoId);
return;
}
Set<SingleSignOnSessionKey> ssoKeys = entry.findSessions();
if (ssoKeys.isEmpty()) {
LOGGER.debug("singleSignOn.debug.deregisterNone, ssoId: {}", ssoId);
}
for (SingleSignOnSessionKey ssoKey : ssoKeys) {
this.expire(ssoKey);
LOGGER.debug("singleSignOn.debug.deregister, ssoKey: {}, ssoId: {}", ssoKey, ssoId);
}
}
/** {@inheritDoc} */
@Override
protected boolean reauthenticate(String ssoId, Realm realm, Request request) {
if (ssoId == null || realm == null) {
return false;
}
boolean reAuthenticated = false;
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(ssoId);
if (entry != null && entry.getCanReauthenticate()) {
String username = entry.getUsername();
if (username != null) {
Principal reAuthPrincipal = realm.authenticate(username, entry.getPassword());
if (reAuthPrincipal != null) {
reAuthenticated = true;
request.setAuthType(entry.getAuthType());
request.setUserPrincipal(reAuthPrincipal);
}
}
}
return reAuthenticated;
}
/** {@inheritDoc} */
@Override
protected void register(String ssoId, Principal principal, String authType, String username, String password) {
LOGGER.debug("singleSignOn.debug.register, ssoId: {}, principal: {}, authType: {}", ssoId, (principal != null ? principal.getName() : ""), authType);
SingleSignOnEntry entry = new SingleSignOnEntry(principal, authType, username, password);
this.manager.setSingleSignOnEntry(ssoId, entry);
}
/** {@inheritDoc} */
@Override
protected boolean update(String ssoId, Principal principal, String authType, String username, String password) {
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(ssoId);
if (entry == null || !entry.getCanReauthenticate()) {
return false;
}
LOGGER.debug("singleSignOn.debug.update, ssoId: {}, authType: {}", ssoId, authType);
entry.updateCredentials(principal, authType, username, password);
this.manager.setSingleSignOnEntry(ssoId, entry);
return true;
}
/** {@inheritDoc} */
@Override
protected void removeSession(String ssoId, Session session) {
LOGGER.debug("singleSignOn.debug.removeSession, ssoId: {}, session: {}", ssoId, session);
SingleSignOnEntry entry = this.manager.getSingleSignOnEntry(ssoId);
if (entry != null) {
entry.removeSession(session);
if (entry.findSessions().size() == 0) {
this.deregister(ssoId);
}
}
}
/** To set session manager. */
void setSessionManager(Manager manager) {
if (manager != null) {
this.manager = (SessionManager) manager;
}
}
/** To expire session. */
private void expire(SingleSignOnSessionKey key) {
if (this.engine == null) {
LOGGER.warn("singleSignOn.sessionExpire.engineNull, key: {}", key);
} else {
Container host = this.engine.findChild(key.getHostName());
if (host == null) {
LOGGER.warn("singleSignOn.sessionExpire.hostNotFound, key: {}", key);
} else {
Context context = (Context) host.findChild(key.getContextName());
if (context == null) {
LOGGER.warn("singleSignOn.sessionExpire.contextNotFound, key: {}", key);
} else {
Session session;
try {
session = this.manager.findSession(key.getSessionId());
} catch (IOException ex) {
LOGGER.warn("singleSignOn.sessionExpire.managerError, key: {}, exception: {}", key, ex);
return;
}
if (session == null) {
LOGGER.warn("singleSignOn.sessionExpire.sessionNotFound, key: {}", key);
} else {
session.expire();
}
}
}
}
}
}

View File

@ -0,0 +1,154 @@
package tomcat.request.session.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tomcat.request.session.annotation.Property;
import tomcat.request.session.model.Config;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Properties;
/** author: Ranjith Manickam @ 5 Feb' 2020 */
public class ConfigUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigUtil.class);
private static final String CONF = "conf";
private static final String CATALINA_BASE = "catalina.base";
/** To get application config. */
public static Config getConfig() {
Properties properties = getApplicationProperties();
Config config = new Config();
for (Field field : Config.class.getDeclaredFields()) {
Property property = field.getAnnotation(Property.class);
if (property == null) {
continue;
}
String propertyName = property.name();
Property.PropertyType propertyType = property.type();
if (propertyName.isEmpty()) {
continue;
}
String value = properties.getProperty(propertyName);
if (isSystemProperty(value)) {
value = getSystemProperty(value);
}
if (value == null || value.isEmpty()) {
value = property.defaultValue();
if (value.isEmpty()) {
continue;
}
}
field.setAccessible(true);
try {
switch (propertyType) {
case BOOLEAN:
field.set(config, Boolean.parseBoolean(value));
break;
case INTEGER:
field.set(config, Integer.parseInt(value));
break;
case LONG:
field.set(config, Long.parseLong(value));
break;
case STRING:
default:
field.set(config, value);
break;
}
} catch (Exception ex) {
LOGGER.error("Error while initializing application properties", ex);
}
}
return config;
}
/** To get redis data cache properties. */
private static Properties getApplicationProperties() {
Properties properties = new Properties();
try {
String filePath = System.getProperty(CATALINA_BASE)
.concat(File.separator)
.concat(CONF).concat(File.separator)
.concat(Config.APPLICATION_PROPERTIES_FILE);
InputStream resourceStream = null;
try {
resourceStream = (!filePath.isEmpty() && new File(filePath).exists()) ? new FileInputStream(filePath) : null;
if (resourceStream == null) {
LOGGER.info("Initializing tomcat redis session manager with default properties");
ClassLoader loader = Thread.currentThread().getContextClassLoader();
resourceStream = loader.getResourceAsStream(Config.APPLICATION_PROPERTIES_FILE);
}
properties.load(resourceStream);
} finally {
if (resourceStream != null) {
resourceStream.close();
}
}
} catch (IOException ex) {
LOGGER.error("Error while retrieving application properties", ex);
}
return properties;
}
/**
* To get property with the specified key from system property.
*
* @param key - search key.
* @return - Returns the system property value.
*/
private static String getSystemProperty(String key) {
int fromIndex = 0;
while (true) {
int beginIndex = key.indexOf("${", fromIndex);
int endIndex = key.indexOf("}", fromIndex);
if (beginIndex < 0 || endIndex < 0) {
break;
}
String expression = key.substring(beginIndex + 2, endIndex);
String value = System.getProperty(expression);
if (value == null || value.isEmpty()) {
fromIndex = endIndex + 1;
continue;
}
key = key.replace(String.format("${%s}", expression), value);
}
return key;
}
/**
* To check if the value is from system property.
*
* @param key - search key.
* @return - Returns true if the key start with '${' and ends with '}'.
*/
private static boolean isSystemProperty(String key) {
if (key == null || key.isEmpty()) {
return false;
}
int beginIndex = key.indexOf("${");
int endIndex = key.indexOf("}");
return beginIndex >= 0 && endIndex >= 0 && beginIndex < endIndex;
}
}

View File

@ -0,0 +1,101 @@
package tomcat.request.session.util;
import org.apache.catalina.util.CustomObjectInputStream;
import tomcat.request.session.model.Session;
import tomcat.request.session.model.SessionMetadata;
import tomcat.request.session.model.SingleSignOnEntry;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
/** author: Ranjith Manickam @ 12 Jul' 2018 */
public class SerializationUtil {
private ClassLoader loader;
/** To set class loader. */
public void setClassLoader(ClassLoader loader) {
this.loader = loader;
}
/** To get session attributes hash code. */
public byte[] getSessionAttributesHashCode(Session session) throws IOException {
byte[] serialized;
Map<String, Object> attributes = new HashMap<>();
for (Enumeration<String> enumerator = session.getAttributeNames();
enumerator.hasMoreElements(); ) {
String key = enumerator.nextElement();
attributes.put(key, session.getAttribute(key));
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos))) {
oos.writeUnshared(attributes);
oos.flush();
serialized = bos.toByteArray();
}
MessageDigest digester;
try {
digester = MessageDigest.getInstance("MD5");
} catch (Exception ex) {
throw new RuntimeException("Unable to get MessageDigest instance for MD5", ex);
}
return digester.digest(serialized);
}
/** To serialize session object. */
public byte[] serializeSessionData(Session session, SessionMetadata metadata) throws IOException {
byte[] serialized;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos))) {
oos.writeObject(metadata);
session.writeObjectData(oos);
oos.flush();
serialized = bos.toByteArray();
}
return serialized;
}
/** To de-serialize session object. */
public void deserializeSessionData(byte[] data, Session session, SessionMetadata metadata)
throws IOException, ClassNotFoundException {
try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));
ObjectInputStream ois = new CustomObjectInputStream(bis, this.loader)) {
SessionMetadata serializedMetadata = (SessionMetadata) ois.readObject();
metadata.copyFieldsFrom(serializedMetadata);
session.readObjectData(ois);
}
}
/** To serialize single-sign-on entry. */
public byte[] serializeSingleSignOnEntry(SingleSignOnEntry entry) throws IOException {
byte[] serialized;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos))) {
entry.writeObjectData(oos);
oos.flush();
serialized = bos.toByteArray();
}
return serialized;
}
/** To de-serialize single-sign-on entry. */
public void deserializeSingleSignOnEntry(byte[] data, SingleSignOnEntry entry)
throws IOException, ClassNotFoundException {
try (BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(data));
ObjectInputStream ois = new CustomObjectInputStream(bis, this.loader)) {
entry.readObjectData(ois);
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

View File

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="download_summary"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "https://api.github.com/repos/ran-jit/tomcat-cluster-redis-session-manager/releases",
success: function(data){
let content = "<table border='1px' style='width: 80%;margin-left: 10%;margin-right: 10%;line-height: 1.5;'><tr><th style='width: 30%;'>tag</th><th>asset name & download count</th></tr>";
for(let i=0; i< data.data.length; i++) {
const tag = data.data[i];
for(var j=0; j< tag.assets.length; j++) {
const asset = tag.assets[j];
content = content + "<tr><td style='width: 10%;'>"+ tag.tag_name + "</td>";
content = content + "<td>" + asset.name + "<div style='text-align:right;'>" + asset.download_count + "</div></td></tr>";
}
}
content = content + "</table>";
document.getElementById("download_summary").innerHTML=content;
}
});
});
</script>
</body>
</html>

View File

@ -1,15 +1,13 @@
/**
* Tomcat clustering with Redis data-cache implementation.
*
* Tomcat clustering with Redis is the plugable one. It uses to store session objects to Redis data cache.
*
* @author Ranjith Manickam
* @since 2.0
* author: Ranjith Manickam @ 12 Jul' 2018
*/
Supports:
* Apache Tomcat 7
* Apache Tomcat 8
- Apache Tomcat 7
- Apache Tomcat 8
- Apache Tomcat 9
Pre-requisite:
1. jedis.jar
@ -20,13 +18,13 @@ more details.. https://github.com/ran-jit/tomcat-cluster-redis-session-manager/w
Steps to be done,
1. Move the downloaded jars to tomcat/lib directory
* tomcat/lib/
- tomcat/lib/
2. Add tomcat system property "catalina.base"
* catalina.base="TOMCAT_LOCATION"
- catalina.base="TOMCAT_LOCATION"
3. Extract downloaded package (tomcat-cluster-redis-session-manager.zip) to configure Redis credentials in redis-data-cache.properties file and move the file to tomcat/conf directory
* tomcat/conf/redis-data-cache.properties
- tomcat/conf/redis-data-cache.properties
4. Add the below two lines in tomcat/conf/context.xml
<Valve className="tomcat.request.session.redis.SessionHandlerValve" />
@ -38,4 +36,5 @@ Steps to be done,
<session-config>
Note:
* This supports, both redis stand-alone and multiple node cluster based on the redis-data-cache.properties configuration.
- All your session attribute values must implement java.io.Serializable.
- Supports redis default, sentinel and cluster based on the redis-data-cache.properties configuration.

View File

@ -1,16 +1,39 @@
#-- Redis data-cache configuration
#- redis hosts ex: 127.0.0.1:6379, 127.0.0.2:6379, 127.0.0.2:6380, ....
# - ${ENV_VARIABLE_NAME}
#- redis hosts. ex: 127.0.0.1:6379, 127.0.0.2:6379, 127.0.0.2:6380, ....
redis.hosts=127.0.0.1:6379
#- redis password (for stand-alone mode)
#- redis password.
#redis.password=
#- set true to enable redis cluster mode
#- set true to enable redis cluster mode. (default value: false)
redis.cluster.enabled=false
#- redis database (default 0)
#- set true to enable redis sentinel mode. (default value: false)
redis.sentinel.enabled=false
# redis sentinel master name. (default value: mymaster)
redis.sentinel.master=mymaster
#- redis database. (default value: 0)
#redis.database=0
#- redis connection timeout (default 2000)
#- redis connection timeout. (default value: 2000 ms)
#redis.timeout=2000
#- enable redis and standard session mode. (default value: false)
# If enabled,
# 1. Must be enabled sticky session in your load balancer configuration. Else this manager may not return the updated session values.
# 2. Session values are stored in local jvm and redis.
# 3. If redis is down/not responding, requests uses jvm stored session values to process user requests. Redis comes back the values will be synced.
lb.sticky-session.enabled=false
#- session persistent policies. (default value: DEFAULT) ex: DEFAULT, SAVE_ON_CHANGE
# policies - DEFAULT, SAVE_ON_CHANGE, ALWAYS_SAVE_AFTER_REQUEST
# 1. SAVE_ON_CHANGE: every time session.setAttribute() or session.removeAttribute() is called the session will be saved.
# 2. ALWAYS_SAVE_AFTER_REQUEST: force saving after every request, regardless of whether or not the manager has detected changes to the session.
session.persistent.policies=DEFAULT
#- single-sign-on session timeout. (default value: 0 ms (-no expiry))
redis.sso.timeout=0