\n");
exit(EXIT_FAILURE);
}
setuid(0);
if(strcmp(argv[1], "-u") == 0) {
chmod("/mnt/dmg", 0755);
do_umount();
} else {
if(do_mount(argv[1]) == 0)
chmod("/mnt/dmg", 0777);
}
exit(EXIT_SUCCESS);
}
static int
do_mount(char *path)
{
pid_t pid;
if((pid = fork()) == -1) {
fprintf(stderr, "fork() failed\n");
exit(EXIT_FAILURE);
}
if(pid == 0) {
exec_mount(path);
return -1;
}
else {
return wait_status(pid);
}
}
static int
do_umount()
{
pid_t pid;
if((pid = fork()) == -1) {
fprintf(stderr, "fork() failed\n");
exit(EXIT_FAILURE);
}
if(pid == 0) {
exec_umount();
return -1;
}
else {
return wait_status(pid);
}
}
static void
exec_mount(char *path)
{
char *args[6];
char *env[] = {NULL};
args[0] = "/bin/mount";
args[1] = "-o";
args[2] = "loop,nosuid";
args[3] = path;
args[4] = "/mnt/dmg";
args[5] = NULL;
execve("/bin/mount", args, env);
}
static void
exec_umount()
{
char *args[3];
char *env[] = {NULL};
args[0] = "/bin/umount";
args[1] = "/mnt/dmg";
args[2] = NULL;
execve("/bin/umount", args, env);
}
static int
wait_status(pid_t pid)
{
int status;
if(waitpid(pid, &status, 0) == -1) {
fprintf(stderr, "waitpid() failed.");
exit(EXIT_FAILURE);
}
if(WIFEXITED(status))
return(status);
return -1;
}
================================================
FILE: build/dist-tools/nsis/epl.txt
================================================
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
"Contributor" means any person or entity that distributes the Program.
"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance with this Agreement.
"Recipient" means anyone who receives the Program under this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program.
d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
a) it complies with the terms and conditions of this Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each copy of the Program.
Contributors may not remove or alter any copyright notices contained within the Program.
Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
================================================
FILE: build/dist-tools/nsis/vega.nsi
================================================
; Script generated by the HM NIS Edit Script Wizard.
; HM NIS Edit Wizard helper defines
!define PRODUCT_NAME "Vega"
!define PRODUCT_VERSION "1.0"
!define PRODUCT_PUBLISHER "Subgraph"
!define PRODUCT_WEB_SITE "http://www.subgraph.com"
!define PRODUCT_DIR_REGKEY "Software\Microsoft\Windows\CurrentVersion\App Paths\Vega.exe"
!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"
!define PRODUCT_UNINST_ROOT_KEY "HKLM"
; MUI 1.67 compatible ------
!include "MUI.nsh"
; MUI Settings
!define MUI_ABORTWARNING
!define MUI_ICON "${NSISDIR}/Contrib/Graphics/Icons/modern-install.ico"
!define MUI_UNICON "${NSISDIR}/Contrib/Graphics/Icons/modern-uninstall.ico"
; Welcome page
!insertmacro MUI_PAGE_WELCOME
; License page
!insertmacro MUI_PAGE_LICENSE "epl.txt"
; Directory page
!insertmacro MUI_PAGE_DIRECTORY
; Instfiles page
!insertmacro MUI_PAGE_INSTFILES
; Finish page
!define MUI_FINISHPAGE_RUN "$INSTDIR\Vega.exe"
!insertmacro MUI_PAGE_FINISH
; Uninstaller pages
!insertmacro MUI_UNPAGE_INSTFILES
; Language files
!insertmacro MUI_LANGUAGE "English"
; MUI end ------
Name "${PRODUCT_NAME} ${PRODUCT_VERSION}"
OutFile "VegaSetup.exe"
InstallDir "$PROGRAMFILES\Vega"
InstallDirRegKey HKLM "${PRODUCT_DIR_REGKEY}" ""
ShowInstDetails show
ShowUnInstDetails show
Section "MainSection" SEC01
SetOutPath "$INSTDIR"
SetOverwrite try
File "vega/.eclipseproduct"
SetOutPath "$INSTDIR\configuration"
File "vega/configuration/config.ini"
SetOutPath "$INSTDIR\configuration\org.eclipse.equinox.simpleconfigurator"
File "vega/configuration/org.eclipse.equinox.simpleconfigurator/bundles.info"
SetOutPath "$INSTDIR\features"
File /r "vega/features/*.*"
SetOutPath "$INSTDIR\plugins"
File /r "vega/plugins/*.*"
SetOutPath "$INSTDIR\scripts"
File "vega/scripts/.project"
SetOutPath "$INSTDIR\scripts\.settings"
File "vega/scripts/.settings/.jsdtscope"
File "vega/scripts/.settings/org.eclipse.wst.jsdt.ui.superType.container"
File "vega/scripts/.settings/org.eclipse.wst.jsdt.ui.superType.name"
SetOutPath "$INSTDIR\scripts\scanner\modules\injection"
File "vega/scripts/scanner/modules/injection/*.js"
SetOutPath "$INSTDIR\scripts\scanner\modules\response"
File "vega/scripts/scanner/modules/response/*.js"
SetOutPath "$INSTDIR\scripts\scanner\prelude"
File "vega/scripts/scanner/prelude/jquery.js"
SetOutPath "$INSTDIR\templates"
File "vega/templates/*.*"
SetOutPath "$INSTDIR"
File "vega/Vega.exe"
CreateDirectory "$SMPROGRAMS\Vega"
CreateShortCut "$SMPROGRAMS\Vega\Vega.lnk" "$INSTDIR\Vega.exe"
CreateShortCut "$DESKTOP\Vega.lnk" "$INSTDIR\Vega.exe"
File "vega/Vega.ini"
SetOutPath "$INSTDIR\xml\alerts"
File "vega/xml/alerts/*.xml"
SectionEnd
Section -AdditionalIcons
SetOutPath $INSTDIR
WriteIniStr "$INSTDIR\${PRODUCT_NAME}.url" "InternetShortcut" "URL" "${PRODUCT_WEB_SITE}"
CreateShortCut "$SMPROGRAMS\Vega\Website.lnk" "$INSTDIR\${PRODUCT_NAME}.url"
CreateShortCut "$SMPROGRAMS\Vega\Uninstall.lnk" "$INSTDIR\uninst.exe"
SectionEnd
Section -Post
WriteUninstaller "$INSTDIR\uninst.exe"
WriteRegStr HKLM "${PRODUCT_DIR_REGKEY}" "" "$INSTDIR\Vega.exe"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayName" "$(^Name)"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\uninst.exe"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\Vega.exe"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "URLInfoAbout" "${PRODUCT_WEB_SITE}"
WriteRegStr ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}"
SectionEnd
Function un.onUninstSuccess
HideWindow
MessageBox MB_ICONINFORMATION|MB_OK "$(^Name) was successfully removed from your computer."
FunctionEnd
Function un.onInit
MessageBox MB_ICONQUESTION|MB_YESNO|MB_DEFBUTTON2 "Are you sure you want to completely remove $(^Name) and all of its components?" IDYES +2
Abort
FunctionEnd
Section Uninstall
Delete "$SMPROGRAMS\Vega\Uninstall.lnk"
Delete "$SMPROGRAMS\Vega\Website.lnk"
Delete "$DESKTOP\Vega.lnk"
Delete "$SMPROGRAMS\Vega\Vega.lnk"
RMDir "$SMPROGRAMS\Vega"
RMDir /r "$INSTDIR"
DeleteRegKey ${PRODUCT_UNINST_ROOT_KEY} "${PRODUCT_UNINST_KEY}"
DeleteRegKey HKLM "${PRODUCT_DIR_REGKEY}"
SetAutoClose true
SectionEnd
================================================
FILE: build/dist-tools/nsis/win-x86.ini
================================================
-vmargs
-Xms256m
-XX:PermSize=128m
-XX:MaxPermSize=256m
-Xmx1024m
================================================
FILE: build/dist-tools/nsis/win-x86_64.ini
================================================
-vmargs
-Xms256m
-XX:PermSize=128m
-XX:MaxPermSize=256m
-Xmx2048m
================================================
FILE: build/dist-tools/nsis/windows-dist.sh
================================================
#!/bin/sh
TARGET=build/tmp/dist-windows
make_dist() {
ARCH=$1
VEGA=build/stage/I.VegaBuild/VegaBuild-win32.win32.$ARCH.zip
rm -rf $TARGET
mkdir -p $TARGET
/usr/bin/unzip -d $TARGET $VEGA
cp build/dist-tools/nsis/win-$ARCH.ini $TARGET/vega/Vega.ini
cp build/dist-tools/nsis/epl.txt $TARGET
cp build/dist-tools/nsis/vega.nsi $TARGET
/usr/local/bin/makensis $TARGET/vega.nsi
}
mkdir build/dist
make_dist x86
mv $TARGET/VegaSetup.exe build/dist/VegaSetup32.exe
make_dist x86_64
mv $TARGET/VegaSetup.exe build/dist/VegaSetup64.exe
================================================
FILE: build/dist-tools/osx/osx-dist.sh
================================================
#!/bin/bash
TARGET=build/tmp/dist-osx
make_dist() {
echo "enter make_dist()"
ARCH=$1
VEGA=build/stage/I.VegaBuild/VegaBuild-macosx.cocoa.$ARCH.zip
rm -rf $TARGET
mkdir -p $TARGET
echo "Target is $TARGET"
echo "Vega is $VEGA"
/usr/bin/unzip -d $TARGET $VEGA
LAUNCHER=$(ls $TARGET/vega/plugins/org.eclipse.equinox.launcher*.jar)
LAUNCHER_LIB=$(ls -d $TARGET/vega/plugins/org.eclipse.equinox.launcher.cocoa*)
cat > $TARGET/Vega.ini <<- EOF
-startup
../Resources/plugins/$(basename $LAUNCHER)
--launcher.library
../Resources/plugins/$(basename $LAUNCHER_LIB)
$(cat $TARGET/vega/Vega.app/Contents/MacOS/Vega.ini)
EOF
RESOURCES=$TARGET/vega/Vega.app/Contents/Resources
mv $TARGET/vega/plugins $RESOURCES
mv $TARGET/vega/features $RESOURCES
mv $TARGET/vega/configuration $RESOURCES
mv $TARGET/vega/scripts $RESOURCES
mv $TARGET/vega/xml $RESOURCES
mv $TARGET/vega/templates $RESOURCES
mv $TARGET/Vega.ini $TARGET/vega/Vega.app/Contents/MacOS/Vega.ini
}
make_dmg() {
echo "enter make_dmg()"
dd if=/dev/zero of=$TARGET/vega.dmg bs=1M count=40
mkfs.hfsplus -v Vega $TARGET/vega.dmg
/usr/local/bin/mount-dmg $TARGET/vega.dmg
mv $TARGET/vega/Vega.app /mnt/dmg
/usr/local/bin/mount-dmg -u
}
mkdir build/dist
make_dist x86
make_dmg
mv $TARGET/vega.dmg build/dist/Vega.dmg
make_dist x86_64
make_dmg
mv $TARGET/vega.dmg build/dist/Vega64.dmg
#rm -rf build/tmp
================================================
FILE: build.xml
================================================
================================================
FILE: dependencies/hc/README.txt
================================================
How to build OSGi compatible HttpComponents bundles for Vega.
(
1) Download the latest versions of the source packages:
httpcomponents-client-4.2.2-src.tar.gz
httpcomponents-core-4.2.3-src.tar.gz
2) Unpack both archives.
3) Patch httpclient file:
httpclient/src/main/java/org/apache/http/impl/client/DefaultRequestDirector
Change method wrapRequest() from private to protected:
DefaultRequestDirector#wrapRequest(HttpRequest request)
4) Build both packages with the command 'mvn package'
5) Build artifacts can be found in
httpcomponents-client-4.2.2/httpclient/target
httpcomponents-core-4.2.3/httpcore/target
6) Copy the following 4 jar files into the lib/ directory:
From httpcomponents-client-4.2.2/httpclient/target
httpclient-4.2.2.jar
httpclient-4.2.2-sources.jar
From httpcomponents-core-4.2.3/httpcore/target
httpcore-4.2.3-sources.jar
httpcore-4.2.3.jar
7) Run 'ant', generated jars appear in output/ directory
org.apache.http.client_4.2.2.vega.jar
org.apache.http.core_4.2.3.vega.jar
org.apache.http.client.source_4.2.2.vega.jar
org.apache.http.core.source_4.2.3.vega.jar
8) Move all of these to
Vega/platform/com.subgraph.vega.application/extra-bundles
Delete the bundles which are begin upgraded
9) possibly change feature.xml, reset target platform, etc...
================================================
FILE: dependencies/hc/build.xml
================================================
================================================
FILE: dependencies/hc/libs/README.txt
================================================
Place these 4 jar files here:
httpclient-4.2.2.jar
httpclient-4.2.2-sources.jar
httpcore-4.2.3.jar
httpcore-4.2.3-sources.jar
================================================
FILE: dependencies/hc/org.apache.http.client.bnd
================================================
-classpath libs/httpclient-4.2.2.jar
-output org.apache.http.client_4.2.2.vega.jar
Export-Package: *
Bundle-Name: org.apache.http.client
Bundle-SymbolicName: org.apache.http.client
Bundle-Version: 4.2.2
Import-Package: *;resolution:=optional
================================================
FILE: dependencies/hc/org.apache.http.client.source.bnd
================================================
Include-Resource: @libs/httpclient-4.2.2-sources.jar
-output org.apache.http.client.source_4.2.2.vega.jar
-classpath libs/httpclient-4.2.2-sources.jar
Bundle-Version: 4.2.2
Eclipse-SourceBundle: org.apache.http.client;version=4.2.2;roots:="."
Private-Package: *
================================================
FILE: dependencies/hc/org.apache.http.core.bnd
================================================
-classpath libs/httpcore-4.2.3.jar
-output org.apache.http.core_4.2.3.vega.jar
Bundle-Name: org.apache.http.core
Bundle-SymbolicName: org.apache.http.core
Export-Package: *
Bundle-Version: 4.2.3
Import-Package: *;resolution:=optional
================================================
FILE: dependencies/hc/org.apache.http.core.source.bnd
================================================
Include-Resource: @libs/httpcore-4.2.3-sources.jar
-output org.apache.http.core.source_4.2.3.vega.jar
-classpath libs/httpcore-4.2.3-sources.jar
Bundle-Version: 4.2.3
Eclipse-SourceBundle: org.apache.http.core;version=4.2.3;roots:="."
Private-Package: *
================================================
FILE: dependencies/hc/output/README.txt
================================================
After processing the output bundles will be placed in this directory.
================================================
FILE: licenses/MPL2.0.txt
================================================
The majority of Rhino is licensed under the MPL 2.0:
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
================================================
FILE: licenses/db4o-dOCL.txt
================================================
============================================================
Notices for file(s):
/Vega/platform/com.subgraph.vega.model/lib/db4o-8.0.249.16098-all-java5.jar
Vega uses db4o under the dOCL.
http://community.versant.com/Blogs/db4o/tabid/197/entryid/1044/Default.aspx
License text from http://www.versant.com/products/New_db4o/Open_Source_Licensing/dOCL.aspx
------------------------------------------------------------
db4o Free/Libre and Open Source Compatibility Software License Agreement (dOCL)
December 2006
PLEASE READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY BEFORE DOWNLOADING, INSTALLING, DISTRIBUTING, LICENSING, OR USING THE SOFTWARE (DEFINED BELOW). THE TERMS AND CONDITIONS OF THIS SOFTWARE LICENSE AGREEMENT ("AGREEMENT") GOVERN USE OF THE SOFTWARE UNLESS YOU AND DB4OBJECTS, INC. ("DB4OBJECTS") HAVE EXECUTED A SEPARATE AGREEMENT.
Versant licenses the Software (as defined in Section 1) pursuant to (1) this Agreement, (2) a commercial, royalty-based license agreement, and (3) the GNU General Public License v2.0 ("GPL"). You may choose to license the Software pursuant to any of the three agreements. Except for any software or other code licensed pursuant to the free/libre and open source software ("FLOSS") licenses set forth in Section 4, where your software is a Derivative Work (defined below) of the Software, this Agreement requires you to distribute and license your software pursuant to the GPL.
In order for this Agreement to become effective, you must register your software. Register your software by sending an email to community@db4o.com. Please provide your email address or developer website username and your software title. There, you will be asked to provide a short description of your software, release notes, and a link to all versions of your software in binary and/or source code form, whichever is required by the applicable FLOSS license.
1. Subject
"Software" means the current version of the db4o database engine software and all patches, bug fixes, error corrections and future versions. Software does not mean add-on packages which are not part of the db4o database engine such as Hibernate or Bloat, which you would license directly from their respective vendors.
2. Redistribution License
Subject to your compliance with the terms and conditions of this Agreement, Versant grants you a non-exclusive and non-transferable license to:
a. create a Derivative Work (defined below) of the Software by combining it with your software (thereby creating a "FLOSS Application");
b. sublicense to your end users perpetually, pursuant to the terms of the GPL, those portions of the Software or your FLOSS Application that were not licensed pursuant to a FLOSS License prior to your accepting this Agreement; and
c. download, install, distribute, license, and use updates of the Software on these same terms and conditions.
You may obtain copies of the Software by download from the Versant website. Software governed by this Agreement and Software governed by the GPL are obtained from the same source. For this reason, portions of the Software may be flagged as governed by the GPL license. However, the terms under which Versant licenses the Software to you depend on your choice of license, regardless of any GPL notices contained in the Software.
3. Derivative Works
For the purpose of this Agreement, software is deemed a derivative work of the Software ("Derivative Work") where it is based on the Software, including without limitation in the following circumstances:
a. the software is compiled against the Software;
b. the software contains specific references to the Software;
c. the software requires the Software to work; or
d. the software uses the proprietary API to the Software.
4. Free/Libre and Open Source Software Licenses
Where your FLOSS Application contains software components that were licensed pursuant to one of the FLOSS licenses set forth below ("FLOSS Licenses"), you may distribute such software components subject to that pre-existing FLOSS License.
a. GNU Library (or "Lesser") General Public License (LGPL), versions 2.0 and 2.1
b. Apache Software License, versions 1.0, 1.1, or 2.0
c. BSD License, as copyrighted on July 22, 1999
d. Eclipse Public License, version 1.0
e. MIT/X11 License
f. Mozilla Public License, version 1.1
g. Microsoft Public License (Ms-PL)
h. Microsoft Reciprocal License (Ms-RL)
i. Code Project Open 1.02 License
For the avoidance of doubt, any works that are merely aggregated with the Software or your FLOSS Application on a volume of storage or distribution medium and that can reasonably be considered independent and separate works are not Derivative Works of the Software or your FLOSS Application, and are outside the scope of this Agreement.
5. Ownership
The Software is licensed, not sold. You own the media on which the Software is recorded, but Versant retains ownership of the Software, including all intellectual property rights therein. The Software is protected by United States copyright law and international treaties. You will not delete or in any manner alter the copyright, trademark, or other proprietary rights notices or markings appearing on the Software as delivered to you.
6. Publicity
Versant may publicize your use of the Software in the FLOSS Application as part of Versant's efforts to market the Software.
7. Term
This Agreement remains effective for as long as your FLOSS Application is listed in our Projects section. You may terminate it at any time by destroying all copies of the Software in your possession or control. This Agreement will automatically terminate without notice if you breach any term of this Agreement. Upon termination, you must promptly destroy all copies of the Software in your possession or control.
8. Warranty Disclaimer
VERSANT MAKES NO REPRESENTATION OR WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NONINFRINGEMENT. VERSANT DOES NOT WARRANT THAT THE SOFTWARE IS ERROR FREE OR THAT YOU WILL BE ABLE TO OPERATE THE SOFTWARE WITHOUT PROBLEMS OR INTERRUPTION. Versant does not guarantee the permanent availability of the Versant website.
9. Limitation of Liability
IN NO EVENT WILL VERSANT BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING WITHOUT LIMITATION ANY SPECIAL, INCIDENTAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL DAMAGES (INCLUDING LOSS OF USE, DATA, BUSINESS, OR PROFITS) OR FOR THE COST OF PROCURING SUBSTITUTE PRODUCTS ARISING OUT OF OR IN CONNECTION WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SOFTWARE, WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON CONTRACT, WARRANTY, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY, OR OTHERWISE, AND WHETHER OR NOT VERSANT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. THE FOREGOING LIMITATIONS WILL SURVIVE AND APPLY EVEN IF ANY LIMITED REMEDY SPECIFIED IN THIS AGREEMENT IS FOUND TO HAVE FAILED OF ITS ESSENTIAL PURPOSE.
10. Export Law
You agree to comply fully with all U.S. export laws and regulations to ensure that neither the Software nor any technical data related thereto nor any direct product thereof are exported or re-exported directly or indirectly in violation of, or used for any purposes prohibited by, such laws and regulations.
11. General
This Agreement will be governed by and construed in accordance with the laws of the State of California, without regard to or application of conflicts of law rules or principles. The United Nations Convention on Contracts for the International Sale of Goods will not apply. You may not assign or transfer this Agreement or any rights granted hereunder, by operation of law or otherwise, without Versant's prior written consent, and any attempt by you to do so, without such consent, will be void and of no effect. Except as expressly set forth in this Agreement, the exercise by either party of any of its remedies under this Agreement will be without prejudice to its other remedies under this Agreement or otherwise. The failure by either party to enforce any provision of this Agreement will not constitute a waiver of future enforcement of that or any other provision. Any waiver, modification, or amendment of any provision of this Agreement will be effective only if in writing and signed by authorized representatives of both parties. If any provision of this Agreement is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the other provisions will remain in full force and effect. This Agreement is the complete and exclusive understanding and agreement between the parties regarding its subject matter, and supersedes all proposals, understandings, or communications between the parties, oral or written, regarding its subject matter, unless you and Versant have executed a separate agreement.
Contact Information
If you have any questions regarding this Agreement, you may contact Versant at 255 Shoreline Drive, Suite 450, Redwood City, CA 94065, United States, community@db4o.com.
BY REGISTERING YOUR SOFTWARE YOU HAVE INDICATED THAT YOU UNDERSTAND THIS AGREEMENT AND ACCEPT ALL OF ITS TERMS. IF YOU DO NOT ACCEPT ALL THE TERMS OF THIS AGREEMENT, THEN VERSANT IS UNWILLING TO LICENSE THE SOFTWARE TO YOU UNDER THESE TERMS.
================================================
FILE: licenses/freemarker.txt
================================================
============================================================
Notices for file(s):
/Vega/platform/com.subgraph.vega.ui.scanner/lib/freemarker.jar
License text from http://freemarker.sourceforge.net/docs/app_license.html
------------------------------------------------------------
FreeMarker 1.x was released under the LGPL license. Later, by community
consensus, we have switched over to a BSD-style license. As of FreeMarker
2.2pre1, the original author, Benjamin Geer, has relinquished the copyright in
behalf of Visigoth Software Society. The current copyright holder is the
Visigoth Software Society.
------------------------------------------------------------------------------
Copyright (c) 2003 The Visigoth Software Society. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. The end-user documentation included with the redistribution, if any, must
include the following acknowlegement:
"This product includes software developed by the
Visigoth Software Society (http://www.visigoths.org/)."
Alternately, this acknowlegement may appear in the software itself, if and
wherever such third-party acknowlegements normally appear.
3. Neither the name "FreeMarker", "Visigoth", nor any of the names of the
project contributors may be used to endorse or promote products derived
from this software without prior written permission. For written
permission, please contact visigoths@visigoths.org.
4. Products derived from this software may not be called "FreeMarker" or
"Visigoth" nor may "FreeMarker" or "Visigoth" appear in their names
without prior written permission of the Visigoth Software Society.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
VISIGOTH SOFTWARE SOCIETY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
This software consists of voluntary contributions made by many individuals on
behalf of the Visigoth Software Society. For more information on the Visigoth
Software Society, please see http://www.visigoths.org/
------------------------------------------------------------------------------
FREEMARKER SUBCOMPONENTS UNDER DIFFERENT LICENSE:
FreeMarker includes a number of subcomponents that are licensed by the Apache
Software Foundation under the Apache License, Version 2.0. Your use of these
subcomponents is subject to the terms and conditions of the Apache License,
Version 2.0. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
The subcomponents under this licence are the following files, which are
included both in freemarker.jar and in the source code:
freemarker/ext/jsp/web-app_2_2.dtd
freemarker/ext/jsp/web-app_2_3.dtd
freemarker/ext/jsp/web-app_2_4.xsd
freemarker/ext/jsp/web-app_2_5.xsd
freemarker/ext/jsp/web-jsptaglibrary_1_1.dtd
freemarker/ext/jsp/web-jsptaglibrary_1_2.dtd
freemarker/ext/jsp/web-jsptaglibrary_2_0.xsd
freemarker/ext/jsp/web-jsptaglibrary_2_1.xsd
================================================
FILE: licenses/jsoup.txt
================================================
============================================================
Notices for file(s):
/Vega/platform/com.subgraph.vega.application/extra-bundles/jsoup-1.7.2-SNAPSHOT.jar
License text from http://jsoup.org/license
------------------------------------------------------------
jsoup License
The jsoup code-base (include source and compiled packages) are distributed under the open source MIT license as described below.
The MIT License
Copyright (c) 2009, 2010 Jonathan Hedley (jonathan@hedley.net)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: licenses/mit-license.txt
================================================
The MIT License (MIT)
Copyright (c)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: platform/com.subgraph.vega.analysis/.classpath
================================================
================================================
FILE: platform/com.subgraph.vega.analysis/.project
================================================
com.subgraph.vega.analysis
org.eclipse.jdt.core.javabuilder
org.eclipse.pde.ManifestBuilder
org.eclipse.pde.SchemaBuilder
org.eclipse.pde.ds.core.builder
org.eclipse.pde.PluginNature
org.eclipse.jdt.core.javanature
================================================
FILE: platform/com.subgraph.vega.analysis/.settings/org.eclipse.pde.core.prefs
================================================
#Sun Mar 13 12:48:28 EDT 2011
eclipse.preferences.version=1
pluginProject.extensions=false
resolve.requirebundle=false
================================================
FILE: platform/com.subgraph.vega.analysis/META-INF/MANIFEST.MF
================================================
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Analysis
Bundle-SymbolicName: com.subgraph.vega.analysis
Bundle-Version: 1.0.0.qualifier
Bundle-Vendor: SUBGRAPH
Bundle-RequiredExecutionEnvironment: JavaSE-1.7,
JavaSE-1.6
Import-Package: com.subgraph.vega.api.analysis,
com.subgraph.vega.api.events,
com.subgraph.vega.api.html,
com.subgraph.vega.api.http.requests,
com.subgraph.vega.api.model,
com.subgraph.vega.api.model.alerts,
com.subgraph.vega.api.model.requests,
com.subgraph.vega.api.model.web,
com.subgraph.vega.api.scanner.modules,
com.subgraph.vega.api.util,
org.apache.http;version="4.0.0",
org.apache.http.client.utils;version="4.2.2",
org.jsoup,
org.jsoup.nodes,
org.jsoup.parser,
org.jsoup.select
Service-Component: OSGI-INF/analysis.xml
================================================
FILE: platform/com.subgraph.vega.analysis/OSGI-INF/analysis.xml
================================================
================================================
FILE: platform/com.subgraph.vega.analysis/build.properties
================================================
output.. = bin/
bin.includes = META-INF/,\
.,\
OSGI-INF/
source.. = src/
================================================
FILE: platform/com.subgraph.vega.analysis/epl-v10.html
================================================
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
================================================
FILE: platform/com.subgraph.vega.analysis/src/com/subgraph/vega/internal/analysis/CSSDetector.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.analysis;
import com.subgraph.vega.api.http.requests.IHttpResponse;
public class CSSDetector {
boolean isBodyCSS(IHttpResponse response) {
if(!response.isMostlyAscii())
return false;
final String body = response.getBodyAsString();
if(body == null || body.isEmpty())
return false;
int i = 0;
char lastChar = 0;
boolean first = false;
while(i < body.length()) {
i = skipWhitespace(body, i);
i = skipComments(body, i);
if(i >= body.length()) break;
if(isCSSKeyword(body, i))
return true;
char c = body.charAt(i);
if(c == '{') {
if(!first || lastChar == 0 || (!Character.isLetterOrDigit(lastChar) && ("-_]*".indexOf(lastChar) == -1)))
return false;
else
return true;
}
if(first) {
if(!Character.isLetterOrDigit(c) && (":,.#_-*[]~=\"'>".indexOf(c) == -1))
return false;
} else {
if(!Character.isLetterOrDigit(c) && (".#_-*".indexOf(c) == -1))
return false;
first = true;
}
lastChar = c;
i += 1;
}
return false;
}
private int skipWhitespace(String body, int idx) {
while(idx < body.length() && Character.isWhitespace(body.charAt(idx)))
idx += 1;
return idx;
}
private int skipComments(String body, int idx) {
while(idx < body.length()) {
if(body.startsWith(" protected
@Override
protected RequestWrapper wrapRequest(final HttpRequest request)
throws ProtocolException {
if (request instanceof HttpEntityEnclosingRequest) {
return new VegaEntityEnclosingRequestWrapper(
(HttpEntityEnclosingRequest) request);
} else {
return new VegaRequestWrapper(request);
}
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/client/VegaRequestWrapper.java
================================================
package com.subgraph.vega.internal.http.requests.client;
import java.io.IOException;
import org.apache.http.HttpRequest;
import org.apache.http.ProtocolException;
import org.apache.http.RequestLine;
import org.apache.http.client.methods.AbortableHttpRequest;
import org.apache.http.conn.ClientConnectionRequest;
import org.apache.http.conn.ConnectionReleaseTrigger;
import org.apache.http.impl.client.RequestWrapper;
public class VegaRequestWrapper extends RequestWrapper implements AbortableHttpRequest {
public VegaRequestWrapper(HttpRequest request) throws ProtocolException {
super(request);
}
@Override
public RequestLine getRequestLine() {
return getOriginal().getRequestLine();
}
private AbortableHttpRequest getAbortableRequest() {
if(getOriginal() instanceof AbortableHttpRequest) {
return (AbortableHttpRequest) getOriginal();
} else {
return null;
}
}
@Override
public void setConnectionRequest(ClientConnectionRequest connRequest)
throws IOException {
final AbortableHttpRequest ab = getAbortableRequest();
if(ab != null) {
ab.setConnectionRequest(connRequest);
}
}
@Override
public void setReleaseTrigger(ConnectionReleaseTrigger releaseTrigger)
throws IOException {
final AbortableHttpRequest ab = getAbortableRequest();
if(ab != null) {
ab.setReleaseTrigger(releaseTrigger);
}
}
@Override
public void abort() {
final AbortableHttpRequest ab = getAbortableRequest();
if(ab != null) {
ab.abort();
} else {
super.abort();
}
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/IHttpClientConfigurer.java
================================================
package com.subgraph.vega.internal.http.requests.config;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
public interface IHttpClientConfigurer {
void configureHttpClient(DefaultHttpClient client);
HttpParams createHttpParams();
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/IRequestEncodingStrategy.java
================================================
package com.subgraph.vega.internal.http.requests.config;
import org.apache.http.RequestLine;
public interface IRequestEncodingStrategy {
RequestLine encodeRequestLine(RequestLine requestLine);
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/RequestEngineConfig.java
================================================
package com.subgraph.vega.internal.http.requests.config;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.internal.http.requests.config.proxy.ProxyHttpClientConfigurer;
import com.subgraph.vega.internal.http.requests.config.proxy.ProxyRequestEncodingStrategy;
import com.subgraph.vega.internal.http.requests.config.scanner.ScannerHttpClientConfigurer;
import com.subgraph.vega.internal.http.requests.config.scanner.ScannerRequestEncodingStrategy;
public class RequestEngineConfig {
public static IRequestEncodingStrategy getRequestEncodingStrategy(IHttpRequestEngine.EngineConfigType type) {
switch(type) {
case CONFIG_SCANNER:
return new ScannerRequestEncodingStrategy();
case CONFIG_PROXY:
return new ProxyRequestEncodingStrategy();
}
throw new IllegalStateException();
}
public static IHttpClientConfigurer getHttpClientConfigurer(IHttpRequestEngine.EngineConfigType type) {
switch(type) {
case CONFIG_SCANNER:
return new ScannerHttpClientConfigurer();
case CONFIG_PROXY:
return new ProxyHttpClientConfigurer();
}
throw new IllegalStateException();
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/proxy/ProxyHttpClientConfigurer.java
================================================
package com.subgraph.vega.internal.http.requests.config.proxy;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import com.subgraph.vega.internal.http.requests.RequestCopyHeadersInterceptor;
import com.subgraph.vega.internal.http.requests.RequestExtractCookiesInterceptor;
import com.subgraph.vega.internal.http.requests.VegaResponseProcessCookies;
import com.subgraph.vega.internal.http.requests.config.IHttpClientConfigurer;
public class ProxyHttpClientConfigurer implements IHttpClientConfigurer {
@Override
public void configureHttpClient(DefaultHttpClient client) {
client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
configureRequestInterceptors(client);
configureResponseInterceptors(client);
}
private void configureRequestInterceptors(DefaultHttpClient client) {
client.clearRequestInterceptors();
client.addRequestInterceptor(new RequestCopyHeadersInterceptor());
client.addRequestInterceptor(new RequestExtractCookiesInterceptor());
}
private void configureResponseInterceptors(DefaultHttpClient client) {
client.clearResponseInterceptors();
client.addResponseInterceptor(new VegaResponseProcessCookies());
}
@Override
public HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
return params;
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/proxy/ProxyRequestEncodingStrategy.java
================================================
package com.subgraph.vega.internal.http.requests.config.proxy;
import org.apache.http.RequestLine;
import com.subgraph.vega.internal.http.requests.config.IRequestEncodingStrategy;
public class ProxyRequestEncodingStrategy implements IRequestEncodingStrategy {
@Override
public RequestLine encodeRequestLine(RequestLine requestLine) {
return requestLine;
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/scanner/ScannerHttpClientConfigurer.java
================================================
package com.subgraph.vega.internal.http.requests.config.scanner;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.protocol.ResponseProcessCookies;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import com.subgraph.vega.api.http.requests.IHttpRequestEngineFactory;
import com.subgraph.vega.internal.http.requests.RequestCopyHeadersInterceptor;
import com.subgraph.vega.internal.http.requests.VegaResponseProcessCookies;
import com.subgraph.vega.internal.http.requests.config.IHttpClientConfigurer;
public class ScannerHttpClientConfigurer implements IHttpClientConfigurer {
@Override
public void configureHttpClient(DefaultHttpClient client) {
client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
client.addRequestInterceptor(new RequestCopyHeadersInterceptor());
client.removeResponseInterceptorByClass(ResponseProcessCookies.class);
client.addResponseInterceptor(new VegaResponseProcessCookies());
}
@Override
public HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(params, IHttpRequestEngineFactory.DEFAULT_USER_AGENT);
return params;
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/config/scanner/ScannerRequestEncodingStrategy.java
================================================
package com.subgraph.vega.internal.http.requests.config.scanner;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Logger;
import org.apache.http.RequestLine;
import org.apache.http.message.BasicRequestLine;
import com.subgraph.vega.internal.http.requests.config.IRequestEncodingStrategy;
public class ScannerRequestEncodingStrategy implements IRequestEncodingStrategy {
private final String PATH_ENC_CHARS = "#&=+;,!$?%";
private final String QUERY_ENC_CHARS = "#+;,!$?%";
private final static Logger logger = Logger.getLogger("scanner");
@Override
public RequestLine encodeRequestLine(RequestLine requestLine) {
final String path = lineToPath(requestLine.getUri());
final String query = lineToQuery(requestLine.getUri());
final StringBuilder sb = new StringBuilder();
sb.append(encodePath(path));
if(query != null) {
sb.append('?');
sb.append(encodeQuery(query));
}
return new BasicRequestLine(requestLine.getMethod(), sb.toString(), requestLine.getProtocolVersion());
}
private String encodeQuery(String query) {
// TODO: Quick fix to support URI-encoding UTF-8 characters, probably wrong level of abstraction, should maybe be re-factored as its own EncodingStrategy with a check earlier in the call chain
if (containsUnicode(query)){
try {
return URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warning("UnsupportedEncodingException on query: " + query);
}
}
return encodeString(query, QUERY_ENC_CHARS);
}
private String encodePath(String path) {
return encodeString(path, PATH_ENC_CHARS);
}
private String encodeString(String s, String encChars) {
final StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++) {
encodeCharIntoBuffer(s.charAt(i), encChars, sb);
}
return sb.toString();
}
private void encodeCharIntoBuffer(char c, String encChars, StringBuilder sb) {
if(c <= 0x20 || c >= 0x80 || encChars.indexOf(c) != -1) {
appendEscape(sb, c);
} else {
sb.append(c);
}
}
private final static char[] hexDigits = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
private static void appendEscape(StringBuilder sb, char c) {
sb.append('%');
sb.append(hexDigits[(c >> 4) & 0x0f]);
sb.append(hexDigits[(c >> 0) & 0x0f]);
}
private static String lineToPath(String line) {
final int idx = line.indexOf('?');
if(idx == -1) {
return line;
}
return line.substring(0, idx);
}
private static String lineToQuery(String line) {
final int idx = line.indexOf('?');
if(idx == -1) {
return null;
}
return line.substring(idx + 1);
}
private static boolean containsUnicode(String line) {
for(int i = 0; i < line.length(); i++) {
if (line.charAt(i) > 255) {
return true;
}
}
return false;
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/connection/SocksModeClientConnectionOperator.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.http.requests.connection;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.http.HttpHost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SchemeSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
public class SocksModeClientConnectionOperator extends DefaultClientConnectionOperator {
private final boolean isSocksMode;
public SocksModeClientConnectionOperator(SchemeRegistry sr) {
super(sr);
isSocksMode = System.getProperty("socksEnabled") != null;
}
@Override
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
if(!isSocksMode) {
super.openConnection(conn, target, local, context, params);
return;
}
final Scheme scheme = schemeRegistry.getScheme(target.getSchemeName());
final SchemeSocketFactory sf = scheme.getSchemeSocketFactory();
final int port = scheme.resolvePort(target.getPort());
Socket sock = sf.createSocket(params);
conn.opening(sock, target);
InetSocketAddress remoteAddress = InetSocketAddress.createUnresolved(target.getHostName(), port);
/* We need to use reflection to set the private host field to the target hostname,
* otherwise SSLSocketImpl blows up due to, it seems, https://bugs.openjdk.java.net/browse/JDK-8022081.
*/
if (sf.isSecure(sock) == true) {
Class> c = sock.getClass();
try {
Field f = c.getDeclaredField("host");
f.setAccessible(true);
f.set(sock, target.getHostName());
} catch (NoSuchFieldException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
InetSocketAddress localAddress = null;
if(local != null) {
localAddress = new InetSocketAddress(local, 0);
}
try {
Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
if(sock != connsock) {
sock = connsock;
conn.opening(sock, target);
}
prepareSocket(sock, context, params);
conn.openCompleted(sf.isSecure(sock), params);
return;
} catch (ConnectException ex) {
throw new HttpHostConnectException(target, ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
================================================
FILE: platform/com.subgraph.vega.http.requests/src/com/subgraph/vega/internal/http/requests/connection/SocksSupportingThreadSafeClientConnectionManager.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.http.requests.connection;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
public class SocksSupportingThreadSafeClientConnectionManager extends
PoolingClientConnectionManager {
public SocksSupportingThreadSafeClientConnectionManager(SchemeRegistry sr) {
super(sr);
}
@Override
protected ClientConnectionOperator createConnectionOperator(final SchemeRegistry sr) {
return new SocksModeClientConnectionOperator(sr);
}
}
================================================
FILE: platform/com.subgraph.vega.model/.classpath
================================================
================================================
FILE: platform/com.subgraph.vega.model/.project
================================================
com.subgraph.vega.model
org.eclipse.jdt.core.javabuilder
org.eclipse.pde.ManifestBuilder
org.eclipse.pde.SchemaBuilder
org.eclipse.pde.ds.core.builder
org.eclipse.pde.PluginNature
org.eclipse.jdt.core.javanature
================================================
FILE: platform/com.subgraph.vega.model/.settings/org.eclipse.pde.core.prefs
================================================
#Tue Aug 24 16:44:22 EDT 2010
eclipse.preferences.version=1
pluginProject.extensions=false
resolve.requirebundle=false
================================================
FILE: platform/com.subgraph.vega.model/META-INF/MANIFEST.MF
================================================
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Model
Bundle-SymbolicName: com.subgraph.vega.model
Bundle-Version: 1.0.0.qualifier
Bundle-Vendor: SUBGRAPH
Bundle-RequiredExecutionEnvironment: JavaSE-1.7,
JavaSE-1.6
Import-Package: com.google.common.base,
com.subgraph.vega.api.annotations,
com.subgraph.vega.api.console,
com.subgraph.vega.api.events,
com.subgraph.vega.api.html,
com.subgraph.vega.api.http.requests,
com.subgraph.vega.api.model,
com.subgraph.vega.api.model.alerts,
com.subgraph.vega.api.model.conditions,
com.subgraph.vega.api.model.conditions.match,
com.subgraph.vega.api.model.identity,
com.subgraph.vega.api.model.macros,
com.subgraph.vega.api.model.requests,
com.subgraph.vega.api.model.scope,
com.subgraph.vega.api.model.tags,
com.subgraph.vega.api.model.variables,
com.subgraph.vega.api.model.web,
com.subgraph.vega.api.model.web.forms,
com.subgraph.vega.api.paths,
com.subgraph.vega.api.scanner,
com.subgraph.vega.api.scanner.modules,
com.subgraph.vega.api.util,
com.subgraph.vega.api.vuge,
com.subgraph.vega.api.xml,
com.subgraph.vega.http.requests.builder,
com.subgraph.vega.http.requests.custom,
org.apache.http;version="4.0.0",
org.apache.http.auth;version="4.1.1",
org.apache.http.auth.params;version="4.1.1",
org.apache.http.client;version="4.1.1",
org.apache.http.client.methods;version="4.1.1",
org.apache.http.client.params;version="4.1.1",
org.apache.http.client.protocol;version="4.1.1",
org.apache.http.client.utils,
org.apache.http.entity;version="4.0.0",
org.apache.http.impl.client;version="4.1.1",
org.apache.http.message;version="4.0.0",
org.apache.http.util;version="4.0.0",
org.w3c.dom.html2
Service-Component: OSGI-INF/model.xml
Bundle-ClassPath: .,
lib/db4o-8.0.249.16098-all-java5.jar
Require-Bundle: org.apache.http.core;bundle-version="4.2.3"
================================================
FILE: platform/com.subgraph.vega.model/OSGI-INF/model.xml
================================================
================================================
FILE: platform/com.subgraph.vega.model/build.properties
================================================
output.. = bin/
bin.includes = META-INF/,\
.,\
lib/db4o-8.0.249.16098-all-java5.jar,\
OSGI-INF/
source.. = src/
================================================
FILE: platform/com.subgraph.vega.model/epl-v10.html
================================================
Eclipse Public License - Version 1.0
Eclipse Public License - v 1.0
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR
DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS
AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the initial
code and documentation distributed under this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that particular Contributor. A
Contribution 'originates' from a Contributor if it was added to the
Program by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include additions to the
Program which: (i) are separate modules of software distributed in
conjunction with the Program under their own license agreement, and (ii)
are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents" mean patent claims licensable by a
Contributor which are necessarily infringed by the use or sale of its
Contribution alone or when combined with the Program.
"Program" means the Contributions distributed in accordance
with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free copyright license to reproduce, prepare derivative works
of, publicly display, publicly perform, distribute and sublicense the
Contribution of such Contributor, if any, and such derivative works, in
source code and object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a non-exclusive, worldwide,
royalty-free patent license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the Contribution of such
Contributor, if any, in source code and object code form. This patent
license shall apply to the combination of the Contribution and the
Program if, at the time the Contribution is added by the Contributor,
such addition of the Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall not apply to any other
combinations which include the Contribution. No hardware per se is
licensed hereunder.
c) Recipient understands that although each Contributor
grants the licenses to its Contributions set forth herein, no assurances
are provided by any Contributor that the Program does not infringe the
patent or other intellectual property rights of any other entity. Each
Contributor disclaims any liability to Recipient for claims brought by
any other entity based on infringement of intellectual property rights
or otherwise. As a condition to exercising the rights and licenses
granted hereunder, each Recipient hereby assumes sole responsibility to
secure any other intellectual property rights needed, if any. For
example, if a third party patent license is required to allow Recipient
to distribute the Program, it is Recipient's responsibility to acquire
that license before distributing the Program.
d) Each Contributor represents that to its knowledge it
has sufficient copyright rights in its Contribution, if any, to grant
the copyright license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in object code
form under its own license agreement, provided that:
a) it complies with the terms and conditions of this
Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all Contributors
all warranties and conditions, express and implied, including warranties
or conditions of title and non-infringement, and implied warranties or
conditions of merchantability and fitness for a particular purpose;
ii) effectively excludes on behalf of all Contributors
all liability for damages, including direct, indirect, special,
incidental and consequential damages, such as lost profits;
iii) states that any provisions which differ from this
Agreement are offered by that Contributor alone and not by any other
party; and
iv) states that source code for the Program is available
from such Contributor, and informs licensees how to obtain it in a
reasonable manner on or through a medium customarily used for software
exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement; and
b) a copy of this Agreement must be included with each
copy of the Program.
Contributors may not remove or alter any copyright notices contained
within the Program.
Each Contributor must identify itself as the originator of its
Contribution, if any, in a manner that reasonably allows subsequent
Recipients to identify the originator of the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business partners and the
like. While this license is intended to facilitate the commercial use of
the Program, the Contributor who includes the Program in a commercial
product offering should do so in a manner which does not create
potential liability for other Contributors. Therefore, if a Contributor
includes the Program in a commercial product offering, such Contributor
("Commercial Contributor") hereby agrees to defend and
indemnify every other Contributor ("Indemnified Contributor")
against any losses, damages and costs (collectively "Losses")
arising from claims, lawsuits and other legal actions brought by a third
party against the Indemnified Contributor to the extent caused by the
acts or omissions of such Commercial Contributor in connection with its
distribution of the Program in a commercial product offering. The
obligations in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property infringement. In
order to qualify, an Indemnified Contributor must: a) promptly notify
the Commercial Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the Commercial
Contributor in, the defense and any related settlement negotiations. The
Indemnified Contributor may participate in any such claim at its own
expense.
For example, a Contributor might include the Program in a commercial
product offering, Product X. That Contributor is then a Commercial
Contributor. If that Commercial Contributor then makes performance
claims, or offers warranties related to Product X, those performance
claims and warranties are such Commercial Contributor's responsibility
alone. Under this section, the Commercial Contributor would have to
defend claims against the other Contributors related to those
performance claims and warranties, and if a court requires any other
Contributor to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS
PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION,
ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY
OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement , including but not limited to
the risks and costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and unavailability or
interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT
NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or unenforceable under
applicable law, it shall not affect the validity or enforceability of
the remainder of the terms of this Agreement, and without further action
by the parties hereto, such provision shall be reformed to the minimum
extent necessary to make such provision valid and enforceable.
If Recipient institutes patent litigation against any entity
(including a cross-claim or counterclaim in a lawsuit) alleging that the
Program itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's patent(s), then such
Recipient's rights granted under Section 2(b) shall terminate as of the
date such litigation is filed.
All Recipient's rights under this Agreement shall terminate if it
fails to comply with any of the material terms or conditions of this
Agreement and does not cure such failure in a reasonable period of time
after becoming aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease use and
distribution of the Program as soon as reasonably practicable. However,
Recipient's obligations under this Agreement and any licenses granted by
Recipient relating to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of this
Agreement, but in order to avoid inconsistency the Agreement is
copyrighted and may only be modified in the following manner. The
Agreement Steward reserves the right to publish new versions (including
revisions) of this Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement. The Eclipse
Foundation is the initial Agreement Steward. The Eclipse Foundation may
assign the responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the Agreement will be
given a distinguishing version number. The Program (including
Contributions) may always be distributed subject to the version of the
Agreement under which it was received. In addition, after a new version
of the Agreement is published, Contributor may elect to distribute the
Program (including its Contributions) under the new version. Except as
expressly stated in Sections 2(a) and 2(b) above, Recipient receives no
rights or licenses to the intellectual property of any Contributor under
this Agreement, whether expressly, by implication, estoppel or
otherwise. All rights in the Program not expressly granted under this
Agreement are reserved.
This Agreement is governed by the laws of the State of New York and
the intellectual property laws of the United States of America. No party
to this Agreement will bring a legal action under this Agreement more
than one year after the cause of action arose. Each party waives its
rights to a jury trial in any resulting litigation.
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/DatabaseConfigurationFactory.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.config.QueryEvaluationMode;
import com.db4o.diagnostic.DiagnosticToConsole;
import com.db4o.reflect.jdk.JdkReflector;
import com.db4o.ta.TransparentPersistenceSupport;
import com.subgraph.vega.internal.model.alerts.ScanAlert;
import com.subgraph.vega.internal.model.requests.RequestLogRecord;
import com.subgraph.vega.internal.model.tags.Tag;
public class DatabaseConfigurationFactory {
final private static boolean LAZY_EVALUATION = true;
final private static boolean DIAGNOSTICS_ENABLED = false;
final private static boolean DEBUG_OUTPUT_ENABLED = false;
final private static int DEBUG_OUTPUT_LEVEL = 4;
public EmbeddedConfiguration createDefaultConfiguration() {
EmbeddedConfiguration configuration = Db4oEmbedded.newConfiguration();
configuration.common().reflectWith(new JdkReflector(this.getClass().getClassLoader()));
configuration.common().add(new TransparentPersistenceSupport());
configuration.common().objectClass(RequestLogRecord.class).objectField("requestId").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("requestOrigin").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("hostname").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("requestMethod").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("responseCode").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("responseLength").indexed(true);
configuration.common().objectClass(RequestLogRecord.class).objectField("tagList").indexed(true);
configuration.common().objectClass(ScanAlert.class).objectField("key").indexed(true);
configuration.common().objectClass(ScanAlert.class).objectField("resource").indexed(true);
configuration.common().objectClass(ScanAlert.class).objectField("requestId").indexed(true);
configuration.common().objectClass(Tag.class).objectField("name").indexed(true);
configuration.common().weakReferences(true);
if(DIAGNOSTICS_ENABLED) {
configuration.common().diagnostic().addListener(new DiagnosticToConsole());
}
if(DEBUG_OUTPUT_ENABLED) {
configuration.common().messageLevel(DEBUG_OUTPUT_LEVEL);
}
if(LAZY_EVALUATION) {
configuration.common().queries().evaluationMode(QueryEvaluationMode.LAZY);
}
return configuration;
}
public ObjectContainer openContainer(String path) {
EmbeddedConfiguration config = createDefaultConfiguration();
return Db4oEmbedded.openFile(config, path);
}
public ObjectContainer openContainer(EmbeddedConfiguration config, String path) {
return Db4oEmbedded.openFile(config, path);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/Model.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import java.util.List;
import java.util.logging.Logger;
import com.subgraph.vega.api.console.IConsole;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.events.NamedEventListenerManager;
import com.subgraph.vega.api.html.IHTMLParser;
import com.subgraph.vega.api.model.IModel;
import com.subgraph.vega.api.model.IWorkspace;
import com.subgraph.vega.api.model.IWorkspaceEntry;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
import com.subgraph.vega.api.paths.IPathFinder;
import com.subgraph.vega.api.xml.IXmlRepository;
public class Model implements IModel {
private final Logger logger = Logger.getLogger("model");
private final EventListenerManager workspaceEventManager = new EventListenerManager();
private final NamedEventListenerManager conditionSetChangeEventManager = new NamedEventListenerManager();
private IWorkspace currentWorkspace;
private IConsole console;
private IHTMLParser htmlParser;
private IXmlRepository xmlRepository;
private IPathFinder pathFinder;
private WorkspaceEntries workspaceEntries;
public void activate() {
workspaceEntries = new WorkspaceEntries(pathFinder);
}
protected void setConsole(IConsole console) {
this.console = console;
}
protected void unsetConsole(IConsole console) {
this.console = null;
}
protected void setHTMLParser(IHTMLParser parser) {
this.htmlParser = parser;
}
protected void unsetHTMLParser(IHTMLParser parser) {
this.htmlParser = null;
}
protected void setXmlRepository(IXmlRepository xmlRepository) {
this.xmlRepository = xmlRepository;
}
protected void unsetXmlRepository(IXmlRepository xmlRepository) {
this.xmlRepository = null;
}
protected void setPathFinder(IPathFinder pathFinder) {
this.pathFinder = pathFinder;
}
protected void unsetPathFinder(IPathFinder pathFinder) {
this.pathFinder = null;
}
@Override
public IWorkspace addWorkspaceListener(IEventHandler handler) {
workspaceEventManager.addListener(handler);
return currentWorkspace;
}
@Override
public void removeWorkspaceListener(IEventHandler handler) {
workspaceEventManager.removeListener(handler);
}
@Override
public List getWorkspaceEntries() {
return workspaceEntries.getWorkspaceEntries();
}
@Override
public boolean openDefaultWorkspace() {
final IWorkspaceEntry entry = workspaceEntries.getDefaultWorkspaceEntry();
if(entry == null)
return false;
else
return openWorkspaceEntry(entry);
}
@Override
public boolean openWorkspaceByIndex(int index) {
throw new UnsupportedOperationException("Not implemented yet");
}
private boolean openWorkspaceEntry(IWorkspaceEntry entry) {
IWorkspace workspace = new Workspace(this, entry, conditionSetChangeEventManager, workspaceEventManager, console, htmlParser, xmlRepository);
if(!workspace.open()) {
logger.warning("Failed to open workspace at path "+ entry.getPath());
return false;
}
currentWorkspace = workspace;
return true;
}
@Override
public void resetCurrentWorkspace() {
if(currentWorkspace != null)
currentWorkspace.reset();
}
@Override
public IWorkspace getCurrentWorkspace() {
return currentWorkspace;
}
@Override
public IHttpConditionSet addConditionSetTracker(String name, IEventHandler handler) {
conditionSetChangeEventManager.addListener(name, handler);
if(currentWorkspace != null) {
return currentWorkspace.getHttpConditionMananger().getConditionSet(name);
}
return null;
}
@Override
public void removeConditionSetTracker(String name, IEventHandler handler) {
conditionSetChangeEventManager.removeListener(name, handler);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/ModelProperties.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableHashMap;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.IModelProperties;
public class ModelProperties implements IModelProperties, Activatable {
private final Map propertyMap;
private transient Activator activator;
public ModelProperties() {
propertyMap = new ActivatableHashMap();
}
public void setProperty(String name, Object value) {
activate(ActivationPurpose.READ);
synchronized(propertyMap) {
propertyMap.put(name, value);
}
}
public void setStringProperty(String name, String value) {
setProperty(name, value);
}
public void setIntegerProperty(String name, int value) {
setProperty(name, value);
}
public Object getProperty(String name) {
activate(ActivationPurpose.READ);
synchronized(propertyMap) {
return propertyMap.get(name);
}
}
public String getStringProperty(String name) {
final Object value = getProperty(name);
if(value == null)
return null;
if(value instanceof String)
return (String) value;
throw new IllegalArgumentException("Property '"+ name +"' exists but it is not a String");
}
public Integer getIntegerProperty(String name) {
final Object value = getProperty(name);
if(value == null)
return null;
if(value instanceof Integer)
return (Integer) value;
throw new IllegalArgumentException("Property '"+ name +"' exists but it is not an Integer");
}
public List propertyKeys() {
activate(ActivationPurpose.READ);
synchronized(propertyMap) {
return new ArrayList(propertyMap.keySet());
}
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator)
return;
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/ModelVersion.java
================================================
package com.subgraph.vega.internal.model;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.IModelVersion;
public class ModelVersion implements IModelVersion, Activatable {
private transient Activator activator;
private final int verMajor;
private final int verMinor;
public ModelVersion(int verMajor, int verMinor) {
this.verMajor = verMajor;
this.verMinor = verMinor;
}
@Override
public int getVerMajor() {
activate(ActivationPurpose.READ);
return verMajor;
}
@Override
public int getVerMinor() {
activate(ActivationPurpose.READ);
return verMinor;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/Workspace.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import com.db4o.ObjectContainer;
import com.db4o.ext.DatabaseFileLockedException;
import com.subgraph.vega.api.console.IConsole;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.NamedEventListenerManager;
import com.subgraph.vega.api.html.IHTMLParser;
import com.subgraph.vega.api.model.IModel;
import com.subgraph.vega.api.model.IModelProperties;
import com.subgraph.vega.api.model.IModelVersion;
import com.subgraph.vega.api.model.IWorkspace;
import com.subgraph.vega.api.model.IWorkspaceEntry;
import com.subgraph.vega.api.model.WorkspaceCloseEvent;
import com.subgraph.vega.api.model.WorkspaceOpenEvent;
import com.subgraph.vega.api.model.WorkspaceResetEvent;
import com.subgraph.vega.api.model.alerts.IScanAlertRepository;
import com.subgraph.vega.api.model.conditions.IHttpConditionManager;
import com.subgraph.vega.api.model.identity.IIdentityModel;
import com.subgraph.vega.api.model.macros.IHttpMacroModel;
import com.subgraph.vega.api.model.requests.IRequestLog;
import com.subgraph.vega.api.model.scope.ITargetScopeManager;
import com.subgraph.vega.api.model.tags.ITagModel;
import com.subgraph.vega.api.model.variables.IVariableModel;
import com.subgraph.vega.api.model.web.IWebModel;
import com.subgraph.vega.api.vuge.IConstants;
import com.subgraph.vega.api.xml.IXmlRepository;
import com.subgraph.vega.internal.model.alerts.ScanAlertRepository;
import com.subgraph.vega.internal.model.conditions.HttpConditionManager;
import com.subgraph.vega.internal.model.identity.IdentityModel;
import com.subgraph.vega.internal.model.macros.HttpMacroModel;
import com.subgraph.vega.internal.model.requests.RequestLog;
import com.subgraph.vega.internal.model.scope.TargetScopeManager;
import com.subgraph.vega.internal.model.tags.TagModel;
import com.subgraph.vega.internal.model.variables.VariableModel;
import com.subgraph.vega.internal.model.web.WebModel;
public class Workspace implements IWorkspace {
private static final int BACKGROUND_COMMIT_INTERVAL = 10000;
private final IModel model;
private final IWorkspaceEntry workspaceEntry;
private final NamedEventListenerManager conditionChangeManager;
private final EventListenerManager eventManager;
private final DatabaseConfigurationFactory configurationFactory;
private final IConsole console;
private final IHTMLParser htmlParser;
private final IXmlRepository xmlRepository;
private final WorkspaceLockStatus lockStatus;
private IModelVersion modelVersion;
private ITagModel tagModel;
private IWebModel webModel;
private IVariableModel variableModel;
private IHttpMacroModel httpMacroModel;
private IIdentityModel identityModel;
private IRequestLog requestLog;
private IScanAlertRepository scanAlerts;
private ITargetScopeManager targetScopeManager;
private HttpConditionManager conditionManager;
private ObjectContainer database;
private boolean opened;
private final Timer backgroundCommitTimer;
private TimerTask backgroundCommitTask;
private WorkspaceStatus workspaceStatus;
Workspace(IModel model, IWorkspaceEntry entry, NamedEventListenerManager conditionChangeManager, EventListenerManager eventManager,
IConsole console, IHTMLParser htmlParser, IXmlRepository xmlRepository) {
this.model = model;
this.configurationFactory = new DatabaseConfigurationFactory();
this.workspaceEntry = entry;
this.conditionChangeManager = conditionChangeManager;
this.eventManager = eventManager;
this.console = console;
this.htmlParser = htmlParser;
this.xmlRepository = xmlRepository;
this.lockStatus = new WorkspaceLockStatus(eventManager);
this.backgroundCommitTimer = new Timer();
}
@Override
public IModel getModel() {
return model;
}
@Override
public boolean open() {
if(opened)
throw new IllegalStateException("open() called on workspace which has already been opened.");
database = openDatabase(getDatabaseFile());
if(database == null)
return false;
opened = true;
eventManager.fireEvent(new WorkspaceOpenEvent(this));
backgroundCommitTask = createBackgroundCommitTask(database);
backgroundCommitTimer.scheduleAtFixedRate(backgroundCommitTask, 0, BACKGROUND_COMMIT_INTERVAL);
return true;
}
private File getDatabaseFile() {
return new File(workspaceEntry.getPath(), "model.db");
}
private ObjectContainer openDatabase(final File databaseFile) {
try {
final String databasePath = databaseFile.getAbsolutePath();
final boolean exists = databaseFile.exists(); // possible race condition
final ObjectContainer db = configurationFactory.openContainer(databasePath);
loadModelVersion(db, !exists);
tagModel = new TagModel(db);
webModel = new WebModel(db);
variableModel = new VariableModel(db);
httpMacroModel = new HttpMacroModel(db);
identityModel = new IdentityModel(db);
requestLog = new RequestLog(db);
scanAlerts = new ScanAlertRepository(db, xmlRepository);
conditionManager = new HttpConditionManager(db, conditionChangeManager);
targetScopeManager = new TargetScopeManager(db);
return db;
} catch (DatabaseFileLockedException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public IModelVersion getModelVersion() {
if (!opened) {
throw new IllegalStateException("Must open workspace first");
}
return modelVersion;
}
@Override
public ITagModel getTagModel() {
if (!opened) {
throw new IllegalStateException("Must open workspace first");
}
return tagModel;
}
@Override
public IVariableModel getVariableModel() {
if (!opened) {
throw new IllegalStateException("Must open workspace first");
}
return variableModel;
}
@Override
public IHttpMacroModel getHttpMacroModel() {
if (!opened) {
throw new IllegalStateException("Must open workspace first");
}
return httpMacroModel;
}
@Override
public IIdentityModel getIdentityModel() {
if (!opened) {
throw new IllegalStateException("Must open workspace first");
}
return identityModel;
}
@Override
public IWebModel getWebModel() {
if(!opened)
throw new IllegalStateException("Must open workspace first");
return webModel;
}
@Override
public IRequestLog getRequestLog() {
if(!opened)
throw new IllegalStateException("Must open workspace first");
return requestLog;
}
@Override
public IScanAlertRepository getScanAlertRepository() {
if(!opened)
throw new IllegalStateException("Must open workspace first");
return scanAlerts;
}
@Override
public IHttpConditionManager getHttpConditionMananger() {
return conditionManager;
}
@Override
public void close() {
if(!opened)
return;
if(lockStatus.isLocked())
throw new IllegalStateException("Cannot close locked workspace.");
backgroundCommitTask.cancel();
conditionManager.notifyClosed();
database.close();
opened = false;
eventManager.fireEvent(new WorkspaceCloseEvent(this));
}
@Override
public void setProperty(String name, Object value) {
getProperties().setProperty(name, value);
}
@Override
public void setStringProperty(String name, String value) {
getProperties().setStringProperty(name, value);
}
@Override
public void setIntegerProperty(String name, int value) {
getProperties().setIntegerProperty(name, value);
}
@Override
public Object getProperty(String name) {
return getProperties().getProperty(name);
}
@Override
public String getStringProperty(String name) {
return getProperties().getStringProperty(name);
}
@Override
public Integer getIntegerProperty(String name) {
return getProperties().getIntegerProperty(name);
}
@Override
public List propertyKeys() {
return getProperties().propertyKeys();
}
private IModelProperties getProperties() {
if(workspaceStatus != null)
return workspaceStatus.getProperties();
synchronized(this) {
List result = database.query(WorkspaceStatus.class);
if(result.size() == 0) {
workspaceStatus = new WorkspaceStatus();
database.store(workspaceStatus);
return workspaceStatus.getProperties();
} else if(result.size() == 1) {
workspaceStatus = result.get(0);
return workspaceStatus.getProperties();
} else {
throw new IllegalStateException("Database corrupted, multiple WorkspaceStatus instances");
}
}
}
@Override
public IHTMLParser getHTMLParser() {
return htmlParser;
}
@Override
public ITargetScopeManager getTargetScopeManager() {
return targetScopeManager;
}
@Override
public void consoleWrite(String output) {
console.write(output);
}
@Override
public void consoleDebug(String output) {
console.debug(output);
}
@Override
public void consoleError(String output) {
console.error(output);
}
@Override
public void lock() {
lockStatus.lock();
}
@Override
public void unlock() {
lockStatus.unlock();
}
@Override
public void reset() {
if(lockStatus.isLocked())
throw new IllegalStateException("Cannot reset locked workspace");
backgroundCommitTask.cancel();
synchronized(this) {
conditionManager.notifyClosed();
database.close();
final File databaseFile = getDatabaseFile();
if(!databaseFile.delete()) {
// XXX
}
database = openDatabase(databaseFile);
if(database != null) {
workspaceStatus = null;
eventManager.fireEvent(new WorkspaceResetEvent(this));
backgroundCommitTask = createBackgroundCommitTask(database);
backgroundCommitTimer.scheduleAtFixedRate(backgroundCommitTask, 0, BACKGROUND_COMMIT_INTERVAL);
} else {
eventManager.fireEvent(new WorkspaceCloseEvent(this));
}
}
}
private TimerTask createBackgroundCommitTask(final ObjectContainer db) {
return new TimerTask() {
@Override
public void run() {
if(!db.ext().isClosed()) {
db.commit();
}
}
};
}
private void loadModelVersion(ObjectContainer database, boolean newFile) {
if (newFile == false) {
final List results = database.query(IModelVersion.class);
if (results.size() != 0) {
modelVersion = results.get(0);
} else {
// reverse compatibility: Vega 1.0 beta and earlier did not have model version
modelVersion = new ModelVersion(1, 0);
database.store(modelVersion);
}
} else {
modelVersion = new ModelVersion(IConstants.VERSION_MAJOR, IConstants.VERSION_MINOR);
database.store(modelVersion);
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/WorkspaceEntries.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import com.subgraph.vega.api.model.IWorkspaceEntry;
import com.subgraph.vega.api.paths.IPathFinder;
public class WorkspaceEntries {
private final static int MAX_WORKSPACE_INDEX = 1000;
private final static int DEFAULT_WORKSPACE_INDEX = 0;
private final Logger logger = Logger.getLogger("model");
private final File workspaceDirectory;
private final IWorkspaceEntry[] entryArray = new IWorkspaceEntry[MAX_WORKSPACE_INDEX + 1];
WorkspaceEntries(IPathFinder pathFinder) {
this.workspaceDirectory = pathFinder.getWorkspaceDirectory();
loadWorkspaceEntries();
}
private void loadWorkspaceEntries() {
if(!workspaceDirectory.exists()) {
if(!workspaceDirectory.mkdirs()) {
logger.warning("Failed to create workspace directory: "+ workspaceDirectory);
return;
}
}
if(!workspaceDirectory.isDirectory()) {
logger.warning("Workspace directory name exists but is not a directory: "+ workspaceDirectory);
return;
}
for(File ws: workspaceDirectory.listFiles()) {
final WorkspaceEntry entry = WorkspaceEntry.createFromPath(ws);
if(entry != null) {
entryArray[entry.getIndex()] = entry;
}
}
if(entryArray[DEFAULT_WORKSPACE_INDEX] == null)
entryArray[DEFAULT_WORKSPACE_INDEX] = createDefaultWorkspace();
}
private WorkspaceEntry createDefaultWorkspace() {
return createWorkspace(DEFAULT_WORKSPACE_INDEX, "default");
}
private WorkspaceEntry createWorkspace(int index, String name) {
final File path = indexToWorkspacePath(index);
final File nameFile = new File(path, ".name");
if(path.exists())
throw new IllegalStateException("Workspace directory already exists "+ path);
if(!path.mkdirs()) {
logger.warning("Failed to make directory while creating workspace: "+ path);
return null;
}
final Writer writer = openNameFileWriter(nameFile);
if(writer == null)
return null;
try {
writer.write(name +"\n");
return new WorkspaceEntry(name, index, false, path);
} catch (IOException e) {
logger.warning("I/O error writing to name file while creating workspace "+ nameFile);
return null;
} finally {
try {
writer.close();
} catch (IOException e) {}
}
}
private Writer openNameFileWriter(File nameFile) {
try {
final FileOutputStream out = new FileOutputStream(nameFile);
return new OutputStreamWriter(out);
} catch (FileNotFoundException e) {
logger.warning("Failed to open name file for writing :"+ nameFile);
return null;
}
}
private File indexToWorkspacePath(int index) {
if(index < 0 || index > MAX_WORKSPACE_INDEX)
throw new IllegalArgumentException("Workspace index out of range (0 - "+ MAX_WORKSPACE_INDEX +") : "+ index);
final String indexStr = String.format("%02d", index);
return new File(workspaceDirectory, indexStr);
}
List getWorkspaceEntries() {
final List entryList = new ArrayList();
for(int i = 0; i <= MAX_WORKSPACE_INDEX; i++)
if(entryArray[i] != null)
entryList.add(entryArray[i]);
return entryList;
}
IWorkspaceEntry getDefaultWorkspaceEntry() {
IWorkspaceEntry firstEntry = null;
for(int i = 0; i <= MAX_WORKSPACE_INDEX; i++) {
IWorkspaceEntry entry = entryArray[i];
if(entry != null) {
if(entry.isAutostart())
return entry;
else if(firstEntry == null)
firstEntry = entry;
}
}
if(firstEntry == null)
throw new IllegalStateException("No default workspace entry found");
return firstEntry;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/WorkspaceEntry.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;
import com.subgraph.vega.api.model.IWorkspaceEntry;
public class WorkspaceEntry implements IWorkspaceEntry {
private static final Logger logger = Logger.getLogger("model");
static WorkspaceEntry createFromPath(File path) {
if(!Character.isDigit(path.getName().charAt(0))) {
return null;
}
final int index = pathToIndex(path);
if(index == -1)
return null;
final String name = pathToWorkspaceName(path);
if(name == null)
return null;
final boolean autostart = pathToAutostartFlag(path);
return new WorkspaceEntry(name, index, autostart, path);
}
static int pathToIndex(File path) {
String indexName = path.getName();
try {
final int n = Integer.parseInt(indexName);
if(n < 0 || n > 1000) {
logger.warning("Could not read workspace because path is incorrectly formatted "+ path);
return -1;
}
else
return n;
} catch (NumberFormatException e) {
logger.warning("Could not read workspace because path is incorrectly formatted "+ path);
return -1;
}
}
static String pathToWorkspaceName(File path) {
final File nameFile = new File(path, ".name");
final BufferedReader reader = openNameFileReader(nameFile);
if(reader == null)
return null;
try {
final String name = reader.readLine();
if(name == null || name.isEmpty()) {
logger.warning("Could not read workpace because name file is empty "+ nameFile);
return null;
}
return name;
} catch (IOException e) {
logger.warning("Could not read workspace, I/O error reading name file "+ nameFile);
return null;
} finally {
try {
reader.close();
} catch (IOException e) { }
}
}
static boolean pathToAutostartFlag(File path) {
final File autostartFile = new File(path, ".autostart");
return autostartFile.exists();
}
static BufferedReader openNameFileReader(File nameFile) {
try {
final FileInputStream in = new FileInputStream(nameFile);
return new BufferedReader(new InputStreamReader(in));
} catch (FileNotFoundException e) {
return null;
}
}
private final String name;
private final int index;
private final boolean autostart;
private final File path;
WorkspaceEntry(String name, int index, boolean autostart, File path) {
this.name = name;
this.index = index;
this.autostart = autostart;
this.path = path;
}
@Override
public String getName() {
return name;
}
@Override
public int getIndex() {
return index;
}
@Override
public File getPath() {
return path;
}
@Override
public boolean isAutostart() {
return autostart;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/WorkspaceLockStatus.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.WorkspaceLockStatusEvent;
public class WorkspaceLockStatus {
private final EventListenerManager eventManager;
private int lockCount = 0;
WorkspaceLockStatus(EventListenerManager eventManager) {
this.eventManager = eventManager;
}
synchronized void lock() {
if(lockCount == 0)
eventManager.fireEvent(new WorkspaceLockStatusEvent(true));
lockCount += 1;
}
synchronized void unlock() {
if(lockCount == 0)
throw new IllegalStateException("Cannot call unlock() on unlocked workspace.");
if(lockCount == 1)
eventManager.fireEvent(new WorkspaceLockStatusEvent(false));
lockCount -= 1;
}
synchronized boolean isLocked() {
return lockCount != 0;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/WorkspaceStatus.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model;
public class WorkspaceStatus {
private final ModelProperties properties;
WorkspaceStatus() {
properties = new ModelProperties();
}
ModelProperties getProperties() {
return properties;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanAlert.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.alerts;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.alerts.IScanAlert;
import com.subgraph.vega.api.model.alerts.IScanAlertHighlight;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.internal.model.ModelProperties;
public class ScanAlert implements IScanAlert, Activatable {
private final String name;
private final Severity severity;
private final String title;
private final String key;
private final IScanInstance scanInstance;
private final long requestId;
private final List alertHighlights;
private String templateName = "main";
private String resource;
private final ModelProperties properties;
private transient Activator activator;
private String discretionaryHostname;
ScanAlert(String key, String name, String title, Severity severity, IScanInstance scanInstance, long requestId) {
this.key = key;
this.name = name;
this.title = title;
this.severity = severity;
this.properties = new ModelProperties();
this.scanInstance = scanInstance;
this.requestId = requestId;
this.alertHighlights = new ActivatableArrayList();
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public Severity getSeverity() {
activate(ActivationPurpose.READ);
return severity;
}
@Override
public String getTitle() {
activate(ActivationPurpose.READ);
return title;
}
@Override
public String getDiscretionaryHostname() {
activate(ActivationPurpose.READ);
return this.discretionaryHostname;
}
@Override
public void setDiscretionaryHostname(String hostname) {
activate(ActivationPurpose.READ);
discretionaryHostname = hostname;
activate(ActivationPurpose.WRITE);
}
@Override
public void setResource(String resourceString) {
activate(ActivationPurpose.READ);
this.resource = resourceString;
activate(ActivationPurpose.WRITE);
}
@Override
public void setTemplateName(String name) {
activate(ActivationPurpose.READ);
templateName = name;
activate(ActivationPurpose.WRITE);
}
@Override
public void setProperty(String name, Object value) {
activate(ActivationPurpose.READ);
if(name.equals("resource") && value instanceof String) {
resource = (String) value;
activate(ActivationPurpose.WRITE);
}
properties.setProperty(name, value);
}
@Override
public void setStringProperty(String name, String value) {
activate(ActivationPurpose.READ);
properties.setStringProperty(name, value);
}
@Override
public void setIntegerProperty(String name, int value) {
activate(ActivationPurpose.READ);
properties.setIntegerProperty(name, value);
}
@Override
public Object getProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getProperty(name);
}
@Override
public String getStringProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getStringProperty(name);
}
@Override
public Integer getIntegerProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getIntegerProperty(name);
}
@Override
public List propertyKeys() {
activate(ActivationPurpose.READ);
return properties.propertyKeys();
}
@Override
public String getTemplateName() {
activate(ActivationPurpose.READ);
return templateName;
}
@Override
public String getResource() {
activate(ActivationPurpose.READ);
return resource;
}
@Override
public String getKey() {
activate(ActivationPurpose.READ);
return key;
}
@Override
public boolean hasAssociatedRequest() {
activate(ActivationPurpose.READ);
return requestId != -1;
}
@Override
public IScanInstance getScanInstance() {
activate(ActivationPurpose.READ);
return scanInstance;
}
@Override
public long getScanId() {
activate(ActivationPurpose.READ);
return scanInstance.getScanId();
}
@Override
public long getRequestId() {
activate(ActivationPurpose.READ);
return requestId;
}
@Override
public void addStringMatchHighlight(String matchStr) {
activate(ActivationPurpose.READ);
alertHighlights.add(new ScanAlertHighlight(matchStr, false, false));
activate(ActivationPurpose.WRITE);
}
@Override
public void addRegexHighlight(String regex) {
activate(ActivationPurpose.READ);
alertHighlights.add(new ScanAlertHighlight(regex, true, true));
activate(ActivationPurpose.WRITE);
}
@Override
public void addRegexCaseInsensitiveHighlight(String regex) {
activate(ActivationPurpose.READ);
alertHighlights.add(new ScanAlertHighlight(regex, true, false));
activate(ActivationPurpose.WRITE);
}
@Override
public Collection getHighlights() {
activate(ActivationPurpose.READ);
return Collections.unmodifiableCollection(new ArrayList(alertHighlights));
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ScanAlert other = (ScanAlert) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (requestId != other.requestId)
return false;
if (scanInstance == null) {
if (other.scanInstance != null)
return false;
} else if (!scanInstance.equals(other.scanInstance))
return false;
if (severity != other.severity)
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + (int) (requestId ^ (requestId >>> 32));
result = prime * result
+ ((scanInstance == null) ? 0 : scanInstance.hashCode());
result = prime * result
+ ((severity == null) ? 0 : severity.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanAlertFactory.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.alerts;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.subgraph.vega.api.model.alerts.IScanAlert.Severity;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.xml.IXmlRepository;
public class ScanAlertFactory {
private final Logger logger = Logger.getLogger("alerts");
private final IXmlRepository xmlRepository;
ScanAlertFactory(IXmlRepository xmlRepository) {
this.xmlRepository = xmlRepository;
}
ScanAlert createAlert(String key, String name, IScanInstance scanInstance, long requestId) {
Document doc = xmlRepository.getDocument("alerts/"+ name +".xml");
if(doc == null)
doc = xmlRepository.getDocument("alerts/default.xml");
if(doc == null) {
logger.warning("Could not find XML alert description named "+ name);
return null;
}
final Element alert = getAlertElement(doc, name);
if(alert == null)
return null;
final Severity severity = parseSeverity(alert);
final String title = parseTitle(alert);
return new ScanAlert(key, name, title, severity, scanInstance, requestId);
}
private Severity parseSeverity(Element alertElement) {
NodeList nodeList = alertElement.getElementsByTagName("severity");
if(nodeList.getLength() == 0 || nodeList.item(0).getNodeType() != Node.ELEMENT_NODE)
return Severity.UNKNOWN;
return processSeverityElement((Element) nodeList.item(0));
}
private Severity processSeverityElement(Element e) {
final String sev = getTextForElement(e);
if(sev == null)
return Severity.UNKNOWN;
if(sev.equalsIgnoreCase("high"))
return Severity.HIGH;
else if(sev.equalsIgnoreCase("medium"))
return Severity.MEDIUM;
else if(sev.equalsIgnoreCase("low"))
return Severity.LOW;
else if(sev.equalsIgnoreCase("info"))
return Severity.INFO;
else
return Severity.UNKNOWN;
}
private String parseTitle(Element alertElement) {
final NodeList nodeList = alertElement.getElementsByTagName("title");
if(nodeList.getLength() == 0 || nodeList.item(0).getNodeType() != Node.ELEMENT_NODE)
return null;
final Element titleElement = (Element) nodeList.item(0);
return getTextForElement(titleElement);
}
private String getTextForElement(Element e) {
final NodeList nodes = e.getChildNodes();
for(int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
if(n.getNodeType() == Node.TEXT_NODE)
return n.getNodeValue();
}
return null;
}
private Element getAlertElement(Document xmlRoot, String name) {
final NodeList alertNodes = xmlRoot.getElementsByTagName("alert");
final int n = alertNodes.getLength();
if(n == 0) {
logger.warning("No alert node found in XML for description "+ name);
return null;
}
if(n > 1) {
logger.warning("Multiple alert entries found in XML for description "+ name +", ignoring extras");
}
if(alertNodes.item(0).getNodeType() != Node.ELEMENT_NODE)
return null;
return (Element) alertNodes.item(0);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanAlertHighlight.java
================================================
package com.subgraph.vega.internal.model.alerts;
import com.subgraph.vega.api.model.alerts.IScanAlertHighlight;
public class ScanAlertHighlight implements IScanAlertHighlight {
private final String matchString;
private final boolean isRegex;
private boolean isCaseSensitive;
ScanAlertHighlight(String matchString, boolean isRegex, boolean isCaseSensitive) {
this.matchString = matchString;
this.isRegex = isRegex;
this.isCaseSensitive = isCaseSensitive;
}
@Override
public boolean isRegularExpression() {
return isRegex;
}
@Override
public boolean isCaseSensitive() {
return isCaseSensitive;
}
@Override
public String getMatchString() {
return matchString;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanAlertRepository.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.alerts;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import com.db4o.ObjectContainer;
import com.db4o.events.Event4;
import com.db4o.events.EventListener4;
import com.db4o.events.EventRegistry;
import com.db4o.events.EventRegistryFactory;
import com.db4o.events.ObjectInfoEventArgs;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.alerts.ActiveScanInstanceEvent;
import com.subgraph.vega.api.model.alerts.IScanAlert;
import com.subgraph.vega.api.model.alerts.IScanAlertRepository;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.model.alerts.NewScanInstanceEvent;
import com.subgraph.vega.api.model.alerts.RemoveScanAlertsEvent;
import com.subgraph.vega.api.model.alerts.RemoveScanInstanceEvent;
import com.subgraph.vega.api.xml.IXmlRepository;
public class ScanAlertRepository implements IScanAlertRepository {
private final static Logger logger = Logger.getLogger("alerts");
private final ObjectContainer database;
private final Object scanInstanceLock = new Object();
private final ScanAlertFactory alertFactory;
private final EventListenerManager scanInstanceEventManager;
private final List activeScanInstanceList;
public ScanAlertRepository(ObjectContainer db, IXmlRepository xmlRepository) {
this.database = db;
this.alertFactory = new ScanAlertFactory(xmlRepository);
this.scanInstanceEventManager = new EventListenerManager();
final EventRegistry registry = EventRegistryFactory.forObjectContainer(database);
registry.activated().addListener(new EventListener4() {
@Override
public void onEvent(Event4 e, ObjectInfoEventArgs args) {
final Object ob = args.object();
if(ob instanceof ScanInstance) {
final ScanInstance scan = (ScanInstance) ob;
scan.setTransientState(database, ScanAlertRepository.this, alertFactory);
final int status = scan.getScanStatus();
if(status != IScanInstance.SCAN_CONFIG && status != IScanInstance.SCAN_COMPLETED && status != IScanInstance.SCAN_CANCELLED) {
scan.updateScanStatus(IScanInstance.SCAN_CANCELLED);
}
}
}
});
getProxyScanInstance();
activeScanInstanceList = new ArrayList();
}
void fireRemoveEventsEvent(IScanInstance instance, Collection removedAlerts) {
scanInstanceEventManager.fireEvent(new RemoveScanAlertsEvent(instance, removedAlerts));
}
@Override
public List addActiveScanInstanceListener(IEventHandler listener) {
scanInstanceEventManager.addListener(listener);
return getAllActiveScanInstances();
}
@Override
public void removeActiveScanInstanceListener(IEventHandler listener) {
scanInstanceEventManager.removeListener(listener);
}
@Override
public synchronized void addActiveScanInstance(IScanInstance scanInstance) {
activeScanInstanceList.add(scanInstance);
scanInstanceEventManager.fireEvent(new ActiveScanInstanceEvent(scanInstance));
}
@Override
public synchronized void removeActiveScanInstance(IScanInstance scanInstance) {
activeScanInstanceList.remove(scanInstance);
}
@Override
public synchronized List getAllActiveScanInstances() {
return new ArrayList(activeScanInstanceList);
}
@Override
public List getAllScanInstances() {
return database.query(IScanInstance.class);
}
@Override
public synchronized IScanInstance createNewScanInstance() {
synchronized(scanInstanceLock) {
final long scanId = allocateNewScanId();
final IScanInstance scan = createScanInstanceForScanId(scanId);
scanInstanceEventManager.fireEvent(new NewScanInstanceEvent(scan));
return scan;
}
}
private IScanInstance createScanInstanceForScanId(long scanId) {
final ScanInstance scan = new ScanInstance(scanId);
scan.setTransientState(database, this, alertFactory);
database.store(scan);
return scan;
}
@Override
public synchronized IScanInstance getScanInstanceByScanId(final long scanId) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IScanInstance scan) {
return scan.getScanId() == scanId;
}
});
if(results.size() == 0) {
return null;
} else if (results.size() > 1) {
logger.warning("Multiple scan instances for scanId = "+ scanId);
}
return results.get(0);
}
@Override
public synchronized IScanInstance getProxyScanInstance() {
final IScanInstance scan = getScanInstanceByScanId(PROXY_ALERT_ORIGIN_SCAN_ID);
if(scan != null) {
return scan;
}
return createScanInstanceForScanId(PROXY_ALERT_ORIGIN_SCAN_ID);
}
private long allocateNewScanId() {
int count = 0;
final Random r = new Random();
while(true) {
long scanId = r.nextInt(999999) + 1;
if(getScanInstanceByScanId(scanId) == null) {
return scanId;
}
count += 1;
if(count > 10) {
throw new IllegalStateException("Unable to generate unique random scan id");
}
}
}
@Override
public Collection getAlertsByRequestId(final long requestId) {
return database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IScanAlert alert) {
return (alert.getRequestId() == requestId);
}
});
}
@Override
public synchronized void removeScanInstance(IScanInstance scanInstance) {
if(scanInstance.getScanId() == PROXY_ALERT_ORIGIN_SCAN_ID) {
throw new IllegalArgumentException("Cannot remove scan instance for proxy alerts");
}
if(scanInstance.isActive()) {
throw new IllegalArgumentException("Cannot remove active scan instance");
}
scanInstanceEventManager.fireEvent(new RemoveScanInstanceEvent(scanInstance));
if(activeScanInstanceList.contains(scanInstance)) {
activeScanInstanceList.remove(scanInstance);
}
scanInstance.deleteScanInstance();
database.delete(scanInstance);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanInstance.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.alerts;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.apache.http.client.methods.HttpUriRequest;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.alerts.IScanAlert;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.model.alerts.ScanExceptionEvent;
import com.subgraph.vega.api.model.alerts.ScanPauseStateChangedEvent;
import com.subgraph.vega.api.model.alerts.ScanStatusChangeEvent;
import com.subgraph.vega.api.scanner.IScan;
import com.subgraph.vega.internal.model.ModelProperties;
public class ScanInstance implements IScanInstance, Activatable {
private final long scanId;
private final ModelProperties properties;
private volatile Date startTime;
private volatile Date stopTime;
private volatile int scanStatus;
private transient volatile IScan scan;
private transient volatile int activeScanCompletedCount;
private transient volatile int activeScanTotalCount;
private transient volatile String currentPath;
private transient volatile boolean isPaused;
private transient ScanAlertRepository repository;
private transient ScanInstanceAlerts scanAlerts;
private transient EventListenerManager eventManager;
private transient Activator activator;
public ScanInstance(long scanId) {
this.scanId = scanId;
this.scanStatus = SCAN_CONFIG;
this.properties = new ModelProperties();
}
public void setTransientState(ObjectContainer database, ScanAlertRepository repository, ScanAlertFactory alertFactory) {
this.eventManager = new EventListenerManager();
this.repository = repository;
this.scanAlerts = new ScanInstanceAlerts(database, this, eventManager, alertFactory);
}
@Override
public long getScanId() {
activate(ActivationPurpose.READ);
return scanId;
}
@Override
public IScan getScan() {
return scan;
}
@Override
public Date getStartTime() {
activate(ActivationPurpose.READ);
return startTime;
}
@Override
public Date getStopTime() {
activate(ActivationPurpose.READ);
return stopTime;
}
@Override
public IScanAlert createAlert(String type) {
return createAlert(type, null, -1);
}
@Override
public IScanAlert createAlert(String type, String key) {
return createAlert(type, key, -1);
}
@Override
public IScanAlert createAlert(String type, String key, long requestId) {
activate(ActivationPurpose.READ);
return scanAlerts.createAlert(type, key, requestId);
}
@Override
public void addAlert(IScanAlert alert) {
activate(ActivationPurpose.READ);
scanAlerts.addAlert(alert);
}
@Override
public void removeAlert(IScanAlert alert) {
removeAlerts(Arrays.asList(alert));
}
@Override
public void removeAlerts(Collection alerts) {
activate(ActivationPurpose.READ);
scanAlerts.removeAlerts(alerts);
repository.fireRemoveEventsEvent(this, alerts);
}
@Override
public boolean hasAlertKey(String key) {
return (getAlertByKey(key) != null);
}
@Override
public IScanAlert getAlertByKey(String key) {
activate(ActivationPurpose.READ);
return scanAlerts.getAlertByKey(key);
}
@Override
public List getAllAlerts() {
activate(ActivationPurpose.READ);
return scanAlerts.getAllAlerts();
}
@Override
public void addScanEventListenerAndPopulate(IEventHandler listener) {
scanAlerts.addScanEventListenerAndPopulate(listener);
listener.handleEvent(new ScanStatusChangeEvent(this, currentPath, scanStatus, activeScanCompletedCount, activeScanTotalCount));
}
@Override
public void removeScanEventListener(IEventHandler listener) {
eventManager.removeListener(listener);
}
@Override
public int getScanStatus() {
activate(ActivationPurpose.READ);
return scanStatus;
}
@Override
public boolean isActive() {
int scanStatus = getScanStatus();
return (scanStatus == SCAN_PROBING || scanStatus == SCAN_STARTING || scanStatus == SCAN_AUDITING);
}
@Override
public boolean isComplete() {
int scanStatus = getScanStatus();
return (scanStatus == SCAN_CANCELLED || scanStatus == SCAN_COMPLETED);
}
@Override
public String getScanCurrentPath() {
return currentPath;
}
@Override
public int getScanCompletedCount() {
return activeScanCompletedCount;
}
@Override
public int getScanTotalCount() {
return activeScanTotalCount;
}
@Override
public void setScan(IScan scan) {
this.scan = scan;
}
@Override
public void updateScanProgress(String currentPath, int completedCount, int totalCount) {
if(currentPath != null) {
this.currentPath = currentPath;
}
activeScanCompletedCount = completedCount;
activeScanTotalCount = totalCount;
eventManager.fireEvent(new ScanStatusChangeEvent(this, this.currentPath, scanStatus, activeScanCompletedCount, activeScanTotalCount));
}
@Override
public void updateScanProgress(int completedCount, int totalCount) {
activeScanCompletedCount = completedCount;
activeScanTotalCount = totalCount;
eventManager.fireEvent(new ScanStatusChangeEvent(this, currentPath, scanStatus, completedCount, totalCount));
}
@Override
public synchronized void updateScanStatus(int status) {
activate(ActivationPurpose.READ);
if ((status == SCAN_PROBING || status == SCAN_STARTING) && (startTime == null)) {
startTime = new Date();
} else if ( (status == SCAN_COMPLETED || status == SCAN_CANCELLED) && (stopTime == null) ) {
stopTime = new Date();
}
if(status == SCAN_CANCELLED && isPaused) {
isPaused = false;
}
this.scanStatus = status;
eventManager.fireEvent(new ScanStatusChangeEvent(this, currentPath, status, activeScanCompletedCount, activeScanTotalCount));
activate(ActivationPurpose.WRITE);
}
@Override
public void notifyScanException(HttpUriRequest request, Throwable exception) {
eventManager.fireEvent(new ScanExceptionEvent(request, exception));
}
@Override
public void notifyScanPauseState(boolean isPaused) {
this.isPaused = isPaused;
eventManager.fireEvent(new ScanPauseStateChangedEvent(isPaused));
}
@Override
public boolean isScanPaused() {
return isPaused;
}
@Override
public void deleteScanInstance() {
eventManager.clearListeners();
scanAlerts.removeAllAlerts();
}
@Override
public void setProperty(String name, Object value) {
activate(ActivationPurpose.WRITE);
properties.setProperty(name, value);
}
@Override
public void setStringProperty(String name, String value) {
activate(ActivationPurpose.WRITE);
properties.setStringProperty(name, value);
}
@Override
public void setIntegerProperty(String name, int value) {
activate(ActivationPurpose.WRITE);
properties.setIntegerProperty(name, value);
}
@Override
public Object getProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getProperty(name);
}
@Override
public String getStringProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getStringProperty(name);
}
@Override
public Integer getIntegerProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getIntegerProperty(name);
}
@Override
public List propertyKeys() {
activate(ActivationPurpose.READ);
return properties.propertyKeys();
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/alerts/ScanInstanceAlerts.java
================================================
package com.subgraph.vega.internal.model.alerts;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.alerts.IScanAlert;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.model.alerts.NewScanAlertEvent;
public class ScanInstanceAlerts {
private final static Logger logger = Logger.getLogger("alerts");
private final ObjectContainer database;
private final IScanInstance scanInstance;
private final EventListenerManager eventManager;
private final ScanAlertFactory alertFactory;
ScanInstanceAlerts(ObjectContainer database, IScanInstance scanInstance, EventListenerManager eventManager, ScanAlertFactory alertFactory) {
this.database = database;
this.scanInstance = scanInstance;
this.eventManager = eventManager;
this.alertFactory = alertFactory;
}
public IScanAlert createAlert(String type, String key, long requestId) {
return alertFactory.createAlert(key, type, scanInstance, requestId);
}
public void addAlert(IScanAlert alert) {
synchronized(this) {
if(rejectDuplicateAlert(alert)) {
return;
}
database.store(alert);
}
eventManager.fireEvent(new NewScanAlertEvent(alert));
}
public void removeAlerts(Collection alerts) {
synchronized(this) {
for(IScanAlert alert: alerts) {
database.delete(alert);
}
}
}
private boolean rejectDuplicateAlert(IScanAlert alert) {
if(alert.getResource() == null) {
return false;
}
for(ScanAlert sa: getAlertListForResource(alert.getResource())) {
if(sa.equals(alert)) {
return true;
}
}
if(alert.getKey() == null) {
return false;
} else {
return hasAlertKey(alert.getKey());
}
}
private List getAlertListForResource(final String resource) {
return database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(ScanAlert alert) {
return resource.equals(alert.getResource()) && alert.getScanId() == scanInstance.getScanId();
}
});
}
public boolean hasAlertKey(String key) {
return (getAlertByKey(key) != null);
}
public IScanAlert getAlertByKey(String key) {
if(key == null) {
return null;
}
final List results = getAlertListForKey(key);
if(results.size() == 0) {
return null;
}
if(results.size() > 1) {
logger.warning("Multiple alert model entries for key: "+ key);
}
return results.get(0);
}
private List getAlertListForKey(final String key) {
return database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(ScanAlert alert) {
return key.equals(alert.getKey()) && alert.getScanId() == scanInstance.getScanId();
}
});
}
public List getAllAlerts() {
return database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IScanAlert alert) {
return alert.getScanId() == scanInstance.getScanId();
}
});
}
public void removeAllAlerts() {
final List all = new ArrayList(getAllAlerts());
removeAlerts(all);
}
public void addScanEventListenerAndPopulate(IEventHandler listener) {
List allAlerts = null;
synchronized(this) {
allAlerts = getAllAlerts();
eventManager.addListener(listener);
}
for(IScanAlert alert: allAlerts) {
listener.handleEvent(new NewScanAlertEvent(alert));
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/AbstractCondition.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionIntegerMatchAction;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionRangeMatchAction;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionStringMatchAction;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.internal.model.conditions.match.IHttpConditionMatchActionEx;
public abstract class AbstractCondition implements IHttpCondition, Activatable {
protected IHttpConditionMatchActionEx matchAction;
private boolean isEnabled;
private boolean isSufficient;
protected AbstractCondition(IHttpConditionMatchAction matchAction) {
this.matchAction = (IHttpConditionMatchActionEx) matchAction;
this.isEnabled = true;
}
@Override
public IHttpConditionMatchAction getMatchAction() {
activate(ActivationPurpose.READ);
return matchAction;
}
@Override
public void setMatchAction(IHttpConditionMatchAction matchAction) {
activate(ActivationPurpose.READ);
if(matchAction instanceof IHttpConditionMatchActionEx) {
this.matchAction = (IHttpConditionMatchActionEx) matchAction;
activate(ActivationPurpose.WRITE);
}
}
@Override
public boolean matches(IRequestLogRecord record) {
return matches(record.getRequest(), record.getResponse());
}
@Override
public boolean isEnabled() {
activate(ActivationPurpose.READ);
return isEnabled;
}
@Override
public void setEnabled(boolean state) {
activate(ActivationPurpose.READ);
isEnabled = state;
activate(ActivationPurpose.WRITE);
}
public IHttpCondition createCopy() {
activate(ActivationPurpose.READ);
return getType().createConditionInstance(matchAction.createCopy());
}
protected boolean matchesString(String value) {
activate(ActivationPurpose.READ);
if(matchAction instanceof IHttpConditionStringMatchAction) {
return ((IHttpConditionStringMatchAction) matchAction).matchesValue(value);
}
throw new IllegalStateException("Expecting an IHttpConditionStringMatchingAction, got"+ matchAction);
}
protected boolean matchesInteger(int value) {
activate(ActivationPurpose.READ);
if(matchAction instanceof IHttpConditionIntegerMatchAction) {
return ((IHttpConditionIntegerMatchAction) matchAction).matchesValue(value);
} else if(matchAction instanceof IHttpConditionRangeMatchAction) {
return ((IHttpConditionRangeMatchAction) matchAction).matchesValue(value);
}
throw new IllegalStateException("Expecting an IHttpConditonIntegerMatchAction or IHttpConditionRangeMatchAction, got"+ matchAction);
}
protected Constraint constrainQuery(Query query) {
activate(ActivationPurpose.READ);
return matchAction.constrainQuery(query);
}
public String getValueString() {
activate(ActivationPurpose.READ);
return matchAction.toString();
}
@Override
public boolean isInternal() {
return false;
}
@Override
public boolean isSufficient() {
activate(ActivationPurpose.READ);
return isSufficient;
}
@Override
public void setSufficient(boolean value) {
activate(ActivationPurpose.READ);
isSufficient = value;
activate(ActivationPurpose.WRITE);
}
public abstract Constraint filterRequestLogQuery(Query query);
private transient Activator activator;
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionHeader.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.Header;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.activation.ActivationPurpose;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.StringMatchActionSet;
public class ConditionHeader extends AbstractCondition {
static private transient IHttpConditionType requestConditionType;
static private transient IHttpConditionType responseConditionType;
static IHttpConditionType getRequestConditionType() {
synchronized (ConditionHeader.class) {
if(requestConditionType == null)
createTypes();
return requestConditionType;
}
}
static IHttpConditionType getResponseConditionType() {
synchronized(ConditionHeader.class) {
if(responseConditionType == null)
createTypes();
return responseConditionType;
}
}
private static void createTypes() {
requestConditionType = createType("request header", true);
responseConditionType = createType("response header", false);
}
private static IHttpConditionType createType(String label, final boolean flag) {
return new ConditionType(label, new StringMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionHeader(flag, matchAction);
}
};
}
private final boolean matchRequestHeader;
ConditionHeader(boolean matchRequestHeader, IHttpConditionMatchAction matchAction) {
super(matchAction);
this.matchRequestHeader = matchRequestHeader;
}
@Override
public boolean matches(HttpRequest request) {
activate(ActivationPurpose.READ);
if(matchRequestHeader)
return matchesString(headersToString(request));
else
return false;
}
@Override
public boolean matches(HttpResponse response) {
activate(ActivationPurpose.READ);
if(!matchRequestHeader)
return matchesString(headersToString(response));
else
return false;
}
private String headersToString(HttpMessage message) {
if(message == null)
return "";
final StringBuilder sb = new StringBuilder();
for(Header h: message.getAllHeaders()) {
sb.append(h.getName());
sb.append(": ");
sb.append(h.getValue());
sb.append("\r\n");
}
return sb.toString();
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
activate(ActivationPurpose.READ);
if(matchRequestHeader)
return matchesString(headersToString(request));
else
return matchesString(headersToString(response));
}
@Override
public IHttpConditionType getType() {
activate(ActivationPurpose.READ);
if(matchRequestHeader)
return getRequestConditionType();
else
return getResponseConditionType();
}
@Override
public Constraint filterRequestLogQuery(Query query) {
activate(ActivationPurpose.READ);
if(matchRequestHeader)
return constrainQuery(query.descend("requestHeaders"));
else
return constrainQuery(query.descend("responseHeaders"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionHostname.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.StringMatchActionSet;
public class ConditionHostname extends AbstractCondition {
static private transient IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized(ConditionHostname.class) {
if(conditionType == null)
conditionType = createType();
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("hostname", new StringMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionHostname(matchAction);
}
};
}
private ConditionHostname(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public boolean matches(HttpRequest request) {
final String hostname = getRequestHostname(request);
if(hostname == null) {
return false;
}
return matchesString(hostname);
}
private String getRequestHostname(HttpRequest request) {
Header hostHeader = request.getFirstHeader("Host");
if(hostHeader == null) {
return null;
}
return hostHeader.getValue();
}
@Override
public boolean matches(HttpResponse response) {
return false;
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return matches(request);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("hostname"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionPath.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.StringMatchActionSet;
public class ConditionPath extends AbstractCondition {
static private transient IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized(ConditionPath.class) {
if(conditionType == null)
conditionType = createType();
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("request path", new StringMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionPath(matchAction);
}
};
}
private ConditionPath(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public boolean matches(HttpRequest request) {
return matchesString(request.getRequestLine().getUri());
}
@Override
public boolean matches(HttpResponse response) {
return false;
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return matches(request);
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("requestPath"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionRequestId.java
================================================
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.internal.model.conditions.match.IntegerMatchActionSet;
public class ConditionRequestId extends AbstractCondition {
private transient static IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized (ConditionRequestId.class) {
if(conditionType == null) {
conditionType = createType();
}
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("request id", new IntegerMatchActionSet(), true) {
@Override
public IHttpCondition createConditionInstance(
IHttpConditionMatchAction matchAction) {
return new ConditionRequestId(matchAction);
}
};
}
private ConditionRequestId(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public boolean matches(IRequestLogRecord record) {
return matchesInteger((int) record.getRequestId());
}
@Override
public boolean matches(HttpRequest request) {
return false;
}
@Override
public boolean matches(HttpResponse response) {
return false;
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return false;
}
@Override
public boolean isInternal() {
return true;
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("requestId"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionRequestMethod.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.StringMatchActionSet;
public class ConditionRequestMethod extends AbstractCondition {
static private transient IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized(ConditionRequestMethod.class) {
if(conditionType == null)
conditionType = createType();
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("request method", new StringMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionRequestMethod(matchAction);
}
};
}
protected ConditionRequestMethod(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public boolean matches(HttpRequest request) {
if(request == null)
return false;
final String method = request.getRequestLine().getMethod();
return matchesString(method);
}
@Override
public boolean matches(HttpResponse response) {
return false;
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return matches(request);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("requestMethod"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionResponseLength.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.IntegerMatchActionSet;
public class ConditionResponseLength extends AbstractCondition {
private static transient IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized (ConditionResponseLength.class) {
if(conditionType == null)
conditionType = createType();
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("response length", new IntegerMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionResponseLength(matchAction);
}
};
}
private ConditionResponseLength(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public boolean matches(HttpRequest request) {
return false;
}
@Override
public boolean matches(HttpResponse response) {
final int length = (int) getLengthFromResponse(response);
return matchesInteger(length);
}
private long getLengthFromResponse(HttpResponse response) {
final Header lengthHeader = response.getFirstHeader("Content-Length");
if(lengthHeader != null) {
try {
return Long.parseLong(lengthHeader.getValue());
} catch (NumberFormatException e) {
return 0;
}
}
if(response.getEntity() == null)
return 0;
return response.getEntity().getContentLength();
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return matches(response);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("responseLength"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionResponseStatusCode.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.IntegerMatchActionSet;
public class ConditionResponseStatusCode extends AbstractCondition {
static private transient IHttpConditionType conditionType;
static IHttpConditionType getConditionType() {
synchronized(ConditionResponseStatusCode.class) {
if(conditionType == null)
conditionType = createType();
return conditionType;
}
}
private static IHttpConditionType createType() {
return new ConditionType("response status code", new IntegerMatchActionSet()) {
@Override
public IHttpCondition createConditionInstance(IHttpConditionMatchAction matchAction) {
return new ConditionResponseStatusCode(matchAction);
}
};
}
private ConditionResponseStatusCode(IHttpConditionMatchAction matchAction) {
super(matchAction);
}
@Override
public boolean matches(HttpRequest request) {
return false;
}
@Override
public boolean matches(HttpResponse response) {
if(response == null)
return false;
return matchesInteger(response.getStatusLine().getStatusCode());
}
@Override
public boolean matches(HttpRequest request, HttpResponse response) {
return matches(response);
}
@Override
public IHttpConditionType getType() {
return getConditionType();
}
@Override
public Constraint filterRequestLogQuery(Query query) {
return constrainQuery(query.descend("responseCode"));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/ConditionType.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import java.util.List;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.internal.model.conditions.match.IMatchActionSet;
public abstract class ConditionType implements IHttpConditionType {
private final String name;
private final boolean isInternal;
private final IMatchActionSet matchActionSet;
ConditionType(String name, IMatchActionSet matchActionSet) {
this(name, matchActionSet, false);
}
ConditionType(String name, IMatchActionSet matchActionSet, boolean isInternal) {
this.name = name;
this.isInternal = isInternal;
this.matchActionSet = matchActionSet;
}
@Override
public String getName() {
return name;
}
@Override
public boolean isInternal() {
return isInternal;
}
@Override
public List getMatchActions() {
return matchActionSet.createMatchActions();
}
@Override
public IHttpConditionMatchAction getMatchActionByName(String name) {
for(IHttpConditionMatchAction action: getMatchActions()) {
if(action.getLabel().equals(name)) {
return action;
}
}
return null;
}
public boolean equals(Object other) {
if(this == other)
return true;
if(other instanceof ConditionType) {
ConditionType that = (ConditionType) other;
return this.name.equals(that.name);
}
return false;
}
public int hashCode() {
return name.hashCode();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/HttpConditionManager.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.events.CancellableObjectEventArgs;
import com.db4o.events.Event4;
import com.db4o.events.EventListener4;
import com.db4o.events.EventRegistry;
import com.db4o.events.EventRegistryFactory;
import com.subgraph.vega.api.events.NamedEventListenerManager;
import com.subgraph.vega.api.model.conditions.ConditionSetChanged;
import com.subgraph.vega.api.model.conditions.IHttpConditionManager;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
import com.subgraph.vega.api.model.conditions.IHttpConditionType;
public class HttpConditionManager implements IHttpConditionManager {
private final ObjectContainer database;
private final List conditionTypes;
private final NamedEventListenerManager conditionSetChangedManager;
public HttpConditionManager(ObjectContainer database, NamedEventListenerManager conditionSetChangedManager) {
this.database = database;
this.conditionTypes = createConditionTypes();
this.conditionSetChangedManager = conditionSetChangedManager;
final EventRegistry registry = EventRegistryFactory.forObjectContainer(database);
registry.activating().addListener(new EventListener4() {
@Override
public void onEvent(Event4 e, CancellableObjectEventArgs args) {
final Object ob = args.object();
if(ob instanceof HttpConditionSet)
((HttpConditionSet)ob).setConditionManager(HttpConditionManager.this);
else if(ob instanceof HttpConditionSetMap)
((HttpConditionSetMap)ob).setConditionManager(HttpConditionManager.this);
}
});
notifyAllChanged();
}
private List createConditionTypes() {
final List types = new ArrayList();
types.add(ConditionHostname.getConditionType());
types.add(ConditionRequestMethod.getConditionType());
types.add(ConditionHeader.getRequestConditionType());
types.add(ConditionPath.getConditionType());
types.add(ConditionHeader.getResponseConditionType());
types.add(ConditionResponseLength.getConditionType());
types.add(ConditionResponseStatusCode.getConditionType());
types.add(ConditionRequestId.getConditionType());
return types;
}
public void notifyClosed() {
synchronized(conditionSetChangedManager) {
conditionSetChangedManager.fireAllKeys(new ConditionSetChanged(null));
}
}
private void notifyAllChanged() {
synchronized(conditionSetChangedManager) {
for(String conditionSetName: conditionSetChangedManager.getAllKeys()) {
IHttpConditionSet conditionSet = getConditionSet(conditionSetName);
conditionSetChangedManager.fireEvent(conditionSetName, new ConditionSetChanged(conditionSet));
}
}
}
void notifyConditionSetChanged(IHttpConditionSet conditionSet) {
conditionSetChangedManager.fireEvent(conditionSet.getName(), new ConditionSetChanged(conditionSet));
}
@Override
public IHttpConditionSet getConditionSet(String name) {
return getConditionSetMap().getConditionSet(name);
}
@Override
public IHttpConditionSet getConditionSetCopy(String name) {
return getConditionSetMap().getConditionSetCopy(name);
}
@Override
public void saveConditionSet(String name, IHttpConditionSet conditionSet) {
synchronized(conditionSetChangedManager) {
getConditionSetMap().saveConditionSet(name, conditionSet);
conditionSetChangedManager.fireEvent(name, new ConditionSetChanged(conditionSet));
}
}
private HttpConditionSetMap getConditionSetMap() {
synchronized(this) {
final List result = database.query(HttpConditionSetMap.class);
if(result.size() == 1)
return result.get(0);
else if(result.size() > 1)
throw new IllegalStateException("Duplicate HttpConditionSetMap records in database");
HttpConditionSetMap map = new HttpConditionSetMap(this);
database.store(map);
return map;
}
}
@Override
public List getConditionTypes() {
return getConditionTypes(false);
}
@Override
public List getConditionTypes(boolean includeInternal) {
if(includeInternal) {
return Collections.unmodifiableList(new ArrayList(conditionTypes));
}
final List result = new ArrayList();
for(IHttpConditionType type: conditionTypes) {
if(!type.isInternal()) {
result.add(type);
}
}
return Collections.unmodifiableList(result);
}
@Override
public IHttpConditionType getConditionTypeByName(String name) {
for(IHttpConditionType type: getConditionTypes(true)) {
if(type.getName().equals(name)) {
return type;
}
}
return null;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/HttpConditionSet.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.conditions.IHttpCondition;
import com.subgraph.vega.api.model.conditions.IHttpConditionManager;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
public class HttpConditionSet implements IHttpConditionSet, Activatable {
private final String name;
private final List conditionList = new ActivatableArrayList();
private boolean matchOnEmptySet;
private transient Object lock;
private transient HttpConditionManager conditionManager;
private transient List temporaryConditions;
private transient List allConditions;
HttpConditionSet(String name, HttpConditionManager conditionManager) {
this(name, conditionManager, null);
}
HttpConditionSet(String name, HttpConditionManager conditionManager, IHttpConditionSet copyMe) {
this.name = name;
this.conditionManager = conditionManager;
this.temporaryConditions = new ArrayList();
this.lock = new Object();
if(copyMe != null) {
for(IHttpCondition c: copyMe.getAllConditions(true)) {
conditionList.add(c.createCopy());
}
for(IHttpCondition c: copyMe.getAllTemporaryConditions(true)) {
temporaryConditions.add(c.createCopy());
}
this.allConditions = new ArrayList();
updateAllConditions();
}
}
private void updateAllConditions() {
synchronized (lock) {
if (allConditions == null) {
allConditions = new ArrayList();
}
else {
allConditions.clear();
}
allConditions.addAll(conditionList);
allConditions.addAll(temporaryConditions);
}
}
private List getAllConditionsList() {
if(allConditions == null) {
allConditions = new ArrayList();
updateAllConditions();
}
return allConditions;
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public boolean matchesAll(IRequestLogRecord record) {
activate(ActivationPurpose.READ);
return matchesAllConditions(record);
}
@Override
public boolean matchesAll(HttpRequest request, HttpResponse response) {
activate(ActivationPurpose.READ);
return matchesAllConditions(request, response);
}
@Override
public boolean matchesAny(IRequestLogRecord record) {
activate(ActivationPurpose.READ);
return matchesAnyCondition(record);
}
@Override
public boolean matchesAny(HttpRequest request, HttpResponse response) {
activate(ActivationPurpose.READ);
return matchesAnyCondition(request, response);
}
private boolean matchesAllConditions(IRequestLogRecord record) {
synchronized(lock) {
if(getAllConditionsList().size() == 0) {
return matchOnEmptySet;
}
for(IHttpCondition c: getAllConditionsList()) {
if(c.isEnabled() && !c.matches(record)) {
return false;
}
}
return true;
}
}
private boolean matchesAllConditions(HttpRequest request, HttpResponse response) {
activate(ActivationPurpose.READ);
synchronized(lock) {
if (getAllConditionsList().size() == 0) {
return matchOnEmptySet;
}
for(IHttpCondition c: getAllConditionsList()) {
if(c.isEnabled() && !c.matches(request, response))
return false;
}
return true;
}
}
private boolean matchesAnyCondition(IRequestLogRecord record) {
synchronized (lock) {
if(getAllConditionsList().size() == 0) {
return matchOnEmptySet;
}
for(IHttpCondition c: getAllConditionsList()) {
if(c.isEnabled() && c.matches(record)) {
return true;
}
}
}
return false;
}
private boolean matchesAnyCondition(HttpRequest request, HttpResponse response) {
activate(ActivationPurpose.READ);
synchronized(lock) {
if (getAllConditionsList().size() == 0) {
return matchOnEmptySet;
}
for(IHttpCondition c: getAllConditionsList()) {
if(c.isEnabled() && c.matches(request, response)) {
return true;
}
}
return false;
}
}
@Override
public void notifyChanged() {
conditionManager.notifyConditionSetChanged(this);
}
@Override
public boolean hasActiveConditions(boolean includeInternal) {
return !(getAllTemporaryConditions(includeInternal).isEmpty() && getAllConditions(includeInternal).isEmpty());
}
@Override
public void appendCondition(IHttpCondition condition, boolean notify) {
activate(ActivationPurpose.READ);
conditionList.add(condition);
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public void removeCondition(IHttpCondition condition, boolean notify) {
activate(ActivationPurpose.READ);
conditionList.remove(condition);
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public void clearConditions(boolean notify) {
activate(ActivationPurpose.READ);
conditionList.clear();
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public List getAllConditions() {
return getAllConditions(false);
}
@Override
public List getAllConditions(boolean includeInternal) {
activate(ActivationPurpose.READ);
if(!includeInternal) {
return Collections.unmodifiableList(new ArrayList(conditionList));
}
final List result = new ArrayList();
for(IHttpCondition condition: conditionList) {
if(!condition.isInternal()) {
result.add(condition);
}
}
return Collections.unmodifiableList(result);
}
@Override
public void appendTemporaryCondition(IHttpCondition condition, boolean notify) {
temporaryConditions.add(condition);
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public void removeTemporaryCondition(IHttpCondition condition, boolean notify) {
temporaryConditions.remove(condition);
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public void clearTemporaryConditions(boolean notify) {
temporaryConditions.clear();
updateAllConditions();
if(notify) {
conditionManager.notifyConditionSetChanged(this);
}
}
@Override
public List getAllTemporaryConditions(boolean includeInternal) {
if(!includeInternal) {
return Collections.unmodifiableList(new ArrayList(temporaryConditions));
}
final List result = new ArrayList();
for(IHttpCondition condition: temporaryConditions) {
if(!condition.isInternal()) {
result.add(condition);
}
}
return Collections.unmodifiableList(result);
}
@Override
public IHttpConditionManager getConditionManager() {
return conditionManager;
}
void setConditionManager(HttpConditionManager conditionManager) {
this.conditionManager = conditionManager;
this.temporaryConditions = new ArrayList();
this.lock = new Object();
}
public List filterRequestLog(ObjectContainer db) {
activate(ActivationPurpose.READ);
if(!hasRecords(db)) {
return Collections.emptyList();
} else {
return executeFilterQuery(db);
}
}
public ObjectSet executeFilterQuery(ObjectContainer db) {
activate(ActivationPurpose.READ);
final Query query = db.query();
query.constrain(IRequestLogRecord.class);
Constraint orChain = null;
Constraint andChain = null;
for(IHttpCondition c: getAllConditionsList()) {
Constraint result = ((AbstractCondition)c).filterRequestLogQuery(query);
if(c.isSufficient()) {
orChain = processConstraintChain(result, orChain, false);
} else {
andChain = processConstraintChain(result, andChain, true);
}
}
if(orChain != null && andChain != null) {
orChain.or(andChain);
}
// If there are only 'sufficient' conditions, then don't filter at all
if(andChain == null) {
final Query q = db.query();
q.constrain(IRequestLogRecord.class);
return q.execute();
}
return query.execute();
}
private Constraint processConstraintChain(Constraint newConstraint, Constraint chain, boolean useAnd) {
if(newConstraint == null) {
return chain;
} else if(chain == null) {
return newConstraint;
} else if(useAnd) {
return chain.and(newConstraint);
} else {
return chain.or(newConstraint);
}
}
private boolean hasRecords(ObjectContainer db) {
final Query query = db.query();
query.constrain(IRequestLogRecord.class);
return query.execute().hasNext();
}
@Override
public void setMatchOnEmptySet(boolean flag) {
activate(ActivationPurpose.READ);
matchOnEmptySet = flag;
activate(ActivationPurpose.WRITE);
}
private transient Activator activator;
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/HttpConditionSetMap.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions;
import java.util.Map;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableHashMap;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
public class HttpConditionSetMap implements Activatable {
private final Map conditionSetMap = new ActivatableHashMap();
private transient Activator activator;
private transient HttpConditionManager conditionManager;
public HttpConditionSetMap(HttpConditionManager conditionManager) {
this.conditionManager = conditionManager;
}
void setConditionManager(HttpConditionManager conditionManager) {
this.conditionManager = conditionManager;
}
IHttpConditionSet getConditionSet(String name) {
activate(ActivationPurpose.READ);
synchronized(conditionSetMap) {
if(!conditionSetMap.containsKey(name))
conditionSetMap.put(name, new HttpConditionSet(name, conditionManager));
return conditionSetMap.get(name);
}
}
IHttpConditionSet getConditionSetCopy(String name) {
activate(ActivationPurpose.READ);
synchronized(conditionSetMap) {
return new HttpConditionSet(name, conditionManager, conditionSetMap.get(name));
}
}
void saveConditionSet(String name, IHttpConditionSet conditionSet) {
activate(ActivationPurpose.READ);
synchronized (conditionSet) {
conditionSetMap.put(name, conditionSet);
}
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/ContainsAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class ContainsAction extends StringMatchAction {
private ContainsAction(String value) {
super(value);
}
public ContainsAction() {
}
@Override
public String getLabel() {
return "contains";
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).contains();
}
@Override
public IHttpConditionMatchAction createCopy() {
return new ContainsAction(stringValue);
}
@Override
public boolean matchesValue(String value) {
return matchesContains(value);
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/DoesNotContainAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class DoesNotContainAction extends StringMatchAction {
private DoesNotContainAction(String value) {
super(value);
}
public DoesNotContainAction() {
}
@Override
public String getLabel() {
return "does not contain";
}
@Override
public IHttpConditionMatchAction createCopy() {
return new DoesNotContainAction(stringValue);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).contains().not();
}
@Override
public boolean matchesValue(String value) {
return !matchesContains(value);
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/DoesNotEndWithAction.java
================================================
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class DoesNotEndWithAction extends StringMatchAction {
public DoesNotEndWithAction() {
}
private DoesNotEndWithAction(String value) {
super(value);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).endsWith(true).not();
}
@Override
public IHttpConditionMatchAction createCopy() {
return new DoesNotEndWithAction(stringValue);
}
@Override
public String getLabel() {
return "does not end with";
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
@Override
public boolean matchesValue(String value) {
if(value == null) {
return true;
}
return !value.endsWith(stringValue);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/DoesNotMatchRegexAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.regex.Pattern;
import com.db4o.query.Evaluation;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class DoesNotMatchRegexAction extends RegexMatchAction {
private DoesNotMatchRegexAction(String value) {
super(value);
}
DoesNotMatchRegexAction() {}
@Override
public String getLabel() {
return "does not match regex";
}
@Override
public boolean matchesValue(String value) {
return !matchesRegex(value);
}
@Override
public IHttpConditionMatchAction createCopy() {
return new DoesNotMatchRegexAction(getPatternString());
}
@Override
protected Evaluation createQueryEvaluation(Pattern pattern) {
return new RegexQueryEvaluation(pattern, true);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/DoesNotStartWithAction.java
================================================
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class DoesNotStartWithAction extends StringMatchAction {
public DoesNotStartWithAction() {
}
private DoesNotStartWithAction(String value) {
super(value);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).startsWith(true).not();
}
@Override
public IHttpConditionMatchAction createCopy() {
return new DoesNotStartWithAction(stringValue);
}
@Override
public String getLabel() {
return "does not start with";
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
@Override
public boolean matchesValue(String value) {
if(value == null) {
return true;
}
return !value.startsWith(stringValue);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/EndsWithAction.java
================================================
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class EndsWithAction extends StringMatchAction {
public EndsWithAction() {
}
private EndsWithAction(String value) {
super(value);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).endsWith(true);
}
@Override
public IHttpConditionMatchAction createCopy() {
return new EndsWithAction(stringValue);
}
@Override
public String getLabel() {
return "ends with";
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
@Override
public boolean matchesValue(String value) {
if(value == null) {
return false;
}
return value.endsWith(stringValue);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/EqualsAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class EqualsAction extends IntegerMatchAction {
EqualsAction() {
this(0);
}
private EqualsAction(int value) {
super(value);
}
@Override
public String getLabel() {
return "equals";
}
@Override
public IHttpConditionMatchAction createCopy() {
return new EqualsAction(integerValue);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(integerValue).equal();
}
@Override
public boolean matchesValue(int value) {
return value == integerValue;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IHttpConditionMatchActionEx.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public interface IHttpConditionMatchActionEx extends IHttpConditionMatchAction {
Constraint constrainQuery(Query query);
IHttpConditionMatchAction createCopy();
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IMatchActionSet.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.List;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public interface IMatchActionSet {
List createMatchActions();
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IntegerMatchAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionIntegerMatchAction;
public abstract class IntegerMatchAction implements IHttpConditionIntegerMatchAction, IHttpConditionMatchActionEx {
protected int integerValue;
IntegerMatchAction() {
}
protected IntegerMatchAction(int value) {
integerValue = value;
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_INTEGER;
}
@Override
public void setInteger(int value) {
integerValue = value;
}
@Override
public String getArgumentAsString() {
return Integer.toString(integerValue);
}
@Override
public boolean setArgumentFromString(String value) {
final Integer n = stringToInteger(value);
if(n == null)
return false;
integerValue = n;
return true;
}
@Override
public boolean isValidArgumentString(String value) {
return stringToInteger(value) != null;
}
private Integer stringToInteger(String s) {
try {
int n = Integer.parseInt(s.trim());
return (n < 0) ? (null) : (n);
} catch (NumberFormatException e) {
return null;
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IntegerMatchActionSet.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.ArrayList;
import java.util.List;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class IntegerMatchActionSet implements IMatchActionSet {
@Override
public List createMatchActions() {
final List actions = new ArrayList();
actions.add(new EqualsAction());
actions.add(new IsGreaterThanAction());
actions.add(new IsLessThanAction());
actions.add(new IsInsideRangeAction());
return actions;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IsGreaterThanAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class IsGreaterThanAction extends IntegerMatchAction {
IsGreaterThanAction() {
}
private IsGreaterThanAction(int value) {
super(value);
}
@Override
public String getLabel() {
return "is greater than";
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(integerValue).greater();
}
@Override
public IHttpConditionMatchAction createCopy() {
return new IsGreaterThanAction(integerValue);
}
@Override
public boolean matchesValue(int value) {
return value > integerValue;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IsInsideRangeAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionRangeMatchAction;
public class IsInsideRangeAction implements IHttpConditionRangeMatchAction, IHttpConditionMatchActionEx {
private int rangeLowValue;
private int rangeHighValue;
IsInsideRangeAction() {}
private static class Range {
final int low;
final int high;
Range(int low, int high) {
this.low = low;
this.high = high;
}
}
private IsInsideRangeAction(int low, int high) {
this.rangeLowValue = low;
this.rangeHighValue = high;
}
@Override
public String getLabel() {
return "is inside range";
}
@Override
public void setRange(int rangeLow, int rangeHigh) {
this.rangeLowValue = rangeLow;
this.rangeHighValue = rangeHigh;
}
@Override
public boolean matchesValue(int value) {
return value >= rangeLowValue && value < rangeHighValue;
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(rangeLowValue).greater().or(query.constrain(rangeLowValue).equal()).and(query.constrain(rangeHighValue).smaller());
}
@Override
public IHttpConditionMatchAction createCopy() {
return new IsInsideRangeAction(rangeLowValue, rangeHighValue);
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_RANGE;
}
@Override
public String getArgumentAsString() {
return rangeLowValue + " - "+ rangeHighValue;
}
@Override
public boolean setArgumentFromString(String value) {
final Range range = stringToRange(value);
if(range == null)
return false;
rangeLowValue = range.low;
rangeHighValue = range.high;
return true;
}
@Override
public boolean isValidArgumentString(String value) {
return stringToRange(value) != null;
}
private Range stringToRange(String s) {
String[] parts = s.split("-");
if(parts.length != 2)
return null;
Integer low = stringToInteger(parts[0]);
Integer high = stringToInteger(parts[1]);
if(low == null || high == null || low > high)
return null;
return new Range(low, high);
}
private Integer stringToInteger(String s) {
try {
int n = Integer.parseInt(s.trim());
return (n < 0) ? (null) : (n);
} catch (NumberFormatException e) {
return null;
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/IsLessThanAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class IsLessThanAction extends IntegerMatchAction {
IsLessThanAction() {
}
private IsLessThanAction(int value) {
super(value);
}
@Override
public String getLabel() {
return "is less than";
}
@Override
public boolean matchesValue(int value) {
return value < integerValue;
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(integerValue).smaller();
}
@Override
public IHttpConditionMatchAction createCopy() {
return new IsLessThanAction(integerValue);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/MatchesRegexAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.regex.Pattern;
import com.db4o.query.Evaluation;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class MatchesRegexAction extends RegexMatchAction {
private MatchesRegexAction(String value) {
super(value);
}
MatchesRegexAction() {
}
@Override
public String getLabel() {
return "matches regex";
}
@Override
public IHttpConditionMatchAction createCopy() {
return new MatchesRegexAction(getPatternString());
}
@Override
public boolean matchesValue(String value) {
return matchesRegex(value);
}
@Override
protected Evaluation createQueryEvaluation(Pattern pattern) {
return new RegexQueryEvaluation(pattern, false);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/RegexMatchAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import com.db4o.query.Constraint;
import com.db4o.query.Evaluation;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionStringMatchAction;
public abstract class RegexMatchAction implements IHttpConditionStringMatchAction, IHttpConditionMatchActionEx {
private String patternString;
private transient Pattern pattern;
private transient boolean patternCompileFailed;
private transient Evaluation regexConstraint;
protected RegexMatchAction() {
}
protected RegexMatchAction(String value) {
patternString = value;
}
protected String getPatternString() {
return patternString;
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_REGEX;
}
@Override
public String getArgumentAsString() {
return patternString;
}
@Override
public boolean setArgumentFromString(String value) {
if(!isValidArgumentString(value))
return false;
setString(value);
return true;
}
@Override
public boolean isValidArgumentString(String value) {
return createRegexPattern(value) != null;
}
protected boolean matchesRegex(String value) {
final Pattern regex = getRegexPattern();
if(regex == null || value == null) {
return false;
}
return regex.matcher(value).find();
}
@Override
public Constraint constrainQuery(Query query) {
final Pattern p = getRegexPattern();
if(p == null) {
return null;
}
return query.constrain(getRegexConstraint(p));
}
protected abstract Evaluation createQueryEvaluation(Pattern pattern);
private Evaluation getRegexConstraint(Pattern pattern) {
synchronized(this) {
if(regexConstraint == null) {
regexConstraint = createQueryEvaluation(pattern);
}
return regexConstraint;
}
}
private Pattern getRegexPattern() {
if(patternCompileFailed)
return null;
synchronized(this) {
if(pattern == null) {
if((pattern = createRegexPattern(patternString)) == null)
patternCompileFailed = true;
}
return pattern;
}
}
private Pattern createRegexPattern(String str) {
try {
return Pattern.compile(str);
} catch (PatternSyntaxException e) {
return null;
}
}
@Override
public void setString(String value) {
this.patternString = value;
this.pattern = null;
this.patternCompileFailed = false;
this.regexConstraint = null;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/RegexQueryEvaluation.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.regex.Pattern;
import com.db4o.query.Candidate;
import com.db4o.query.Evaluation;
public class RegexQueryEvaluation implements Evaluation {
private static final long serialVersionUID = 1L;
private final Pattern pattern;
private final boolean invertMatch;
public RegexQueryEvaluation(Pattern pattern, boolean invertMatch) {
this.pattern = pattern;
this.invertMatch = invertMatch;
}
@Override
public void evaluate(Candidate candidate) {
final String value = (String) candidate.getObject();
final boolean result = pattern.matcher(value).find();
candidate.include(result ^ invertMatch);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/StartsWithAction.java
================================================
package com.subgraph.vega.internal.model.conditions.match;
import com.db4o.query.Constraint;
import com.db4o.query.Query;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class StartsWithAction extends StringMatchAction {
public StartsWithAction() {
}
private StartsWithAction(String value) {
super(value);
}
@Override
public Constraint constrainQuery(Query query) {
return query.constrain(stringValue).startsWith(true);
}
@Override
public IHttpConditionMatchAction createCopy() {
return new StartsWithAction(stringValue);
}
@Override
public String getLabel() {
return "starts with";
}
@Override
public MatchActionArgumentType getArgumentType() {
return MatchActionArgumentType.ARGUMENT_STRING;
}
@Override
public boolean matchesValue(String value) {
if(value == null) {
return false;
}
return value.startsWith(stringValue);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/StringMatchAction.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionStringMatchAction;
public abstract class StringMatchAction implements IHttpConditionMatchActionEx, IHttpConditionStringMatchAction {
protected String stringValue;
protected StringMatchAction() {}
protected StringMatchAction(String value) {
this.stringValue = value;
}
@Override
public String getArgumentAsString() {
return stringValue;
}
@Override
public boolean setArgumentFromString(String value) {
stringValue = value;
return true;
}
@Override
public boolean isValidArgumentString(String value) {
return true;
}
protected boolean matchesContains(String value) {
if(value == null) {
return false;
}
return value.contains(stringValue);
}
@Override
public void setString(String value) {
this.stringValue = value;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/conditions/match/StringMatchActionSet.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.conditions.match;
import java.util.ArrayList;
import java.util.List;
import com.subgraph.vega.api.model.conditions.match.IHttpConditionMatchAction;
public class StringMatchActionSet implements IMatchActionSet {
@Override
public List createMatchActions() {
final List actions = new ArrayList();
actions.add(new ContainsAction());
actions.add(new DoesNotContainAction());
actions.add(new MatchesRegexAction());
actions.add(new DoesNotMatchRegexAction());
actions.add(new StartsWithAction());
actions.add(new DoesNotStartWithAction());
actions.add(new EndsWithAction());
actions.add(new DoesNotEndWithAction());
return actions;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/AbstractAuthMethod.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.identity;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.identity.IAuthMethod;
public abstract class AbstractAuthMethod implements IAuthMethod, Activatable {
private transient Activator activator;
private AuthMethodType type;
protected AbstractAuthMethod(AuthMethodType type) {
this.type = type;
}
@Override
public AuthMethodType getType() {
activate(ActivationPurpose.READ);
return type;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/AuthMethodHttpMacro.java
================================================
package com.subgraph.vega.internal.model.identity;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.api.model.identity.IAuthMethod;
import com.subgraph.vega.api.model.identity.IAuthMethodHttpMacro;
import com.subgraph.vega.api.model.macros.IHttpMacro;
public class AuthMethodHttpMacro extends AbstractAuthMethod implements IAuthMethodHttpMacro {
private IHttpMacro macro;
protected AuthMethodHttpMacro() {
super(IAuthMethod.AuthMethodType.AUTH_METHOD_HTTP_MACRO);
}
@Override
public void setMacro(IHttpMacro macro) {
activate(ActivationPurpose.READ);
this.macro = macro;
activate(ActivationPurpose.WRITE);
}
@Override
public IHttpMacro getMacro() {
activate(ActivationPurpose.READ);
return macro;
}
@Override
public void setAuth(IHttpRequestEngine requestEngine) {
// authentication is handled externally for now
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/AuthMethodNtlm.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.identity;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.protocol.HttpContext;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.api.model.identity.IAuthMethod;
import com.subgraph.vega.api.model.identity.IAuthMethodNtlm;
public class AuthMethodNtlm extends AbstractAuthMethod implements IAuthMethodNtlm {
private String username;
private String password;
private String workstation;
private String domain;
protected AuthMethodNtlm() {
super(IAuthMethod.AuthMethodType.AUTH_METHOD_NTLM);
}
@Override
public void setUsername(String username) {
activate(ActivationPurpose.READ);
this.username = username;
activate(ActivationPurpose.WRITE);
}
@Override
public String getUsername() {
activate(ActivationPurpose.READ);
return username;
}
@Override
public void setPassword(String password) {
activate(ActivationPurpose.READ);
this.password = password;
activate(ActivationPurpose.WRITE);
}
@Override
public String getPassword() {
activate(ActivationPurpose.READ);
return password;
}
@Override
public void setWorkstation(String workstation) {
activate(ActivationPurpose.READ);
this.workstation = workstation;
activate(ActivationPurpose.WRITE);
}
@Override
public String getWorkstation() {
activate(ActivationPurpose.READ);
return workstation;
}
@Override
public void setDomain(String domain) {
activate(ActivationPurpose.READ);
this.domain = domain;
activate(ActivationPurpose.WRITE);
}
@Override
public String getDomain() {
activate(ActivationPurpose.READ);
return domain;
}
@Override
public void setAuth(IHttpRequestEngine requestEngine) {
activate(ActivationPurpose.READ);
HttpClient httpClient = requestEngine.getHttpClient();
List authPref = new ArrayList(1);
authPref.add(AuthPolicy.NTLM);
httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPref);
HttpContext httpContext = requestEngine.getHttpContext();
NTCredentials creds = new NTCredentials(username, password, workstation, domain);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, creds);
httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/AuthMethodRfc2617.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.identity;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.AuthPolicy;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.protocol.HttpContext;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.api.model.identity.IAuthMethod;
import com.subgraph.vega.api.model.identity.IAuthMethodRfc2617;
public class AuthMethodRfc2617 extends AbstractAuthMethod implements IAuthMethodRfc2617 {
private AuthScheme authScheme;
private String username;
private String password;
private String charset;
protected AuthMethodRfc2617() {
super(IAuthMethod.AuthMethodType.AUTH_METHOD_RFC2617);
authScheme = IAuthMethodRfc2617.AuthScheme.AUTH_SCHEME_DIGEST;
}
@Override
public void setAuthScheme(AuthScheme authScheme) {
activate(ActivationPurpose.READ);
this.authScheme = authScheme;
activate(ActivationPurpose.WRITE);
}
@Override
public AuthScheme getAuthScheme() {
activate(ActivationPurpose.READ);
return authScheme;
}
@Override
public void setUsername(String username) {
activate(ActivationPurpose.READ);
this.username = username;
activate(ActivationPurpose.WRITE);
}
@Override
public String getUsername() {
activate(ActivationPurpose.READ);
return username;
}
@Override
public void setPassword(String password) {
activate(ActivationPurpose.READ);
this.password = password;
activate(ActivationPurpose.WRITE);
}
@Override
public String getPassword() {
activate(ActivationPurpose.READ);
return password;
}
@Override
public void setCharset(String charset) {
activate(ActivationPurpose.READ);
this.charset = charset;
activate(ActivationPurpose.WRITE);
}
@Override
public String getCharset() {
activate(ActivationPurpose.READ);
return charset;
}
@Override
public void setAuth(IHttpRequestEngine requestEngine) {
activate(ActivationPurpose.READ);
HttpClient httpClient = requestEngine.getHttpClient();
List authPref = new ArrayList(1);
switch (authScheme) {
case AUTH_SCHEME_BASIC:
authPref.add(AuthPolicy.BASIC);
break;
case AUTH_SCHEME_DIGEST:
authPref.add(AuthPolicy.DIGEST);
break;
}
httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authPref);
HttpContext httpContext = requestEngine.getHttpContext();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, creds);
httpContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/Identity.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.identity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.collections.ActivatableHashMap;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.identity.IAuthMethod;
import com.subgraph.vega.api.model.identity.IIdentity;
public class Identity implements IIdentity, Activatable {
private transient Activator activator;
private String name;
private IAuthMethod authMethod;
private ActivatableHashMap userDict;
private ActivatableArrayList pathExclusionList;
public Identity() {
pathExclusionList = new ActivatableArrayList();
userDict = new ActivatableHashMap();
}
@Override
public void setName(String name) {
activate(ActivationPurpose.READ);
this.name = name;
activate(ActivationPurpose.WRITE);
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public void setAuthMethod(IAuthMethod authMethod) {
activate(ActivationPurpose.READ);
// XXX remove the old one from the database?
this.authMethod = authMethod;
activate(ActivationPurpose.WRITE);
}
@Override
public IAuthMethod getAuthMethod() {
activate(ActivationPurpose.READ);
return authMethod;
}
@Override
public void addPathExclusion(String expression) {
activate(ActivationPurpose.READ);
pathExclusionList.add(expression);
activate(ActivationPurpose.WRITE);
}
@Override
public Collection getPathExclusions() {
activate(ActivationPurpose.READ);
return new ArrayList(pathExclusionList);
}
@Override
public void rmPathExclusion(String expression) {
activate(ActivationPurpose.READ);
pathExclusionList.remove(expression);
activate(ActivationPurpose.WRITE);
}
@Override
public String setDictValue(String key, String value) {
activate(ActivationPurpose.READ);
return userDict.put(key, value);
}
@Override
public String getDictValue(String key) {
activate(ActivationPurpose.READ);
return userDict.get(key);
}
@Override
public Map getDict() {
activate(ActivationPurpose.READ);
return new HashMap(userDict);
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/identity/IdentityModel.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.identity;
import java.util.Collection;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.identity.IAuthMethodHttpMacro;
import com.subgraph.vega.api.model.identity.IAuthMethodNtlm;
import com.subgraph.vega.api.model.identity.IAuthMethodRfc2617;
import com.subgraph.vega.api.model.identity.IIdentity;
import com.subgraph.vega.api.model.identity.IIdentityModel;
import com.subgraph.vega.api.model.identity.NewIdentityEvent;
public class IdentityModel implements IIdentityModel {
private final ObjectContainer database;
private final EventListenerManager changeEventManager;
public IdentityModel(ObjectContainer database) {
this.database = database;
this.changeEventManager = new EventListenerManager();
}
@Override
public Collection getAllIdentities() {
return database.query(IIdentity.class);
}
@Override
public IIdentity createIdentity() {
return new Identity();
}
@Override
public IAuthMethodRfc2617 createAuthMethodRfc2617() {
return new AuthMethodRfc2617();
}
@Override
public IAuthMethodNtlm createAuthMethodNtlm() {
return new AuthMethodNtlm();
}
@Override
public IAuthMethodHttpMacro createAuthMethodHttpMacro() {
return new AuthMethodHttpMacro();
}
@Override
public void store(IIdentity identity) {
database.store(identity);
changeEventManager.fireEvent(new NewIdentityEvent(identity));
}
@Override
public boolean isIdentityStored(IIdentity identity) {
return database.ext().isStored(identity);
}
@Override
public IIdentity getIdentityByName(final String name) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IIdentity identity) {
return name.equals(identity.getName());
}
});
if (results.size() == 0) {
return null;
}
return results.get(0);
}
@Override
public void addChangeListener(IEventHandler listener) {
changeEventManager.addListener(listener);
}
@Override
public void removeChangeListener(IEventHandler listener) {
changeEventManager.removeListener(listener);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/macros/HttpMacro.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.macros;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.macros.IHttpMacro;
import com.subgraph.vega.api.model.macros.IHttpMacroItem;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
public class HttpMacro implements IHttpMacro, Activatable {
private transient Activator activator;
private String name;
private ActivatableArrayList macroItemList;
public HttpMacro() {
macroItemList = new ActivatableArrayList();
}
@Override
public void setName(String name) {
activate(ActivationPurpose.READ);
this.name = name;
activate(ActivationPurpose.WRITE);
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public IHttpMacroItem createMacroItem(IRequestLogRecord record) throws URISyntaxException, IOException {
activate(ActivationPurpose.READ);
HttpMacroItem macroItem = new HttpMacroItem(record);
macroItemList.add(macroItem);
return macroItem;
}
@Override
public void removeMacroItem(IHttpMacroItem item) {
activate(ActivationPurpose.READ);
macroItemList.remove(item);
}
@Override
public Collection getMacroItems() {
activate(ActivationPurpose.READ);
return new ArrayList(macroItemList);
}
@Override
public int macroItemsSize() {
activate(ActivationPurpose.READ);
return macroItemList.size();
}
@Override
public int indexOfMacroItem(IHttpMacroItem item) {
activate(ActivationPurpose.READ);
return macroItemList.indexOf(item);
}
@Override
public void swapMacroItems(int idx1, int idx2) {
activate(ActivationPurpose.READ);
if (idx1 < macroItemList.size() && idx2 < macroItemList.size() && idx1 != idx2) {
final IHttpMacroItem tmp = macroItemList.set(idx1, macroItemList.get(idx2));
macroItemList.set(idx2, tmp);
}
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/macros/HttpMacroItem.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.macros;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.http.requests.IHttpHeaderBuilder;
import com.subgraph.vega.api.http.requests.IHttpMacroContext;
import com.subgraph.vega.api.http.requests.IHttpRequestBuilder;
import com.subgraph.vega.api.model.macros.IHttpMacroItem;
import com.subgraph.vega.api.model.macros.IHttpMacroItemParam;
import com.subgraph.vega.api.model.macros.IHttpMacroItemParam.ValueSetIn;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.http.requests.builder.HttpRequestBuilder;
public class HttpMacroItem implements IHttpMacroItem, Activatable {
// Headers to remove when copying headers while generating a request.
private final static String[] HEADERS_RM = {
HTTP.CONN_DIRECTIVE, // "Connection"
HTTP.CONN_KEEP_ALIVE, // "Keep-Alive"
"Proxy-Authenticate",
"Proxy-Authorization",
"TE",
"Trailers",
HTTP.TRANSFER_ENCODING, // "Transfer-Encoding"
"Upgrade",
"Proxy-Connection",
HTTP.CONTENT_LEN,
HTTP.CONTENT_TYPE,
"Cookie",
};
private transient Activator activator;
private IRequestLogRecord requestLogRecord;
private HttpParams requestParams;
private String requestMethod;
private ProtocolVersion requestProtocolVersion;
private String requestScheme;
private String requestHost;
private int requestPort;
private String requestPath; /** Raw path of request */
private final ArrayList requestHeaderList = new ArrayList();
private boolean useCookies;
private boolean keepCookies;
private ActivatableArrayList paramList;
public HttpMacroItem(IRequestLogRecord requestLogRecord) throws URISyntaxException, IOException {
this.requestLogRecord = requestLogRecord;
useCookies = true;
keepCookies = true;
final HttpRequest request = requestLogRecord.getRequest();
processRequest(request, requestLogRecord.getHttpHost());
paramList = new ActivatableArrayList();
processParams(request);
}
@Override
public IRequestLogRecord getRequestLogRecord() {
activate(ActivationPurpose.READ);
return requestLogRecord;
}
@Override
public void setUseCookies(boolean useCookies) {
activate(ActivationPurpose.READ);
this.useCookies = useCookies;
activate(ActivationPurpose.WRITE);
}
@Override
public boolean getUseCookies() {
activate(ActivationPurpose.READ);
return useCookies;
}
@Override
public void setKeepCookies(boolean keepCookies) {
activate(ActivationPurpose.READ);
this.keepCookies = keepCookies;
activate(ActivationPurpose.WRITE);
}
@Override
public boolean getKeepCookies() {
activate(ActivationPurpose.READ);
return keepCookies;
}
@Override
public IHttpMacroItemParam createParam(String name, String value, ValueSetIn setIn) {
HttpMacroItemParam param = new HttpMacroItemParam(name, value, setIn);
paramList.add(param);
return param;
}
@Override
public void removeParam(IHttpMacroItemParam param) {
paramList.remove(param);
}
@Override
public int paramsSize() {
return paramList.size();
}
@Override
public int indexOfParam(IHttpMacroItemParam param) {
return paramList.indexOf(param);
}
@Override
public void swapParams(int idx1, int idx2) {
if (idx1 < paramList.size() && idx2 < paramList.size() && idx1 != idx2) {
final IHttpMacroItemParam tmp = paramList.set(idx1, paramList.get(idx2));
paramList.set(idx2, tmp);
}
}
@Override
public Collection getParams() {
return new ArrayList(paramList);
}
@Override
public IHttpMacroItemParam[] getParam(String name) {
final ArrayList tmp = new ArrayList();
for (IHttpMacroItemParam param: paramList) {
if (param.getName().equals(name)) {
tmp.add(param);
}
}
return tmp.toArray(new IHttpMacroItemParam[0]);
}
@Override
public HttpUriRequest createRequest(IHttpMacroContext context) throws UnsupportedEncodingException, URISyntaxException {
final HttpRequestBuilder builder = new HttpRequestBuilder();
setRequestBuilder(builder, context);
return builder.buildRequest(false);
}
@Override
public void setRequestBuilder(IHttpRequestBuilder requestBuilder, IHttpMacroContext context) throws UnsupportedEncodingException, URISyntaxException {
activate(ActivationPurpose.READ);
setRequestParams(requestBuilder);
setRequestLine(requestBuilder, context);
setRequestHeaders(requestBuilder);
setRequestBody(requestBuilder, context);
}
@Override
public void updateFromRequestBuilder(IHttpRequestBuilder requestBuilder) throws URISyntaxException {
activate(ActivationPurpose.READ);
requestParams = requestBuilder.getParams().copy();
requestMethod = requestBuilder.getMethod();
requestScheme = requestBuilder.getScheme();
requestHost = requestBuilder.getHost();
requestPort = requestBuilder.getHostPort();
final URI uri = new URI(requestBuilder.getPath());
requestPath = uri.getRawPath();
requestProtocolVersion = requestBuilder.getProtocolVersion();
requestHeaderList.clear();
for (IHttpHeaderBuilder header: requestBuilder.getHeaders()) {
requestHeaderList.add(header.buildHeader());
}
activate(ActivationPurpose.WRITE);
// REVISIT: we need to process the request body and URI for parameters
}
private void setRequestParams(IHttpRequestBuilder requestBuilder) {
requestBuilder.setParams(requestParams.copy());
}
private void setRequestLine(IHttpRequestBuilder requestBuilder, IHttpMacroContext context) throws URISyntaxException {
requestBuilder.setMethod(requestMethod);
setRequestUri(requestBuilder, context);
requestBuilder.setProtocolVersion(requestProtocolVersion);
}
private void setRequestUri(IHttpRequestBuilder requestBuilder, IHttpMacroContext context) throws URISyntaxException {
requestBuilder.setScheme(requestScheme);
requestBuilder.setHost(requestHost);
requestBuilder.setHostPort(requestPort);
final String query = createUriQuery(context);
String path = requestPath;
if (query.length() != 0) {
path += "?" + query;
}
requestBuilder.setPath(path);
}
private void setRequestHeaders(IHttpRequestBuilder requestBuilder) {
requestBuilder.setHeaders(requestHeaderList.toArray(new Header[0]));
}
private void setRequestBody(IHttpRequestBuilder requestBuilder, IHttpMacroContext context) throws UnsupportedEncodingException {
ArrayList bodyParamList = new ArrayList();
for (IHttpMacroItemParam param: paramList) {
if (param.getSetIn() == IHttpMacroItemParam.ValueSetIn.VALUE_SET_IN_BODY) {
bodyParamList.add(new BasicNameValuePair(param.getName(), param.getValue()));
}
}
if (bodyParamList.size() != 0) {
final StringEntity entity = new StringEntity(URLEncodedUtils.format(bodyParamList, "UTF-8"), "UTF-8");
entity.setContentType("application/x-www-form-urlencoded");
requestBuilder.setEntity(entity);
requestBuilder.setMethod("POST");
}
}
private String createUriQuery(IHttpMacroContext context) {
StringBuilder buf = new StringBuilder();
for (IHttpMacroItemParam param: paramList) {
if (param.getSetIn() == IHttpMacroItemParam.ValueSetIn.VALUE_SET_IN_URI) {
if (buf.length() != 0) {
buf.append('&');
}
buf.append(param.getName());
buf.append('=');
buf.append(param.getValue());
}
}
return buf.toString();
}
private void processRequest(HttpRequest request, HttpHost host) throws URISyntaxException {
requestParams = request.getParams().copy();
final RequestLine requestLine = request.getRequestLine();
requestMethod = requestLine.getMethod();
requestScheme = host.getSchemeName();
requestHost = host.getHostName();
requestPort = host.getPort();
final URI uri = new URI(request.getRequestLine().getUri());
requestPath = uri.getRawPath();
requestProtocolVersion = requestLine.getProtocolVersion();
requestHeaderList.clear();
Collections.addAll(requestHeaderList, copyHeaders(request.getAllHeaders()));
}
private void processParams(HttpRequest request) throws URISyntaxException, IOException {
processParamsUri(request);
processParamsBody(request);
}
private void processParamsUri(HttpRequest request) throws URISyntaxException {
URI uri = new URI(request.getRequestLine().getUri());
List requestParamList = URLEncodedUtils.parse(uri, "UTF-8");
for (NameValuePair pair: requestParamList) {
paramList.add(new HttpMacroItemParam(pair.getName(), pair.getValue(), IHttpMacroItemParam.ValueSetIn.VALUE_SET_IN_URI));
}
}
private void processParamsBody(HttpRequest request) throws IOException {
if (request instanceof HttpEntityEnclosingRequest) {
List entityParamList = null;
entityParamList = URLEncodedUtils.parse(((HttpEntityEnclosingRequest) request).getEntity());
for (NameValuePair pair: entityParamList) {
paramList.add(new HttpMacroItemParam(pair.getName(), pair.getValue(), IHttpMacroItemParam.ValueSetIn.VALUE_SET_IN_BODY));
}
}
}
private Header[] copyHeaders(Header[] headers) {
ArrayList headerList = new ArrayList();
for (Header header: headers) {
int idx;
for (idx = 0; idx < HEADERS_RM.length; idx++) {
if (HEADERS_RM[idx].equals(header.getName())) {
break;
}
}
if (idx == HEADERS_RM.length) {
headerList.add(header);
}
}
return headerList.toArray(new Header[0]);
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/macros/HttpMacroItemParam.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.macros;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.macros.IHttpMacroItemParam;
public class HttpMacroItemParam implements IHttpMacroItemParam, Activatable {
private transient Activator activator;
private String name;
private ValueSource source;
private ValueSetIn setIn;
private String value;
public HttpMacroItemParam(String name, ValueSetIn setIn) {
this.name = name;
this.setIn = setIn;
}
public HttpMacroItemParam(String name, String value, ValueSetIn setIn) {
this.name = name;
this.source = IHttpMacroItemParam.ValueSource.SOURCE_LITERAL;
this.value = value;
this.setIn = setIn;
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public void setValueSource(ValueSource source) {
activate(ActivationPurpose.READ);
this.source = source;
activate(ActivationPurpose.WRITE);
}
@Override
public ValueSource getValueSource() {
activate(ActivationPurpose.READ);
return source;
}
@Override
public void setSetIn(ValueSetIn setIn) {
activate(ActivationPurpose.READ);
this.setIn = setIn;
activate(ActivationPurpose.WRITE);
}
@Override
public ValueSetIn getSetIn() {
activate(ActivationPurpose.READ);
return setIn;
}
@Override
public void setValue(String value) {
activate(ActivationPurpose.READ);
this.value = value;
activate(ActivationPurpose.WRITE);
}
@Override
public String getValue() {
activate(ActivationPurpose.READ);
return value;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/macros/HttpMacroModel.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.macros;
import java.util.Collection;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.macros.IHttpMacro;
import com.subgraph.vega.api.model.macros.IHttpMacroModel;
import com.subgraph.vega.api.model.macros.NewMacroEvent;
public class HttpMacroModel implements IHttpMacroModel {
private ObjectContainer database;
private final EventListenerManager changeEventManager;
public HttpMacroModel(ObjectContainer database) {
this.database = database;
this.changeEventManager = new EventListenerManager();
}
@Override
public Collection getAllMacros() {
return database.query(IHttpMacro.class);
}
@Override
public IHttpMacro createMacro() {
return new HttpMacro();
}
@Override
public void store(IHttpMacro macro) {
database.store(macro);
changeEventManager.fireEvent(new NewMacroEvent(macro));
}
@Override
public boolean isMacroStored(IHttpMacro macro) {
return database.ext().isStored(macro);
}
@Override
public IHttpMacro getMacroByName(final String name) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IHttpMacro macro) {
return name.equals(macro.getName());
}
});
if (results.size() == 0) {
return null;
}
return results.get(0);
}
@Override
public void addChangeListener(IEventHandler listener) {
changeEventManager.addListener(listener);
}
@Override
public void removeChangeListener(IEventHandler listener) {
changeEventManager.removeListener(listener);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/HttpMessageCloner.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpMessage;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.util.EntityUtils;
import com.db4o.ObjectContainer;
public class HttpMessageCloner {
private final ObjectContainer database;
HttpMessageCloner(ObjectContainer database) {
this.database = database;
}
HttpRequest copyRequest(HttpRequest request) {
if(request instanceof HttpEntityEnclosingRequest) {
return copyEntityEnclosingRequest((HttpEntityEnclosingRequest) request);
} else {
return copyBasicRequest(request);
}
}
HttpResponse copyResponse(HttpResponse response) {
final HttpEntity e = copyEntity(response.getEntity());
final RequestLogResponse r = new RequestLogResponse(database, response.getStatusLine(), entityToDatabaseId(e));
copyHeaders(response, r);
return r;
}
private HttpRequest copyEntityEnclosingRequest(HttpEntityEnclosingRequest request) {
final HttpEntity e = copyEntity(request.getEntity());
final RequestLogEntityEnclosingRequest r = new RequestLogEntityEnclosingRequest(database, request.getRequestLine(), entityToDatabaseId(e));
copyHeaders(request, r);
return r;
}
private HttpRequest copyBasicRequest(HttpRequest request) {
if(request == null) {
return null;
}
final HttpRequest r = new BasicHttpRequest(request.getRequestLine());
copyHeaders(request, r);
return r;
}
private static void copyHeaders(HttpMessage from, HttpMessage to) {
for(Header h: from.getAllHeaders()) {
to.addHeader(new BasicHeader(h.getName(), h.getValue()));
}
}
private long entityToDatabaseId(HttpEntity entity) {
if(entity == null) {
return 0;
}
database.ext().store(entity);
return database.ext().getID(entity);
}
private HttpEntity copyEntity(HttpEntity entity) {
try {
if(entity == null) {
return null;
}
final byte[] content = EntityUtils.toByteArray(entity);
return new RequestLogEntity(content, entity.getContentType(), entity.getContentEncoding());
} catch (IOException e) {
return null;
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/HttpRequestBuilderStorable.java
================================================
/*******************************************************************************
* Copyright (c) 2012 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.params.HttpParams;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.http.requests.IHttpHeaderBuilder;
import com.subgraph.vega.api.http.requests.IHttpRequestBuilder;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.http.requests.builder.HttpHeaderBuilder;
import com.subgraph.vega.http.requests.builder.HttpRequestBuilder;
/**
* Decorator for IHttpRequestBuilder to maintain data in the database using transparent activation.
*/
public class HttpRequestBuilderStorable extends HttpRequestBuilder implements IHttpRequestBuilder, Activatable {
protected transient Activator activator;
@Override
public void clear() {
activate(ActivationPurpose.READ);
super.clear();
activate(ActivationPurpose.WRITE);
}
@Override
public void setParams(HttpParams params) {
activate(ActivationPurpose.READ);
super.setParams(params);
activate(ActivationPurpose.WRITE);
}
@Override
public HttpParams getParams() {
activate(ActivationPurpose.READ);
return super.getParams();
}
@Override
public void setProtocolVersion(ProtocolVersion protocolVersion) {
activate(ActivationPurpose.READ);
super.setProtocolVersion(protocolVersion);
activate(ActivationPurpose.WRITE);
}
@Override
public ProtocolVersion getProtocolVersion() {
activate(ActivationPurpose.READ);
return super.getProtocolVersion();
}
@Override
public void setHeaders(Header[] headers) {
activate(ActivationPurpose.READ);
super.setHeaders(headers);
activate(ActivationPurpose.WRITE);
}
@Override
public HttpHeaderBuilder addHeader(String name, String value) {
activate(ActivationPurpose.READ);
final HttpHeaderBuilder builder = super.addHeader(name, value);
activate(ActivationPurpose.WRITE);
return builder;
}
@Override
public HttpHeaderBuilder setHeader(String name, String value) {
activate(ActivationPurpose.READ);
final HttpHeaderBuilder builder = super.setHeader(name, value);
activate(ActivationPurpose.WRITE);
return builder;
}
@Override
public void removeHeader(IHttpHeaderBuilder header) {
activate(ActivationPurpose.READ);
super.removeHeader(header);
activate(ActivationPurpose.WRITE);
}
@Override
public void removeHeaders(String name) {
activate(ActivationPurpose.READ);
super.removeHeaders(name);
activate(ActivationPurpose.WRITE);
}
@Override
public void clearHeaders() {
activate(ActivationPurpose.READ);
super.clearHeaders();
activate(ActivationPurpose.WRITE);
}
@Override
public void swapHeader(int idx1, int idx2) {
activate(ActivationPurpose.READ);
super.swapHeader(idx1, idx2);
activate(ActivationPurpose.WRITE);
}
@Override
public int getHeaderIdxOf(IHttpHeaderBuilder next) {
activate(ActivationPurpose.READ);
return super.getHeaderIdxOf(next);
}
@Override
public int getHeaderCnt() {
activate(ActivationPurpose.READ);
return super.getHeaderCnt();
}
@Override
public IHttpHeaderBuilder getHeader(int idx) {
activate(ActivationPurpose.READ);
return super.getHeader(idx);
}
@Override
public IHttpHeaderBuilder[] getHeaders() {
activate(ActivationPurpose.READ);
return super.getHeaders();
}
@Override
public void setEntity(HttpEntity entity) {
activate(ActivationPurpose.READ);
super.setEntity(entity);
activate(ActivationPurpose.WRITE);
}
@Override
public HttpEntity getEntity() {
activate(ActivationPurpose.READ);
return null;
}
@Override
public void setFromRequest(IRequestLogRecord record) throws URISyntaxException {
activate(ActivationPurpose.READ);
super.setFromRequest(record);
activate(ActivationPurpose.WRITE);
}
@Override
public void setFromRequest(HttpRequest request) throws URISyntaxException {
activate(ActivationPurpose.READ);
super.setFromRequest(request);
activate(ActivationPurpose.WRITE);
}
@Override
public void setFromRequestLine(RequestLine requestLine) throws URISyntaxException {
activate(ActivationPurpose.READ);
super.setFromRequestLine(requestLine);
activate(ActivationPurpose.WRITE);
}
@Override
public void setFromUri(URI uri) {
activate(ActivationPurpose.READ);
super.setFromUri(uri);
activate(ActivationPurpose.WRITE);
}
@Override
public void setFromHttpHost(HttpHost host) {
activate(ActivationPurpose.READ);
super.setFromHttpHost(host);
activate(ActivationPurpose.WRITE);
}
@Override
public void setScheme(String scheme) {
activate(ActivationPurpose.READ);
super.setScheme(scheme);
activate(ActivationPurpose.WRITE);
}
@Override
public String getScheme() {
activate(ActivationPurpose.READ);
return super.getScheme();
}
@Override
public void setHost(String host) {
activate(ActivationPurpose.READ);
}
@Override
public String getHost() {
activate(ActivationPurpose.READ);
return super.getHost();
}
@Override
public void setHostPort(int port) {
activate(ActivationPurpose.READ);
super.setHostPort(port);
activate(ActivationPurpose.WRITE);
}
@Override
public int getHostPort() {
activate(ActivationPurpose.READ);
return super.getHostPort();
}
@Override
public void setMethod(String method) {
activate(ActivationPurpose.READ);
super.setMethod(method);
}
@Override
public String getMethod() {
activate(ActivationPurpose.READ);
return super.getMethod();
}
@Override
public void setPath(String path) {
activate(ActivationPurpose.READ);
super.setPath(path);
activate(ActivationPurpose.WRITE);
}
@Override
public String getPath() {
activate(ActivationPurpose.READ);
return super.getPath();
}
@Override
public String getRequestLine() {
activate(ActivationPurpose.READ);
return super.getRequestLine();
}
@Override
public HttpUriRequest buildRequest(boolean setHeadersEntity) throws URISyntaxException {
activate(ActivationPurpose.READ);
return super.buildRequest(setHeadersEntity);
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/LazyEntityLoader.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import com.db4o.ObjectContainer;
public class LazyEntityLoader {
private final long entityId;
private final ObjectContainer database;
LazyEntityLoader(long entityId, ObjectContainer database) {
this.entityId = entityId;
this.database = database;
}
HttpEntity getEntity() {
if(entityId == 0) {
return null;
}
final RequestLogEntity e = database.ext().getByID(entityId);
if(e == null) {
return null;
}
database.ext().activate(e);
final HttpEntity copy = createEntityCopy(e);
database.ext().deactivate(e, 1);
database.ext().purge(e);
return copy;
}
private HttpEntity createEntityCopy(RequestLogEntity entity) {
final ByteArrayEntity copy = new ByteArrayEntity(entity.getContentArray());
copy.setContentType(entity.getContentType());
copy.setContentEncoding(copy.getContentEncoding());
return copy;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLog.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.events.Event4;
import com.db4o.events.EventListener4;
import com.db4o.events.EventRegistry;
import com.db4o.events.EventRegistryFactory;
import com.db4o.events.ObjectInfoEventArgs;
import com.db4o.query.Predicate;
import com.db4o.query.Query;
import com.subgraph.vega.api.http.requests.IHttpResponse;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
import com.subgraph.vega.api.model.requests.IRequestLog;
import com.subgraph.vega.api.model.requests.IRequestLogNewRecordListener;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.api.model.requests.IRequestOrigin;
import com.subgraph.vega.api.model.requests.IRequestOriginProxy;
import com.subgraph.vega.api.model.requests.IRequestOriginScanner;
import com.subgraph.vega.internal.model.conditions.HttpConditionSet;
public class RequestLog implements IRequestLog {
private final ObjectContainer database;
private final RequestLogId requestLogId;
private final HttpMessageCloner cloner;
private final List newRecordListeners = new ArrayList();
private final Object lock = new Object();
public RequestLog(final ObjectContainer database) {
this.database = database;
this.requestLogId = getRequestLogId(database);
this.cloner = new HttpMessageCloner(database);
final EventRegistry registry = EventRegistryFactory.forObjectContainer(database);
registry.activated().addListener(new EventListener4 () {
@Override
public void onEvent(Event4 arg0, ObjectInfoEventArgs args) {
final Object ob = args.object();
if(ob instanceof RequestLogResponse) {
final RequestLogResponse r = (RequestLogResponse) ob;
r.setDatabase(database);
} else if(ob instanceof RequestLogEntityEnclosingRequest) {
final RequestLogEntityEnclosingRequest r = (RequestLogEntityEnclosingRequest) ob;
r.setDatabase(database);
}
}
});
}
private RequestLogId getRequestLogId(ObjectContainer database) {
List result = database.query(RequestLogId.class);
if(result.size() == 0) {
RequestLogId rli = new RequestLogId();
database.store(rli);
return rli;
} else if(result.size() == 1) {
return result.get(0);
} else {
throw new IllegalStateException("Database corrupted, found multiple RequestLogId instances");
}
}
@Override
public long allocateRequestId() {
final long id = requestLogId.allocateId();
database.store(requestLogId);
return id;
}
@Override
public long getNextRequestId() {
return requestLogId.getCurrentId();
}
@Override
public long addRequestResponse(IHttpResponse response) {
if (response.getRequestId() != -1) {
return response.getRequestId();
}
final long id = allocateRequestId();
final HttpRequest newRequest = cloner.copyRequest(response.getOriginalRequest());
final HttpResponse newResponse = cloner.copyResponse(response.getRawResponse());
database.store(newRequest);
database.store(newResponse);
final RequestLogRecord record = new RequestLogRecord(id, newRequest, response.getRequestOrigin(), newResponse, response.getHost(), response.getRequestMilliseconds(), response.getTags());
synchronized(lock){
database.store(record);
filterNewRecord(record);
}
response.setRequestId(id);
return id;
}
private void filterNewRecord(IRequestLogRecord record) {
for(RequestLogNewRecordListener listener: newRecordListeners) {
listener.filterRecord(record);
}
}
@Override
public RequestLogRecord lookupRecord(final long requestId) {
synchronized(this) {
List result = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(RequestLogRecord record) {
return record.requestId == requestId;
}
});
if(result.size() == 0)
return null;
else if(result.size() == 1)
return result.get(0);
else
throw new IllegalStateException("Database corrupted, found multiple RequestLogRecords for id == "+ requestId);
}
}
@Override
public List getAllRecords() {
if(!hasRecords()) {
return Collections.emptyList();
}
final Query query = database.query();
query.constrain(IRequestLogRecord.class);
return query.execute();
}
private boolean hasRecords() {
final Query query = database.query();
query.constrain(IRequestLogRecord.class);
return query.execute().hasNext();
}
public List getRecordsByConditionSet(IHttpConditionSet conditionFilter) {
if(conditionFilter instanceof HttpConditionSet) {
return ((HttpConditionSet)conditionFilter).filterRequestLog(database);
} else {
return Collections.emptyList();
}
}
@Override
public Iterator getRecordIteratorByConditionSet(IHttpConditionSet conditionFilter) {
if(conditionFilter instanceof HttpConditionSet) {
final ObjectSet result = ((HttpConditionSet)conditionFilter).executeFilterQuery(database);
return createIteratorForResult(result);
} else {
final List emptyList = Collections.emptyList();
return emptyList.iterator();
}
}
private Iterator createIteratorForResult(final ObjectSet result) {
return new Iterator() {
@Override
public boolean hasNext() {
return result.hasNext();
}
@Override
public IRequestLogRecord next() {
return result.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public IRequestOriginProxy getRequestOriginProxy(final InetAddress address, final int port) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IRequestOriginProxy requestOrigin) {
return address.equals(requestOrigin.getInetAddress()) && port == requestOrigin.getPort();
}
});
if (results.size() == 0) {
IRequestOriginProxy requestOrigin = new RequestOriginProxy(address, port);
database.store(requestOrigin);
return requestOrigin;
} else {
return results.get(0);
}
}
@Override
public IRequestOriginScanner getRequestOriginScanner(final IScanInstance scanInstance) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IRequestOriginScanner requestOrigin) {
return scanInstance.getScanId() == requestOrigin.getScanInstance().getScanId();
}
});
if (results.size() == 0) {
IRequestOriginScanner requestOrigin = new RequestOriginScanner(scanInstance);
database.store(requestOrigin);
return requestOrigin;
} else {
return results.get(0);
}
}
@Override
public IRequestOrigin getRequestOriginRequestEditor() {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IRequestOrigin requestOrigin) {
return requestOrigin.getOrigin() == IRequestOrigin.Origin.ORIGIN_REQUEST_EDITOR;
}
});
if (results.size() == 0) {
IRequestOrigin requestOrigin = new RequestOrigin(IRequestOrigin.Origin.ORIGIN_REQUEST_EDITOR);
database.store(requestOrigin);
return requestOrigin;
} else {
return results.get(0);
}
}
@Override
public void addNewRecordListener(IRequestLogNewRecordListener callback) {
addNewRecordListener(callback, null);
}
@Override
public void addNewRecordListener(IRequestLogNewRecordListener callback,
IHttpConditionSet filterCondition) {
synchronized (lock) {
newRecordListeners.add(new RequestLogNewRecordListener(callback, filterCondition));
}
}
@Override
public void removeNewRecordListener(IRequestLogNewRecordListener callback) {
synchronized (lock) {
final Iterator it = newRecordListeners.iterator();
while(it.hasNext()) {
RequestLogNewRecordListener listener = it.next();
if(listener.getListener() == callback) {
it.remove();
}
}
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogEntity.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class RequestLogEntity implements HttpEntity {
private byte[] content;
private Header contentType;
private Header contentEncoding;
RequestLogEntity(byte[] content, Header contentType, Header contentEncoding) {
this.content = content;
this.contentType = copyHeader(contentType);
this.contentEncoding = copyHeader(contentEncoding);
}
public byte[] getContentArray() {
return content;
}
private Header copyHeader(Header h) {
if(h == null) {
return null;
} else {
return new BasicHeader(h.getName(), h.getValue());
}
}
@Override
public boolean isRepeatable() {
return true;
}
@Override
public boolean isChunked() {
return false;
}
@Override
public long getContentLength() {
return content.length;
}
@Override
public Header getContentType() {
return contentType;
}
@Override
public Header getContentEncoding() {
return contentEncoding;
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
return new ByteArrayInputStream(content);
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
if(outstream == null) {
throw new IllegalArgumentException("Output stream may not be null");
}
outstream.write(content);
outstream.flush();
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void consumeContent() throws IOException {
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogEntityEnclosingRequest.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import org.apache.http.HttpEntity;
import org.apache.http.RequestLine;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import com.db4o.ObjectContainer;
public class RequestLogEntityEnclosingRequest extends BasicHttpEntityEnclosingRequest {
private final long entityId;
private transient LazyEntityLoader loader;
public RequestLogEntityEnclosingRequest(ObjectContainer database, RequestLine requestline, long entityId) {
super(requestline);
this.entityId = entityId;
setDatabase(database);
}
void setDatabase(ObjectContainer database) {
this.loader = new LazyEntityLoader(entityId, database);
}
@Override
public HttpEntity getEntity() {
return loader.getEntity();
}
@Override
public void setEntity(final HttpEntity entity) {
throw new UnsupportedOperationException();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogId.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
public class RequestLogId {
private long currentId = 0;
synchronized long allocateId() {
final long ret = currentId;
currentId++;
return ret;
}
synchronized long getCurrentId() {
return currentId;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogNewRecordListener.java
================================================
package com.subgraph.vega.internal.model.requests;
import com.subgraph.vega.api.model.conditions.IHttpConditionSet;
import com.subgraph.vega.api.model.requests.IRequestLogNewRecordListener;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.api.model.requests.RequestLogNewRecordEvent;
public class RequestLogNewRecordListener {
private final IRequestLogNewRecordListener listenerCallback;
private final IHttpConditionSet filterCondition;
public RequestLogNewRecordListener(IRequestLogNewRecordListener callback, IHttpConditionSet filter) {
this.listenerCallback = callback;
this.filterCondition = filter;
}
void filterRecord(IRequestLogRecord record) {
if(matchesRecord(record)) {
listenerCallback.onNewRecord(new RequestLogNewRecordEvent(record));
}
}
IRequestLogNewRecordListener getListener() {
return listenerCallback;
}
private boolean matchesRecord(IRequestLogRecord record) {
if(filterCondition != null) {
return filterCondition.matchesAll(record);
} else {
return true;
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogRecord.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableArrayList;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.requests.IRequestLogRecord;
import com.subgraph.vega.api.model.requests.IRequestOrigin;
import com.subgraph.vega.api.model.tags.ITag;
public class RequestLogRecord implements IRequestLogRecord, Activatable {
final long requestId;
private final HttpRequest request;
private IRequestOrigin requestOrigin;
private final HttpHost host;
private String hostname;
private String requestMethod;
private String requestPath;
private String requestHeaders;
private int responseCode;
private int responseLength;
private String responseHeaders;
private HttpResponse response;
private final long timestamp;
private long requestTimeMs;
private ActivatableArrayList tagList;
private transient Activator activator;
RequestLogRecord(long requestId, HttpRequest request, IRequestOrigin requestOrigin, HttpResponse response, HttpHost host, long requestTimeMs, List tagList) {
this.requestId = requestId;
this.request = request;
this.requestOrigin = requestOrigin;
this.response = response;
this.host = host;
this.timestamp = new Date().getTime();
this.requestTimeMs = requestTimeMs;
this.tagList = new ActivatableArrayList(tagList);
setCachedRequestFields(request, host);
setCachedResponseFields(response);
}
RequestLogRecord(long requestId, HttpRequest request, IRequestOrigin requestOrigin, HttpHost host, long requestTimeMs, List tagList) {
this(requestId, request, requestOrigin, null, host, requestTimeMs, tagList);
}
private void setCachedRequestFields(HttpRequest request, HttpHost host) {
if(request == null) {
hostname = null;
requestMethod = null;
requestHeaders = null;
requestPath = null;
} else {
hostname = host.getHostName();
requestMethod = request.getRequestLine().getMethod();
requestHeaders = headersToString(request.getAllHeaders());
requestPath = request.getRequestLine().getUri();
}
}
private void setCachedResponseFields(HttpResponse response) {
if(response == null) {
responseCode = 0;
responseLength = 0;
responseHeaders = null;
} else {
responseCode = response.getStatusLine().getStatusCode();
responseLength = (int) getLengthFromResponse(response);
responseHeaders = headersToString(response.getAllHeaders());
}
}
private String headersToString(Header[] headers) {
final StringBuilder sb = new StringBuilder();
for(Header h: headers) {
sb.append(h.getName());
sb.append(": ");
sb.append(h.getValue());
sb.append("\n");
}
return sb.toString();
}
private long getLengthFromResponse(HttpResponse response) {
final Header lengthHeader = response.getFirstHeader("Content-Length");
if(lengthHeader != null) {
try {
return Long.parseLong(lengthHeader.getValue());
} catch (NumberFormatException e) {
return 0;
}
}
if(response.getEntity() == null)
return 0;
return response.getEntity().getContentLength();
}
void setResponse(HttpResponse response) {
activate(ActivationPurpose.READ);
this.response = response;
setCachedResponseFields(response);
activate(ActivationPurpose.WRITE);
}
String getHostname() {
return hostname;
}
String getRequestMethod() {
return requestMethod;
}
String getRequestHeaders() {
return requestHeaders;
}
String getRequestPath() {
return requestPath;
}
int getResponseCode() {
return responseCode;
}
int getResponseLength() {
return responseLength;
}
String getResponseHeaders() {
return responseHeaders;
}
@Override
public long getRequestId() {
activate(ActivationPurpose.READ);
return requestId;
}
@Override
public long getTimestamp() {
activate(ActivationPurpose.READ);
return timestamp;
}
@Override
public IRequestOrigin getRequestOrigin() {
activate(ActivationPurpose.READ);
return requestOrigin;
}
@Override
public long getRequestMilliseconds() {
activate(ActivationPurpose.READ);
return requestTimeMs;
}
@Override
public HttpRequest getRequest() {
activate(ActivationPurpose.READ);
return request;
}
@Override
public HttpResponse getResponse() {
activate(ActivationPurpose.READ);
synchronized(response) {
return response;
}
}
@Override
public HttpHost getHttpHost() {
activate(ActivationPurpose.READ);
return host;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
@Override
public Collection getAllTags() {
activate(ActivationPurpose.READ);
return Collections.unmodifiableList(new ArrayList(tagList));
}
@Override
public ITag getTag(int idx) {
activate(ActivationPurpose.READ);
return tagList.get(idx);
}
@Override
public int getTagCount() {
activate(ActivationPurpose.READ);
return tagList.size();
}
@Override
public void setTags(Collection tags) {
activate(ActivationPurpose.READ);
tagList.clear();
tagList.addAll(tags);
activate(ActivationPurpose.WRITE);
}
@Override
public void addTag(ITag tag) {
activate(ActivationPurpose.READ);
tagList.add(tag);
activate(ActivationPurpose.WRITE);
}
@Override
public void removeTag(ITag tag) {
activate(ActivationPurpose.READ);
tagList.remove(tag);
activate(ActivationPurpose.WRITE);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestLogResponse.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicHttpResponse;
import com.db4o.ObjectContainer;
public class RequestLogResponse extends BasicHttpResponse {
private final long entityId;
private transient LazyEntityLoader loader;
public RequestLogResponse(ObjectContainer database, StatusLine statusline, long entityId) {
super(statusline);
this.entityId = entityId;
setDatabase(database);
}
void setDatabase(ObjectContainer database) {
this.loader = new LazyEntityLoader(entityId, database);
}
@Override
public HttpEntity getEntity() {
return loader.getEntity();
}
@Override
public void setEntity(final HttpEntity entity) {
throw new UnsupportedOperationException();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestOrigin.java
================================================
package com.subgraph.vega.internal.model.requests;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.requests.IRequestOrigin;
public class RequestOrigin implements IRequestOrigin, Activatable {
private transient Activator activator;
private Origin origin;
public RequestOrigin(Origin origin) {
this.origin = origin;
}
@Override
public Origin getOrigin() {
activate(ActivationPurpose.READ);
return origin;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestOriginProxy.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import java.net.InetAddress;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.model.requests.IRequestOrigin;
import com.subgraph.vega.api.model.requests.IRequestOriginProxy;
public class RequestOriginProxy extends RequestOrigin implements IRequestOriginProxy {
private InetAddress address;
private int port;
public RequestOriginProxy(InetAddress address, int port) {
super(IRequestOrigin.Origin.ORIGIN_PROXY);
this.address = address;
this.port = port;
}
@Override
public InetAddress getInetAddress() {
activate(ActivationPurpose.READ);
return address;
}
@Override
public int getPort() {
activate(ActivationPurpose.READ);
return port;
}
@Override
public String toString() {
final StringBuffer buf = new StringBuffer();
buf.append('[');
buf.append(address.getHostAddress());
buf.append("]:");
buf.append(port);
return buf.toString();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/requests/RequestOriginScanner.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.requests;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.model.requests.IRequestOriginScanner;
import com.subgraph.vega.api.model.requests.IRequestOrigin;
public class RequestOriginScanner extends RequestOrigin implements IRequestOriginScanner {
private IScanInstance scanInstance;
public RequestOriginScanner(IScanInstance scanInstance) {
super(IRequestOrigin.Origin.ORIGIN_SCANNNER);
this.scanInstance = scanInstance;
}
@Override
public IScanInstance getScanInstance() {
activate(ActivationPurpose.READ);
return scanInstance;
}
@Override
public String toString() {
return "Scan ID " + scanInstance.getScanId();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/scope/TargetScope.java
================================================
package com.subgraph.vega.internal.model.scope;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.http.HttpHost;
import org.apache.http.client.utils.URIUtils;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableHashSet;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.scope.ActiveScopeChangedEvent;
import com.subgraph.vega.api.model.scope.ITargetScope;
import com.subgraph.vega.api.util.UriTools;
public class TargetScope implements ITargetScope, Activatable {
private final long id;
private final Set scopeURIs;
private final Set exclusionPatterns;
private final Set exclusionURIs;
private final boolean isDefault;
private String name;
private boolean isActiveScope;
private boolean isReadOnly;
private boolean isDetached;
private transient EventListenerManager scopeChangedListeners;
private transient List compiledPatterns;
private transient Activator activator;
TargetScope(long id, boolean isDefault, EventListenerManager scopeChangeListeners) {
this.id = id;
this.name = "";
this.isDefault = isDefault;
this.scopeURIs = new ActivatableHashSet();
this.exclusionPatterns = new ActivatableHashSet();
this.exclusionURIs = new ActivatableHashSet();
this.scopeChangedListeners = scopeChangeListeners;
}
@Override
public long getScopeId() {
activate(ActivationPurpose.READ);
return id;
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
private void checkReadOnly() {
if(isReadOnly) {
throw new IllegalStateException("Attempt to modify TargetScope instance which is marked Read Only");
}
}
@Override
public void setName(String name) {
activate(ActivationPurpose.READ);
checkReadOnly();
this.name = name;
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public synchronized void addScopeURI(URI uri) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (scopeURIs) {
scopeURIs.add(uri.toString());
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public synchronized void removeScopeURI(URI uri, boolean removeContained) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (scopeURIs) {
scopeURIs.remove(uri.toString());
if(removeContained) {
removeContainedURIs(uri);
}
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
private void removeContainedURIs(URI base) {
final List current = new ArrayList(scopeURIs);
for(String uriStr: current) {
if(UriTools.doesBaseUriContain(base, URI.create(uriStr))) {
scopeURIs.remove(uriStr);
}
}
}
@Override
public synchronized Collection getScopeURIs() {
activate(ActivationPurpose.READ);
final List ret = new ArrayList();
synchronized (scopeURIs) {
for(String uriStr: scopeURIs) {
ret.add(URI.create(uriStr));
}
return Collections.unmodifiableCollection(ret);
}
}
@Override
public void addExclusionPattern(String pattern) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (exclusionPatterns) {
exclusionPatterns.add(pattern);
compiledPatterns = compilePatterns();
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public void addExclusionURI(URI uri) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (exclusionURIs) {
exclusionURIs.add(uri.toString());
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public void removeExclusionPattern(String pattern) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized(exclusionPatterns) {
exclusionPatterns.remove(pattern);
compiledPatterns = compilePatterns();
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public void removeExclusionURI(URI uri) {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (exclusionURIs) {
exclusionURIs.remove(uri.toString());
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public Collection getExclusionPatterns() {
activate(ActivationPurpose.READ);
synchronized(exclusionPatterns) {
return Collections.unmodifiableCollection(new ArrayList(exclusionPatterns));
}
}
@Override
public Collection getExclusionURIs() {
activate(ActivationPurpose.READ);
final List ret = new ArrayList();
synchronized (exclusionURIs) {
for(String uriStr: exclusionURIs) {
ret.add(URI.create(uriStr));
}
return Collections.unmodifiableCollection(ret);
}
}
@Override
public boolean isExcluded(URI uri) {
activate(ActivationPurpose.READ);
final String uriString = uri.toString();
for(Pattern p: getCompiledPatterns()) {
if(p.matcher(uriString).find()) {
return true;
}
}
synchronized (exclusionURIs) {
for(String uriStr: exclusionURIs) {
if(UriTools.doesBaseUriContain(URI.create(uriStr), uri)) {
return true;
}
}
}
return false;
}
@Override
public boolean isExcluded(HttpHost host, String uriPath) {
activate(ActivationPurpose.READ);
final String uriString = host.toString() + uriPath;
for(Pattern p: getCompiledPatterns()) {
if(p.matcher(uriString).find()) {
return true;
}
}
synchronized (exclusionURIs) {
for(String uriStr: exclusionURIs) {
if(matchesBase(URI.create(uriStr), host, uriPath)) {
return true;
}
}
}
return false;
}
@Override
public boolean isInsideScope(URI uri) {
activate(ActivationPurpose.READ);
synchronized (scopeURIs) {
for(String uriStr: scopeURIs) {
if(UriTools.doesBaseUriContain(URI.create(uriStr), uri)) {
return true;
}
}
}
return false;
}
@Override
public boolean isInsideScope(HttpHost host, String uriPath) {
activate(ActivationPurpose.READ);
synchronized (scopeURIs) {
for(String uriStr: scopeURIs) {
if(matchesBase(URI.create(uriStr), host, uriPath)) {
return true;
}
}
}
return false;
}
private boolean matchesBase(URI baseURI, HttpHost host, String uriPath) {
final HttpHost baseHost = URIUtils.extractHost(baseURI);
final String basePath = getPathPart(baseURI);
if(!hostsMatch(baseHost, host)) {
return false;
}
return uriPath.startsWith(basePath);
}
private boolean hostsMatch(HttpHost h1, HttpHost h2) {
return stringsMatch(h1.getHostName(), h2.getHostName()) &&
stringsMatch(h1.getSchemeName(), h2.getSchemeName()) &&
portsMatch(h1.getSchemeName(), h1.getPort(), h2.getPort());
}
private boolean stringsMatch(String s1, String s2) {
if(s1 == null && s2 != null) {
return false;
}
return s1.equalsIgnoreCase(s2);
}
private boolean portsMatch(String scheme, int p1, int p2) {
if(p1 == p2) {
return true;
} else if(
"http".equalsIgnoreCase(scheme) && (
((p1 == -1) && (p2 == 80)) ||
((p1 == 80) && (p2 == -1)))) {
return true;
} else if(
"https".equalsIgnoreCase(scheme) && (
((p1 == -1) && (p2 == 443)) ||
((p1 == 443) && (p2 == -1)))) {
return true;
} else {
return false;
}
}
private String getPathPart(URI uri) {
if(uri.getQuery() == null) {
return uri.getPath();
} else {
return uri.getPath() + '?' + uri.getQuery();
}
}
@Override
public boolean filter(URI uri) {
return isInsideScope(uri) && !isExcluded(uri);
}
@Override
public boolean filter(HttpHost host, String uri) {
return isInsideScope(host, uri) && !isExcluded(host, uri);
}
@Override
public void clear() {
activate(ActivationPurpose.READ);
checkReadOnly();
synchronized (scopeURIs) {
synchronized (exclusionPatterns) {
scopeURIs.clear();
exclusionPatterns.clear();
exclusionURIs.clear();
}
}
activate(ActivationPurpose.WRITE);
notifyIfActiveScope();
}
@Override
public boolean isEmpty() {
return scopeURIs.isEmpty();
}
@Override
public boolean isActiveScope() {
activate(ActivationPurpose.READ);
return isActiveScope;
}
@Override
public void setReadOnly(boolean value) {
activate(ActivationPurpose.READ);
isReadOnly = value;
activate(ActivationPurpose.WRITE);
}
public void setDetached(boolean value) {
activate(ActivationPurpose.READ);
if(value && isActiveScope) {
throw new IllegalStateException("Cannot detach the active scope.");
}
if(value && isDefault) {
throw new IllegalStateException("Cannot detach the default scope");
}
isDetached = value;
activate(ActivationPurpose.WRITE);
}
@Override
public boolean isReadOnly() {
activate(ActivationPurpose.READ);
return isReadOnly;
}
@Override
public boolean isDetached() {
return isDetached;
}
public void setIsActiveScope(boolean flag) {
activate(ActivationPurpose.READ);
if(flag && isDetached) {
throw new IllegalStateException("Cannot use a detached scope as the active scope");
}
isActiveScope = flag;
activate(ActivationPurpose.WRITE);
}
@Override
public boolean isDefaultScope() {
activate(ActivationPurpose.READ);
return isDefault;
}
private List getCompiledPatterns() {
synchronized (exclusionPatterns) {
if(compiledPatterns == null) {
compiledPatterns = compilePatterns();
}
}
return compiledPatterns;
}
private List compilePatterns() {
activate(ActivationPurpose.READ);
final List patterns = new ArrayList();
for(String regex: exclusionPatterns) {
patterns.add(Pattern.compile(regex));
}
return patterns;
}
@Override
public String toString() {
return getName();
}
private void notifyIfActiveScope() {
if(isActiveScope) {
scopeChangedListeners.fireEvent(new ActiveScopeChangedEvent(this));
}
}
void setEventListenerManager(EventListenerManager mgr) {
this.scopeChangedListeners = mgr;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/scope/TargetScopeId.java
================================================
package com.subgraph.vega.internal.model.scope;
public class TargetScopeId {
private long currentId = 0;
synchronized long allocateId() {
final long ret = currentId;
currentId ++;
return ret;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/scope/TargetScopeManager.java
================================================
package com.subgraph.vega.internal.model.scope;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.events.CancellableObjectEventArgs;
import com.db4o.events.Event4;
import com.db4o.events.EventListener4;
import com.db4o.events.EventRegistry;
import com.db4o.events.EventRegistryFactory;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.scope.ActiveScopeChangedEvent;
import com.subgraph.vega.api.model.scope.ITargetScope;
import com.subgraph.vega.api.model.scope.ITargetScopeManager;
public class TargetScopeManager implements ITargetScopeManager {
private final ObjectContainer database;
private final TargetScopeId scopeId;
private final EventListenerManager scopeChangeListeners;
private ITargetScope activeScope;
private ITargetScope defaultScope;
public TargetScopeManager(ObjectContainer database) {
this.database = database;
this.scopeId = getTargetScopeId(database);
scopeChangeListeners = new EventListenerManager();
final EventRegistry registry = EventRegistryFactory.forObjectContainer(database);
registry.activating().addListener(new EventListener4() {
@Override
public void onEvent(Event4 e,
CancellableObjectEventArgs args) {
final Object ob = args.object();
if(ob instanceof TargetScope) {
((TargetScope)ob).setEventListenerManager(scopeChangeListeners);
}
}
});
defaultScope = findDefaultScope();
activeScope = findActiveScope();
}
private TargetScopeId getTargetScopeId(ObjectContainer database) {
List result = database.query(TargetScopeId.class);
if(result.size() == 0) {
final TargetScopeId tsi = new TargetScopeId();
database.store(tsi);
return tsi;
} else if(result.size() == 1) {
return result.get(0);
} else {
throw new IllegalStateException("Database corrupted, found multiple TargetScopeId instances");
}
}
@Override
public ITargetScope createNewScope() {
return createNewScope("New Scope");
}
@Override
public ITargetScope createDuplicatedScope(ITargetScope scope) {
final ITargetScope newScope = createNewScope(scope.getName());
for(URI u: scope.getScopeURIs()) {
newScope.addScopeURI(u);
}
for(URI u: scope.getExclusionURIs()) {
newScope.addExclusionURI(u);
}
for(String s: scope.getExclusionPatterns()) {
newScope.addExclusionPattern(s);
}
return newScope;
}
private ITargetScope createNewScope(String name) {
final long id = scopeId.allocateId();
final ITargetScope scope = new TargetScope(id, false, scopeChangeListeners);
scope.setName(name);
return scope;
}
private ITargetScope createDefaultScope() {
final long id = scopeId.allocateId();
final ITargetScope scope = new TargetScope(id, true, scopeChangeListeners);
((TargetScope)scope).setIsActiveScope(true);
scope.setName("Default Scope");
database.store(scope);
return scope;
}
@Override
public void saveScope(ITargetScope scope) {
database.store(scope);
}
@Override
public boolean removeScope(ITargetScope scope) {
if(scope == defaultScope) {
return false;
} else if(scope == activeScope) {
setActiveScope(defaultScope);
}
database.delete(scope);
return true;
}
@Override
public Collection getAllScopes() {
return database.query(ITargetScope.class);
}
@Override
public ITargetScope getActiveScope() {
return activeScope;
}
@Override
public ITargetScope getDefaultScope() {
return defaultScope;
}
@Override
public void setActiveScope(ITargetScope scope) {
if(scope == activeScope || !database.ext().isStored(scope)) {
return;
}
synchronized (this) {
((TargetScope)activeScope).setIsActiveScope(false);
((TargetScope)scope).setIsActiveScope(true);
activeScope = scope;
scopeChangeListeners.fireEvent(new ActiveScopeChangedEvent(activeScope));
}
}
@Override
public void setScopeDetached(ITargetScope scope) {
if(scope.isActiveScope()) {
setActiveScope(defaultScope);
}
((TargetScope)scope).setDetached(true);
}
@Override
public void setScopeAttached(ITargetScope scope) {
((TargetScope)scope).setDetached(false);
}
@Override
public ITargetScope addActiveScopeChangeListener(IEventHandler listener) {
synchronized (this) {
scopeChangeListeners.addListener(listener);
return activeScope;
}
}
@Override
public void removeActiveScopeChangeListener(IEventHandler listener) {
scopeChangeListeners.removeListener(listener);
}
private ITargetScope findDefaultScope() {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(ITargetScope scope) {
return scope.isDefaultScope();
}
});
if(results.size() == 0) {
return createDefaultScope();
}
return results.get(0);
}
private ITargetScope findActiveScope() {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(ITargetScope scope) {
return scope.isActiveScope();
}
});
if(results.size() == 0) {
final ITargetScope active = findDefaultScope();
((TargetScope)active).setIsActiveScope(true);
return active;
}
return results.get(0);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/tags/Tag.java
================================================
package com.subgraph.vega.internal.model.tags;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.tags.ITag;
public class Tag implements ITag, Activatable {
private transient Activator activator;
private String name;
private String description;
private int nameColor;
private int rowColor;
public Tag() {
rowColor = 0xffffff;
}
public Tag(ITag tag) {
name = tag.getName();
description = tag.getDescription();
nameColor = tag.getNameColor();
rowColor = tag.getRowColor();
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
@Override
public void setName(String name) {
activate(ActivationPurpose.READ);
this.name = name;
activate(ActivationPurpose.WRITE);
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public void setDescription(String description) {
activate(ActivationPurpose.READ);
this.description = description;
activate(ActivationPurpose.WRITE);
}
@Override
public String getDescription() {
activate(ActivationPurpose.READ);
return description;
}
@Override
public void setNameColor(int color) {
activate(ActivationPurpose.READ);
nameColor = color;
activate(ActivationPurpose.WRITE);
}
@Override
public int getNameColor() {
activate(ActivationPurpose.READ);
return nameColor;
}
@Override
public void setRowColor(int color) {
activate(ActivationPurpose.READ);
rowColor = color;
activate(ActivationPurpose.WRITE);
}
@Override
public int getRowColor() {
activate(ActivationPurpose.READ);
return rowColor;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/tags/TagModel.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.tags;
import java.util.Collection;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.model.tags.ITag;
import com.subgraph.vega.api.model.tags.ITagModel;
public class TagModel implements ITagModel {
private ObjectContainer database;
public TagModel(ObjectContainer database) {
this.database = database;
}
@Override
public Collection getAllTags() {
return database.query(ITag.class);
}
@Override
public ITag createTag() {
return new Tag();
}
@Override
public ITag createTag(ITag tag) {
return new Tag(tag);
}
@Override
public void store(ITag tag) {
database.store(tag);
}
@Override
public boolean isTagStored(ITag tag) {
return database.ext().isStored(tag);
}
@Override
public ITag getTagByName(final String name) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(ITag tag) {
return name.equals(tag.getName());
}
});
if (results.size() == 0) {
return null;
}
return results.get(0);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/variables/Variable.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.variables;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.variables.IVariable;
public class Variable implements IVariable, Activatable {
private transient Activator activator;
private String name;
private String description;
@Override
public void setName(String name) {
activate(ActivationPurpose.READ);
this.name = name;
activate(ActivationPurpose.WRITE);
}
@Override
public String getName() {
activate(ActivationPurpose.READ);
return name;
}
@Override
public void setDescription(String description) {
activate(ActivationPurpose.READ);
this.description = description;
activate(ActivationPurpose.WRITE);
}
@Override
public String getDescription() {
activate(ActivationPurpose.READ);
return description;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if (activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if (this.activator == activator) {
return;
}
if (activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/variables/VariableModel.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.variables;
import java.util.Collection;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.model.variables.IVariable;
import com.subgraph.vega.api.model.variables.IVariableModel;
public class VariableModel implements IVariableModel {
private ObjectContainer database;
public VariableModel(ObjectContainer database) {
this.database = database;
}
@Override
public Collection getAllIdentities() {
return database.query(IVariable.class);
}
@Override
public IVariable createVariable() {
return new Variable();
}
@Override
public void store(IVariable variable) {
database.store(variable);
}
@Override
public boolean isVariableStored(IVariable variable) {
return database.ext().isStored(variable);
}
@Override
public IVariable getVariableByName(final String name) {
final List results = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IVariable tag) {
return name.equals(tag.getName());
}
});
if (results.size() == 0) {
return null;
}
return results.get(0);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebEntity.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import java.util.List;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.IModelProperties;
import com.subgraph.vega.api.model.web.IWebEntity;
import com.subgraph.vega.api.model.web.NewWebEntityEvent;
import com.subgraph.vega.api.model.web.UpdatedWebEntityEvent;
import com.subgraph.vega.internal.model.ModelProperties;
public abstract class WebEntity implements IWebEntity, Activatable {
private transient Activator activator;
protected transient EventListenerManager eventManager;
protected transient ObjectContainer database;
private boolean visitedFlag;
private boolean scannedFlag;
private IModelProperties properties = new ModelProperties();
protected WebEntity(EventListenerManager eventManager, ObjectContainer database) {
this.eventManager = eventManager;
this.database = database;
}
@Override
public boolean isVisited() {
activate(ActivationPurpose.READ);
return visitedFlag;
}
@Override
public void setVisited(boolean notify) {
activate(ActivationPurpose.READ);
if(getParent() != null)
getParent().setVisited(notify);
if(!visitedFlag) {
visitedFlag = true;
activate(ActivationPurpose.WRITE);
if(notify)
notifyUpdatedEntity(this);
}
}
@Override
public boolean isScanned() {
activate(ActivationPurpose.READ);
return scannedFlag;
}
@Override
public void setScanned() {
activate(ActivationPurpose.READ);
scannedFlag = true;
activate(ActivationPurpose.WRITE);
}
@Override
public void setProperty(String name, Object value) {
activate(ActivationPurpose.READ);
properties.setProperty(name, value);
}
@Override
public void setStringProperty(String name, String value) {
activate(ActivationPurpose.READ);
properties.setStringProperty(name, value);
}
@Override
public void setIntegerProperty(String name, int value) {
activate(ActivationPurpose.READ);
properties.setIntegerProperty(name, value);
}
@Override
public Object getProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getProperty(name);
}
@Override
public String getStringProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getStringProperty(name);
}
@Override
public Integer getIntegerProperty(String name) {
activate(ActivationPurpose.READ);
return properties.getIntegerProperty(name);
}
@Override
public List propertyKeys() {
activate(ActivationPurpose.READ);
return properties.propertyKeys();
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
void setEventManager(EventListenerManager eventManager) {
this.eventManager = eventManager;
}
void setDatabase(ObjectContainer database) {
if(this.database == null)
this.database = database;
}
ObjectContainer getDatabase() {
return database;
}
void notifyNewEntity(IWebEntity entity) {
if(eventManager != null)
eventManager.fireEvent(new NewWebEntityEvent(entity));
}
void notifyUpdatedEntity(IWebEntity entity) {
if(eventManager != null)
eventManager.fireEvent(new UpdatedWebEntityEvent(entity));
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebHost.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import static com.google.common.base.Preconditions.checkNotNull;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpHost;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.google.common.base.Objects;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.web.IWebEntity;
import com.subgraph.vega.api.model.web.IWebHost;
import com.subgraph.vega.api.model.web.IWebModelVisitor;
import com.subgraph.vega.api.model.web.IWebMountPoint;
public class WebHost extends WebEntity implements IWebHost {
static WebHost createWebHost(EventListenerManager eventManager, ObjectContainer database, HttpHost host) {
final WebMountPoint rootMountPoint = WebMountPoint.createRootMountPoint(eventManager, database, checkNotNull(host));
final WebHost webHost = new WebHost(eventManager, database, host, rootMountPoint);
rootMountPoint.setWebHost(webHost);
return webHost;
}
private final HttpHost host;
private final WebMountPoint mountPoint;
private final WebPath rootPath;
private transient URI cachedUri;
private WebHost(EventListenerManager eventManager, ObjectContainer database, HttpHost host, WebMountPoint rootMountPoint) {
super(eventManager, database);
if(host.getHostName().isEmpty()) {
throw new IllegalArgumentException("Hostname is empty");
}
hostToUri(host);
this.host = host;
this.mountPoint = rootMountPoint;
this.rootPath = rootMountPoint.getMountPath();
}
@Override
public HttpHost getHttpHost() {
activate(ActivationPurpose.READ);
return host;
}
@Override
public String getScheme() {
return getHttpHost().getSchemeName();
}
@Override
public String getHostname() {
return getHttpHost().getHostName();
}
@Override
public int getPort() {
return getHttpHost().getPort();
}
@Override
public IWebMountPoint getRootMountPoint() {
activate(ActivationPurpose.READ);
return mountPoint;
}
@Override
public WebPath getRootPath() {
activate(ActivationPurpose.READ);
return rootPath;
}
@Override
public URI getUri() {
activate(ActivationPurpose.READ);
synchronized(this) {
if(cachedUri == null)
cachedUri = generateUri();
return cachedUri;
}
}
private static URI hostToUri(HttpHost host) {
try {
return new URI(host.getSchemeName(), null, host.getHostName(), host.getPort(), null, null, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException("Unable to convert host to URI: "+ host);
}
}
private URI generateUri() {
return hostToUri(host);
}
@Override
public WebPath addPath(String path) {
activate(ActivationPurpose.READ);
WebPath wp = getRootPath();
for(String s: path.split("/")) {
if(!s.isEmpty()) {
wp = wp.addChildPath(s);
}
}
return wp;
}
@Override
public boolean equals(Object other) {
if(this == other)
return true;
else if(other instanceof WebHost) {
WebHost that = (WebHost) other;
return this.getHttpHost().equals(that.getHttpHost());
} else {
return false;
}
}
@Override
public int hashCode() {
return getHttpHost().hashCode();
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("host", getHttpHost()).toString();
}
@Override
public IWebEntity getParent() {
activate(ActivationPurpose.READ);
return null;
}
@Override
public void accept(IWebModelVisitor visitor) {
visitor.visit(this);
getRootPath().accept(visitor);
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebModel.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import java.util.Collection;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.w3c.dom.html2.HTMLDocument;
import com.db4o.ObjectContainer;
import com.db4o.events.CancellableObjectEventArgs;
import com.db4o.events.Event4;
import com.db4o.events.EventListener4;
import com.db4o.events.EventRegistry;
import com.db4o.events.EventRegistryFactory;
import com.db4o.query.Predicate;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.model.web.IWebEntity;
import com.subgraph.vega.api.model.web.IWebHost;
import com.subgraph.vega.api.model.web.IWebModel;
import com.subgraph.vega.api.model.web.IWebModelVisitor;
import com.subgraph.vega.api.model.web.IWebPath;
import com.subgraph.vega.api.model.web.NewWebEntityEvent;
import com.subgraph.vega.api.model.web.forms.IWebForm;
import com.subgraph.vega.api.util.VegaURI;
import com.subgraph.vega.internal.model.web.forms.FormParser;
public class WebModel implements IWebModel {
private final EventListenerManager eventManager = new EventListenerManager();
private final ObjectContainer database;
private final FormParser formParser;
public WebModel(ObjectContainer database) {
this.formParser = new FormParser(this);
this.database = database;
EventRegistry registry = EventRegistryFactory.forObjectContainer(database);
registry.activating().addListener(new EventListener4() {
@Override
public void onEvent(Event4 e,
CancellableObjectEventArgs args) {
final Object ob = args.object();
if(ob instanceof WebEntity) {
final WebEntity entity = (WebEntity) ob;
entity.setEventManager(eventManager);
entity.setDatabase(WebModel.this.database);
}
}
});
}
@Override
synchronized public Collection getAllWebHosts() {
return database.query(IWebHost.class);
}
@Override
public Collection getUnscannedHosts() {
return database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IWebHost host) {
return host.isScanned() == false;
}
});
}
@Override
public Collection getUnscannedPaths() {
final List paths = database.query(new Predicate() {
private static final long serialVersionUID = 1L;
@Override
public boolean match(IWebPath path) {
return path.isScanned() == false;
}
});
return paths;
}
@Override
public Collection getAllPaths() {
return database.query(IWebPath.class);
}
@Override
public synchronized IWebPath getWebPathByUri(VegaURI uri) {
final HttpHost host = uri.getTargetHost();
if (host != null) {
IWebHost wh = getWebHostByHttpHost(host);
if(wh == null) {
wh = createWebHostFromHttpHost(host);
}
return wh.addPath(uri.getPath());
} else {
return null;
}
}
@Override
public IWebPath addGetTarget(VegaURI uri) {
final IWebPath path = getWebPathByUri(uri);
if (path != null) {
List params = URLEncodedUtils.parse(uri.getQuery(), Consts.UTF_8);
path.addGetParameterList(params);
}
return path;
}
@Override
synchronized public WebHost getWebHostByHttpHost(HttpHost host) {
for(WebHost wh: database.query(WebHost.class)) {
if(wh.getHttpHost().equals(host))
return wh;
}
return null;
}
@Override
synchronized public IWebHost createWebHostFromHttpHost(HttpHost host) {
final WebHost wh = getWebHostByHttpHost(host);
if(wh != null)
return wh;
final WebHost newHost = WebHost.createWebHost(eventManager, database, host);
newHost.setDatabase(database);
newHost.getRootPath().setDatabase(database);
database.store(newHost);
database.store(newHost.getRootMountPoint());
database.store(newHost.getRootPath());
notifyNewEntity(newHost);
return newHost;
}
@Override
public void addChangeListenerAndPopulate(IEventHandler listener) {
synchronized(this) {
for(IWebHost wh: getAllWebHosts()) {
listener.handleEvent(new NewWebEntityEvent(wh));
}
eventManager.addListener(listener);
}
}
@Override
public void removeChangeListener(IEventHandler listener) {
eventManager.removeListener(listener);
}
private void notifyNewEntity(IWebEntity entity) {
eventManager.fireEvent(new NewWebEntityEvent(entity));
}
@Override
public Collection parseForms(IWebPath source,
HTMLDocument document) {
return formParser.parseForms(source, document);
}
@Override
public void accept(IWebModelVisitor visitor) {
for(IWebHost host: getAllWebHosts()) {
host.accept(visitor);
}
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebMountPoint.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import org.apache.http.HttpHost;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.web.IWebHost;
import com.subgraph.vega.api.model.web.IWebMountPoint;
public class WebMountPoint implements IWebMountPoint, Activatable {
static WebMountPoint createRootMountPoint(EventListenerManager eventManager, ObjectContainer database, HttpHost httpHost) {
WebPath rootPath = WebPath.createRootPath(eventManager, database);
final WebMountPoint mountPoint = new WebMountPoint(rootPath);
rootPath.setMountPoint(mountPoint);
return mountPoint;
}
private transient Activator activator;
private IWebHost host;
private final WebPath path;
WebMountPoint() {
this.path = null;
this.host = null;
}
private WebMountPoint(WebPath rootPath) {
this.path = rootPath;
this.host = null;
}
WebMountPoint(IWebHost host, WebPath path) {
this.host = host;
this.path = path;
}
@Override
public IWebHost getWebHost() {
activate(ActivationPurpose.READ);
return host;
}
@Override
public WebPath getMountPath() {
activate(ActivationPurpose.READ);
return path;
}
void setWebHost(IWebHost host) {
activate(ActivationPurpose.READ);
this.host = host;
activate(ActivationPurpose.WRITE);
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebPath.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.db4o.collections.ActivatableHashMap;
import com.google.common.base.Objects;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.web.IWebEntity;
import com.subgraph.vega.api.model.web.IWebModelVisitor;
import com.subgraph.vega.api.model.web.IWebMountPoint;
import com.subgraph.vega.api.model.web.IWebPath;
import com.subgraph.vega.api.model.web.IWebPathParameters;
import com.subgraph.vega.api.model.web.IWebResponse;
public class WebPath extends WebEntity implements IWebPath {
static WebPath createRootPath(EventListenerManager eventManager, ObjectContainer database) {
return new WebPath(eventManager, database, null, "");
}
private final WebPath parentPath;
private final String pathComponent;
private final Map childPathMap = new ActivatableHashMap();
private IWebMountPoint mountPoint;
private final WebPathParameters getParameters = new WebPathParameters();
private final WebPathParameters postParameters = new WebPathParameters();
private final Map, IWebResponse> getResponses = new ActivatableHashMap, IWebResponse>();
private final Map, IWebResponse> postResponses = new ActivatableHashMap, IWebResponse>();
private PathType pathType;
private String mimeType;
private transient URI cachedUri;
private transient String cachedFullPath;
private WebPath(EventListenerManager eventManager, ObjectContainer database, WebPath parentPath, String pathComponent) {
this(eventManager, database, parentPath, pathComponent, null);
}
WebPath(EventListenerManager eventManager, ObjectContainer database, WebPath parentPath, String pathComponent, IWebMountPoint mountPoint) {
super(eventManager, database);
this.parentPath = parentPath;
this.pathComponent = pathComponent;
this.mountPoint = mountPoint;
this.pathType = PathType.PATH_UNKNOWN;
}
@Override
public WebPath getParentPath() {
return parentPath;
}
@Override
public URI getUri() {
activate(ActivationPurpose.READ);
synchronized(this) {
if(cachedUri == null)
cachedUri = generateURI();
return cachedUri;
}
}
private URI generateURI() {
final URI hostUri = mountPoint.getWebHost().getUri();
try {
return new URI(hostUri.getScheme(), hostUri.getAuthority(), getFullPath(), null, null);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
@Override
public String getFullPath() {
if(cachedFullPath == null)
cachedFullPath = generateFullPath();
return cachedFullPath;
}
private String generateFullPath() {
activate(ActivationPurpose.READ);
if(parentPath == null)
return "/";
final String parentFullPath = parentPath.getFullPath();
if(parentFullPath.endsWith("/"))
return parentFullPath + pathComponent;
else
return parentFullPath + "/" + pathComponent;
}
@Override
public IWebMountPoint getMountPoint() {
activate(ActivationPurpose.READ);
return mountPoint;
}
@Override
public Collection getChildPaths() {
activate(ActivationPurpose.READ);
synchronized(childPathMap) {
return new HashSet(childPathMap.values());
}
}
void setMountPoint(IWebMountPoint mountPoint) {
activate(ActivationPurpose.READ);
this.mountPoint = mountPoint;
}
@Override
public boolean equals(Object other) {
if(this == other) {
return true;
} else if(other instanceof WebPath) {
WebPath that = (WebPath) other;
return this.getMountPoint().getWebHost().equals(that.getMountPoint().getWebHost()) &&
this.getFullPath().equals(that.getFullPath());
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hashCode(this.getMountPoint().getWebHost(), this.getFullPath());
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("host", mountPoint.getWebHost()).add("path", getFullPath()).toString();
}
@Override
public boolean isGetTarget() {
activate(ActivationPurpose.READ);
return getParameters.hasParameters();
}
@Override
public boolean isPostTarget() {
activate(ActivationPurpose.READ);
return postParameters.hasParameters();
}
@Override
public void addGetParameterList(List params) {
activate(ActivationPurpose.READ);
getParameters.addParameterList(params);
}
@Override
public void addPostParameterList(List params) {
activate(ActivationPurpose.READ);
postParameters.addParameterList(params);
}
@Override
public IWebPathParameters getGetParameters() {
activate(ActivationPurpose.READ);
return getParameters;
}
@Override
public IWebPathParameters getPostParameters() {
activate(ActivationPurpose.READ);
return postParameters;
}
@Override
public IWebPath getChildPath(String pathComponent) {
activate(ActivationPurpose.READ);
synchronized(childPathMap) {
return childPathMap.get(pathComponent);
}
}
@Override
public WebPath addChildPath(String pathComponent) {
activate(ActivationPurpose.READ);
synchronized(childPathMap) {
if(childPathMap.containsKey(pathComponent))
return childPathMap.get(pathComponent);
WebPath newPath = new WebPath(eventManager, database, this, pathComponent, getMountPoint());
ObjectContainer database = getDatabase();
database.store(newPath);
newPath.setDatabase(database);
childPathMap.put(pathComponent, newPath);
notifyNewEntity(newPath);
return newPath;
}
}
@Override
public String getPathComponent() {
activate(ActivationPurpose.READ);
return pathComponent;
}
@Override
public List getGetResponses() {
activate(ActivationPurpose.READ);
synchronized(getResponses) {
return Collections.unmodifiableList(new ArrayList(getResponses.values()));
}
}
@Override
public List getPostResponses() {
activate(ActivationPurpose.READ);
synchronized(postResponses) {
return Collections.unmodifiableList(new ArrayList(postResponses.values()));
}
}
@Override
public IWebEntity getParent() {
activate(ActivationPurpose.READ);
if(parentPath != null)
return parentPath;
else if(mountPoint != null)
return mountPoint.getWebHost();
else
return null;
}
@Override
public void addPostResponse(List parameters, String mimeType) {
activate(ActivationPurpose.READ);
synchronized(postResponses) {
maybeAddWebResponse(postResponses, parameters, mimeType);
}
}
@Override
public void addGetResponse(String query, String mimeType) {
activate(ActivationPurpose.READ);
synchronized(getResponses) {
maybeAddWebResponse(getResponses, parseParameters(query), mimeType);
}
}
private void maybeAddWebResponse(Map, IWebResponse> responseMap, List parameters, String mimeType) {
if(responseMap.containsKey(parameters)) {
final IWebResponse wr = responseMap.get(parameters);
if(mimeType == null || mimeType.equals(wr.getMimeType()))
return;
}
// Possibly overwrite a map entry with a new entry that has same query but different mime type
final IWebResponse newResponse = createWebResponse(parameters, mimeType);
responseMap.put(parameters, newResponse);
notifyNewEntity(newResponse);
}
private WebResponse createWebResponse(List parameters, String mimeType) {
WebResponse response = new WebResponse(eventManager, database, this, parameters, mimeType);
ObjectContainer database = getDatabase();
response.setDatabase(database);
database.store(response);
return response;
}
private static List parseParameters(String query) {
if(query == null || query.isEmpty())
return Collections.emptyList();
final List parameterList = new ArrayList();
try {
URLEncodedUtils.parse(parameterList, new Scanner(query), "UTF-8");
} catch (RuntimeException e) {
parameterList.clear();
parameterList.add(new BasicNameValuePair(query, null));
}
return parameterList;
}
@Override
public void setPathType(PathType type) {
activate(ActivationPurpose.READ);
this.pathType = type;
cachedFullPath = null;
cachedUri = null;
activate(ActivationPurpose.WRITE);
}
@Override
public PathType getPathType() {
activate(ActivationPurpose.READ);
return pathType;
}
@Override
public void setMimeType(String mimeType) {
activate(ActivationPurpose.READ);
this.mimeType = mimeType;
activate(ActivationPurpose.WRITE);
}
@Override
public String getMimeType() {
activate(ActivationPurpose.READ);
return mimeType;
}
@Override
public void accept(IWebModelVisitor visitor) {
visitor.visit(this);
for(IWebPath child: getChildPaths()) {
child.accept(visitor);
}
for(IWebResponse response: getGetResponses()) {
response.accept(visitor);
}
for(IWebResponse r: getPostResponses()) {
r.accept(visitor);
}
}
@Override
public HttpHost getHttpHost() {
return mountPoint.getWebHost().getHttpHost();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebPathParameters.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.http.NameValuePair;
import com.db4o.activation.ActivationPurpose;
import com.db4o.activation.Activator;
import com.db4o.collections.ActivatableHashSet;
import com.db4o.ta.Activatable;
import com.subgraph.vega.api.model.web.IWebPathParameters;
public class WebPathParameters implements IWebPathParameters, Activatable {
private transient Activator activator;
private final Set> parameterLists;
WebPathParameters() {
this.parameterLists = new ActivatableHashSet>();
}
void addParameterList(List params) {
if(params.isEmpty())
return;
activate(ActivationPurpose.READ);
synchronized(parameterLists) {
if(parameterLists.contains(params))
return;
parameterLists.add(params);
}
}
public Collection getValuesForParameter(String name) {
final Set valueSet = new HashSet();
for(List params: getParameterLists()) {
for(NameValuePair pair: params) {
if(pair.getName().equals(name)) {
valueSet.add(pair.getValue());
}
}
}
return valueSet;
}
@Override
public boolean hasParameters() {
activate(ActivationPurpose.READ);
synchronized(parameterLists) {
return !parameterLists.isEmpty();
}
}
@Override
public Collection> getParameterLists() {
activate(ActivationPurpose.READ);
synchronized(parameterLists) {
return new HashSet>(parameterLists);
}
}
@Override
public Collection getParameterNames() {
final Set nameSet = new HashSet();
for(List params: getParameterLists()) {
for(NameValuePair pair: params) {
nameSet.add(pair.getName());
}
}
return nameSet;
}
@Override
public Collection> getParameterNameLists() {
final Set< List > nameLists = new HashSet>();
for(List params: getParameterLists()) {
List nl = new ArrayList();
for(NameValuePair pair: params) {
nl.add(pair.getName());
}
nameLists.add(nl);
}
return nameLists;
}
@Override
public void activate(ActivationPurpose activationPurpose) {
if(activator != null) {
activator.activate(activationPurpose);
}
}
@Override
public void bind(Activator activator) {
if(this.activator == activator) {
return;
}
if(activator != null && this.activator != null) {
throw new IllegalStateException("Object can only be bound to one activator");
}
this.activator = activator;
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/WebResponse.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web;
import java.util.Collections;
import java.util.List;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import com.db4o.ObjectContainer;
import com.db4o.activation.ActivationPurpose;
import com.subgraph.vega.api.events.EventListenerManager;
import com.subgraph.vega.api.model.web.IWebEntity;
import com.subgraph.vega.api.model.web.IWebModelVisitor;
import com.subgraph.vega.api.model.web.IWebPath;
import com.subgraph.vega.api.model.web.IWebResponse;
public class WebResponse extends WebEntity implements IWebResponse {
private final IWebPath parentPath;
private final List parameters;
private final String mimeType;
private transient String cachedQueryString;
WebResponse(EventListenerManager eventManager, ObjectContainer database, IWebPath parentPath, List parameters, String mimeType) {
super(eventManager, database);
this.parentPath = parentPath;
this.mimeType = mimeType;
this.parameters = parameters;
setVisited(true);
}
@Override
public List getRequestParameters() {
activate(ActivationPurpose.READ);
return Collections.unmodifiableList(parameters);
}
@Override
public String getMimeType() {
activate(ActivationPurpose.READ);
return mimeType;
}
@Override
public IWebEntity getParent() {
activate(ActivationPurpose.READ);
return parentPath;
}
@Override
public String getQueryString() {
activate(ActivationPurpose.READ);
synchronized(this) {
if(cachedQueryString == null) {
cachedQueryString = createQueryString();
}
return cachedQueryString;
}
}
private String createQueryString() {
final StringBuilder sb = new StringBuilder();
for(NameValuePair pair: parameters) {
if(sb.length() > 0)
sb.append("&");
sb.append(pair.getName());
if(pair.getValue() != null) {
sb.append("=");
sb.append(pair.getValue());
}
}
return sb.toString();
}
@Override
public IWebPath getPathEntity() {
activate(ActivationPurpose.READ);
return parentPath;
}
@Override
public void accept(IWebModelVisitor visitor) {
visitor.visit(this);
}
@Override
public HttpHost getHttpHost() {
return parentPath.getHttpHost();
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/forms/FormFiller.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web.forms;
import java.util.Set;
import com.subgraph.vega.api.model.web.forms.IWebFormField;
public class FormFiller {
String getDefaultValue(IWebFormField field) {
switch(field.getType()) {
case INPUT_TEXT:
return getDefaultTextValue(field);
case INPUT_PASSWORD:
case INPUT_FILE:
return "";
case INPUT_HIDDEN:
return field.getValue();
case INPUT_RADIO:
case SELECT_OPTION:
case INPUT_CHECKBOX:
return getDefaultMultipleValue(field);
case TEXTAREA:
return "Put Text here";
}
return "foo";
}
String getDefaultTextValue(IWebFormField field) {
return "foo";
}
String getDefaultPasswordValue(IWebFormField field) {
return "foo";
}
String getDefaultMultipleValue(IWebFormField field) {
if(!field.hasMultipleValues())
return "foo";
final String checkedValue = firstSetValue(field.getCheckedValues());
if(checkedValue != null)
return checkedValue;
final String oneValue = firstSetValue(field.getMultipleValues());
if(oneValue != null)
return oneValue;
return "foo";
}
private String firstSetValue(Set stringSet) {
if(stringSet.isEmpty())
return null;
return stringSet.toArray(new String[0])[0];
}
}
================================================
FILE: platform/com.subgraph.vega.model/src/com/subgraph/vega/internal/model/web/forms/FormParser.java
================================================
/*******************************************************************************
* Copyright (c) 2011 Subgraph.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Subgraph - initial API and implementation
******************************************************************************/
package com.subgraph.vega.internal.model.web.forms;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.w3c.dom.html2.HTMLCollection;
import org.w3c.dom.html2.HTMLDocument;
import org.w3c.dom.html2.HTMLElement;
import org.w3c.dom.html2.HTMLFormElement;
import org.w3c.dom.html2.HTMLInputElement;
import com.subgraph.vega.api.model.web.IWebPath;
import com.subgraph.vega.api.model.web.forms.IWebForm;
import com.subgraph.vega.internal.model.web.WebModel;
public class FormParser {
private final static Logger logger = Logger.getLogger("forms");
private final WebModel model;
public FormParser(WebModel model) {
this.model = model;
}
public Collection parseForms(IWebPath source, HTMLDocument document) {
final List