├── .classpath ├── .gitignore ├── .project ├── .settings ├── org.eclipse.jdt.core.prefs └── org.eclipse.m2e.core.prefs ├── LICENSE ├── README.md ├── build.fxbuild ├── data └── .empty ├── pom.xml ├── src ├── application │ ├── Main.java │ ├── application.css │ ├── business │ │ ├── ConfigurationService.java │ │ ├── CustomHostService.java │ │ ├── HostService.java │ │ ├── ServiceFactory.java │ │ ├── impl │ │ │ ├── ConfigurationServiceImpl.java │ │ │ ├── CustomHostServiceImpl.java │ │ │ ├── HostServiceImpl.java │ │ │ └── ServiceFactoryImpl.java │ │ └── repository │ │ │ ├── ConfigurationRepository.java │ │ │ ├── CustomHostRepository.java │ │ │ ├── HostRepository.java │ │ │ ├── Repository.java │ │ │ └── RepositoryFactory.java │ ├── conf │ │ └── Factory.java │ ├── model │ │ ├── Configuration.java │ │ ├── CustomHost.java │ │ └── Host.java │ ├── persistence │ │ └── sqlite │ │ │ ├── BaseSQLiteRepository.java │ │ │ ├── ConfigurationSQLiteRepository.java │ │ │ ├── CustomHostSQLiteRepository.java │ │ │ ├── HostSQLiteRepository.java │ │ │ ├── SQLiteRepositoryFactory.java │ │ │ └── util │ │ │ └── SQLiteJDBC.java │ ├── util │ │ ├── HostsFileManager.java │ │ ├── Logger.java │ │ ├── SystemUtil.java │ │ ├── WebUtil.java │ │ ├── WindowsUtil.java │ │ └── properties │ │ │ ├── Messages.java │ │ │ └── Settings.java │ └── view │ │ ├── ErrorAdminController.java │ │ ├── ErrorAdminDialog.fxml │ │ ├── ErrorDialog.fxml │ │ ├── ErrorDialogController.java │ │ ├── MainView.fxml │ │ ├── MainViewController.java │ │ └── RootLayout.fxml ├── configuration.properties ├── docs │ └── help_en.html ├── messages_en.properties └── resources │ ├── ico-big.png │ ├── ico.png │ └── main-tab.PNG └── test └── VihomaTesting.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | # Eclipse 26 | .project 27 | 28 | data/ 29 | target/ 30 | bin/ 31 | tmp/ -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | ViHoMa 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.xtext.ui.shared.xtextBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.m2e.core.maven2Builder 20 | 21 | 22 | 23 | 24 | 25 | org.eclipse.m2e.core.maven2Nature 26 | org.eclipse.xtext.ui.shared.xtextNature 27 | org.eclipse.jdt.core.javanature 28 | 29 | 30 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled 3 | org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore 4 | org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull 5 | org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= 6 | org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault 7 | org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= 8 | org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable 9 | org.eclipse.jdt.core.compiler.annotation.nullable.secondary= 10 | org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled 11 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 12 | org.eclipse.jdt.core.compiler.compliance=1.8 13 | org.eclipse.jdt.core.compiler.problem.APILeak=warning 14 | org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning 15 | org.eclipse.jdt.core.compiler.problem.autoboxing=ignore 16 | org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning 17 | org.eclipse.jdt.core.compiler.problem.deadCode=warning 18 | org.eclipse.jdt.core.compiler.problem.deprecation=warning 19 | org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled 20 | org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled 21 | org.eclipse.jdt.core.compiler.problem.discouragedReference=warning 22 | org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore 23 | org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore 24 | org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore 25 | org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled 26 | org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore 27 | org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning 28 | org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning 29 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 30 | org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning 31 | org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled 32 | org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning 33 | org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning 34 | org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore 35 | org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore 36 | org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning 37 | org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore 38 | org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore 39 | org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled 40 | org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore 41 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore 42 | org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled 43 | org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning 44 | org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore 45 | org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning 46 | org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning 47 | org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore 48 | org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning 49 | org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning 50 | org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error 51 | org.eclipse.jdt.core.compiler.problem.nullReference=warning 52 | org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error 53 | org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning 54 | org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning 55 | org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore 56 | org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning 57 | org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore 58 | org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore 59 | org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore 60 | org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning 61 | org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning 62 | org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore 63 | org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore 64 | org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore 65 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore 66 | org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore 67 | org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled 68 | org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning 69 | org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled 70 | org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled 71 | org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled 72 | org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore 73 | org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning 74 | org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning 75 | org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled 76 | org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning 77 | org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning 78 | org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore 79 | org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning 80 | org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning 81 | org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled 82 | org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info 83 | org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore 84 | org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore 85 | org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore 86 | org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning 87 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore 88 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled 89 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled 90 | org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled 91 | org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore 92 | org.eclipse.jdt.core.compiler.problem.unusedImport=warning 93 | org.eclipse.jdt.core.compiler.problem.unusedLabel=warning 94 | org.eclipse.jdt.core.compiler.problem.unusedLocal=warning 95 | org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore 96 | org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore 97 | org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled 98 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled 99 | org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled 100 | org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning 101 | org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore 102 | org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning 103 | org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning 104 | org.eclipse.jdt.core.compiler.release=disabled 105 | org.eclipse.jdt.core.compiler.source=1.8 106 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ViHoMa 2 | Vihoma logo 3 | Hi! You have reached the GIT repository for Vihoma, a Visual Hosts file Manager. 4 | 5 | ### What is Vihoma? 6 | Vihoma is a program that runs on your computer and helps the operating system to block connections to malicious websites. It's like an adblocker, but system-wide. You may manually block domains through its graphical interface, or let the program automatically do it for you. 7 | 8 | If you are a more advanced user, then Vihoma also lets you add domains with custom addresses: 9 | ![Vihoma main tab](https://raw.githubusercontent.com/cmabad/ViHoMa/master/src/resources/main-tab.PNG) 10 | 11 | ### How does it protect me? 12 | This app will download a list of hosts that are considered malicious, and tells your computer to avoid the connection to them by adding that list to a local file called `hosts`. 13 | It uses a consolidated hosts list provided by **Steven Black**. You can check his [Github repository](https://github.com/StevenBlack/hosts) for more information. 14 | 15 | ### What do I need to run it? 16 | Vihoma is built with Java 8 and JavaFX. You'll need to have **JRE 8** installed on your computer. Given that a system file is modified, **administration privileges** are required too. 17 | 18 | ### Where can I download it? 19 | You will find .zip files containing the program executable on [this](https://www.dropbox.com/sh/tdtitqzdbm6ij1z/AADVGZw6w4lVZM6lmipe7hDma?dl=0) dropbox folder. 20 | 21 | ### How do i run it? 22 | If you are on **Windows**, double click on the vihoma.bat file. 23 | 24 | If a **GNU/Linux**-based system is used, execute vihoma.sh. Make sure that you have an OpenJRE 8 instance installed. The JavaFX library is not included, so you must manually install openjfx too. *For example, using apt install openjfx*. 25 | 26 | *NOTE: Vihoma overwrites your system's hosts file. If you have previously modified it with custom hosts, you may want to backup the file first.* 27 | -------------------------------------------------------------------------------- /build.fxbuild: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /data/.empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cmabad/ViHoMa/b0210941c9289aaba62d93e0b47cd026472cfbfd/data/.empty -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | Vihoma 5 | Vihoma 6 | 2019 7 | 8 | src 9 | test 10 | 11 | 12 | src 13 | 14 | **/*.java 15 | 16 | 17 | 18 | 19 | 20 | test 21 | 22 | **/*.java 23 | 24 | 25 | 26 | 27 | 28 | maven-compiler-plugin 29 | 3.3 30 | 31 | 1.8 32 | 1.8 33 | 34 | 35 | 36 | maven-jar-plugin 37 | 38 | 39 | 40 | application.Main 41 | 42 | 43 | 44 | 45 | 46 | maven-assembly-plugin 47 | 48 | 49 | 50 | jar-with-dependencies 51 | 52 | 53 | 54 | 55 | application.Main 56 | 57 | 58 | 59 | 60 | 61 | make-assembly 62 | package 63 | 64 | single 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | org.xerial 75 | sqlite-jdbc 76 | 3.25.2 77 | 78 | 79 | 86 | 93 | 94 | 95 | junit 96 | junit 97 | 4.12 98 | test 99 | 100 | 106 | 107 | -------------------------------------------------------------------------------- /src/application/Main.java: -------------------------------------------------------------------------------- 1 | package application; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.net.URISyntaxException; 6 | 7 | import application.business.impl.ServiceFactoryImpl; 8 | import application.conf.Factory; 9 | import application.model.Configuration; 10 | import application.model.CustomHost; 11 | import application.model.Host; 12 | import application.persistence.sqlite.SQLiteRepositoryFactory; 13 | import application.persistence.sqlite.util.SQLiteJDBC; 14 | import application.util.HostsFileManager; 15 | import application.util.SystemUtil; 16 | import application.util.WebUtil; 17 | import application.util.WindowsUtil; 18 | import application.util.properties.Messages; 19 | import application.view.ErrorAdminController; 20 | import application.view.ErrorDialogController; 21 | import application.view.MainViewController; 22 | import javafx.application.Application; 23 | import javafx.collections.FXCollections; 24 | import javafx.collections.ObservableList; 25 | import javafx.fxml.FXMLLoader; 26 | import javafx.scene.Scene; 27 | import javafx.scene.image.Image; 28 | import javafx.scene.layout.AnchorPane; 29 | import javafx.scene.layout.BorderPane; 30 | import javafx.stage.Modality; 31 | import javafx.stage.Stage; 32 | 33 | /** 34 | * This class sets up some initial documentation and launches the different 35 | * interface modes depending on the user parameters. 36 | * 37 | */ 38 | public class Main extends Application { 39 | 40 | private static Stage primaryStage; 41 | private BorderPane rootLayout; 42 | private ObservableList blockedHosts = FXCollections.observableArrayList(); 43 | private ObservableList customHosts = FXCollections.observableArrayList(); 44 | private final static boolean isAdmin = SystemUtil.isAdmin(); 45 | 46 | public Main() { 47 | fillBlockedHostObservableList(); 48 | fillCustomHostObservableList(); 49 | } 50 | 51 | public static void main(String[] args) throws URISyntaxException { 52 | configure(); 53 | if (0 < args.length && "-quiet".equals(args[0])) { 54 | quietRun(); 55 | System.exit(0); 56 | } else 57 | launch(args); 58 | } 59 | 60 | private static void quietRun() { 61 | if (!isAdmin) { 62 | System.out.println(Messages.get("errorVihomaRequiresAdminRights")); 63 | SystemUtil.removeVihomaFolderPath(); 64 | System.exit(0); 65 | } 66 | 67 | System.out.println(Messages.get("updating")); 68 | Factory.service.forHost().updateDatabaseFromWeb(); 69 | try { 70 | HostsFileManager.persistHostsFile( 71 | Factory.service.forHost().findAllActive() 72 | , Factory.service.forConfiguration().getBlockedAddress() 73 | , Factory.service.forCustomHost().findAllActive()); 74 | } catch (IOException e) { 75 | System.out.println(Messages.get("oops")); 76 | } 77 | } 78 | 79 | public ObservableList getBlockedHostsData() { 80 | return blockedHosts; 81 | } 82 | 83 | public ObservableList getCustomHostsData() { 84 | return customHosts; 85 | } 86 | 87 | public void fillBlockedHostObservableList() { 88 | blockedHosts.clear(); 89 | for (Host host : Factory.service.forHost().findAll()) 90 | blockedHosts.add(host); 91 | } 92 | 93 | public void fillCustomHostObservableList() { 94 | customHosts.clear(); 95 | for (CustomHost chost : Factory.service.forCustomHost().findAll()) 96 | customHosts.add(chost); 97 | } 98 | 99 | public void fillBlockedHostObservableList(String filter) { 100 | blockedHosts.clear(); 101 | for (Host host : Factory.service.forHost().findByDomain(filter)) 102 | blockedHosts.add(host); 103 | } 104 | 105 | public void fillCustomHostObservableList(String filter) { 106 | customHosts.clear(); 107 | for (CustomHost chost : Factory.service.forCustomHost().findByDomainOrIp(filter)) 108 | customHosts.add(chost); 109 | } 110 | 111 | @Override 112 | public void start(Stage primaryStagee) { 113 | primaryStage = primaryStagee; 114 | primaryStage.setTitle("ViHoMa"); 115 | 116 | primaryStage.getIcons().add( 117 | new Image(Main.class.getClassLoader() 118 | .getResourceAsStream("resources/ico.png"))); 119 | 120 | initRootLayout(); 121 | if (isAdmin) { 122 | showMainOverview(); 123 | updateAtStartup(); 124 | } 125 | else { 126 | showErrorAdminRightsDialog(); 127 | SystemUtil.removeVihomaFolderPath(); 128 | System.exit(0); 129 | } 130 | } 131 | 132 | private void updateAtStartup() { 133 | Configuration update = Factory.service.forConfiguration() 134 | .findByParameter("updateAtVihomaStartup"); 135 | if (null != update && "yes".equals(update.getValue())) { 136 | quietRun(); 137 | } 138 | fillBlockedHostObservableList(); 139 | } 140 | 141 | public void errorExit() { 142 | showErrorDialog(); 143 | try { 144 | HostsFileManager.persistHostsFile( 145 | SystemUtil.getVihomaFolderPath() + ".hosts.vihoma." 146 | + System.currentTimeMillis()/1000 + ".crash" 147 | ,Factory.service.forHost().findAll() 148 | , Factory.service.forConfiguration().getBlockedAddress() 149 | , Factory.service.forCustomHost().findAll()); 150 | } catch (IOException e) { 151 | System.out.println(Messages.get("oops")); 152 | } 153 | new File(SystemUtil.getVihomaFolderPath() + "vihoma.sqlite").delete(); 154 | System.exit(0); 155 | } 156 | 157 | /** 158 | * Initializes the root layout. 159 | */ 160 | public void initRootLayout() { 161 | try { 162 | FXMLLoader loader = new FXMLLoader(); 163 | loader.setLocation(Main.class.getResource("view/RootLayout.fxml")); 164 | rootLayout = (BorderPane) loader.load(); 165 | 166 | Scene scene = new Scene(rootLayout); 167 | primaryStage.setScene(scene); 168 | primaryStage.setMaxHeight(400); 169 | primaryStage.setMaxWidth(600); 170 | primaryStage.setMinHeight(300); 171 | primaryStage.setMinWidth(400); 172 | primaryStage.show(); 173 | } catch (IOException e) { 174 | errorExit(); 175 | } 176 | } 177 | 178 | /** 179 | * Shows the main view inside the root layout. 180 | */ 181 | public void showMainOverview() { 182 | try { 183 | FXMLLoader loader = new FXMLLoader(); 184 | loader.setLocation(Main.class.getResource("view/MainView.fxml")); 185 | AnchorPane mainView = (AnchorPane) loader.load(); 186 | 187 | rootLayout.setCenter(mainView); 188 | 189 | MainViewController controller = loader.getController(); 190 | controller.setMainApp(this); 191 | } catch (IOException e) { 192 | errorExit(); 193 | } 194 | } 195 | 196 | public static boolean showErrorAdminRightsDialog() { 197 | try { 198 | FXMLLoader loader = new FXMLLoader(); 199 | loader.setLocation(Main.class.getResource("view/ErrorAdminDialog.fxml")); 200 | AnchorPane page = (AnchorPane) loader.load(); 201 | 202 | Stage dialogStage = new Stage(); 203 | dialogStage.setTitle("Vihoma"); 204 | dialogStage.getIcons().add( 205 | new Image(Main.class.getClassLoader() 206 | .getResourceAsStream("resources/ico.png"))); 207 | dialogStage.initModality(Modality.WINDOW_MODAL); 208 | dialogStage.initOwner(primaryStage); 209 | Scene scene = new Scene(page); 210 | dialogStage.setScene(scene); 211 | 212 | ErrorAdminController controller = loader.getController(); 213 | controller.setDialogStage(dialogStage); 214 | 215 | dialogStage.showAndWait(); 216 | 217 | return controller.isOkClicked(); 218 | } catch (IOException e) { 219 | return false; 220 | } 221 | } 222 | 223 | public boolean showErrorDialog() { 224 | try { 225 | FXMLLoader loader = new FXMLLoader(); 226 | loader.setLocation(Main.class.getResource("view/ErrorDialog.fxml")); 227 | AnchorPane page = (AnchorPane) loader.load(); 228 | 229 | Stage dialogStage = new Stage(); 230 | dialogStage.setTitle("Vihoma"); 231 | dialogStage.getIcons().add( 232 | new Image(Main.class.getClassLoader() 233 | .getResourceAsStream("resources/ico.png"))); 234 | dialogStage.initModality(Modality.WINDOW_MODAL); 235 | dialogStage.initOwner(primaryStage); 236 | Scene scene = new Scene(page); 237 | dialogStage.setScene(scene); 238 | 239 | ErrorDialogController controller = loader.getController(); 240 | controller.setDialogStage(dialogStage); 241 | 242 | dialogStage.showAndWait(); 243 | 244 | return controller.isOkClicked(); 245 | } catch (IOException e) { 246 | return false; 247 | } 248 | } 249 | 250 | /** 251 | * Returns the main stage. 252 | * @return 253 | */ 254 | public Stage getPrimaryStage() { 255 | return primaryStage; 256 | } 257 | 258 | /** 259 | * creates the local Vihoma folder where the logs and database will be stored, 260 | * initializes the database and does some configuration settings if it is 261 | * run for the first time. 262 | */ 263 | public static void configure() { 264 | File file = new File(SystemUtil.getVihomaFolderPath()); 265 | file.mkdirs(); 266 | Factory.service = new ServiceFactoryImpl(); 267 | Factory.repository = new SQLiteRepositoryFactory(); 268 | SQLiteJDBC.getManager(); //sets the database up 269 | firstRun(); 270 | //Messages.setLanguage("enEN"); 271 | } 272 | 273 | private static void firstRun() { 274 | Configuration first = 275 | Factory.service.forConfiguration().findByParameter("firstRun"); 276 | if (null == first || "yes".equals(first.getValue())) { 277 | try { 278 | if (WindowsUtil.isDNSClientActivated()) 279 | WindowsUtil.toggleWindowsDNSClient(); 280 | Factory.service.forConfiguration().set("firstRun", "no"); 281 | } catch (IOException e) { 282 | // Logger.err(e.getMessage()); 283 | //logging here may cause errors on unix-like systems 284 | } 285 | WebUtil.openHelp(); 286 | } 287 | } 288 | } 289 | -------------------------------------------------------------------------------- /src/application/application.css: -------------------------------------------------------------------------------- 1 | /* JavaFX CSS - Leave this comment until you have at least create one rule which uses -fx-Property */ -------------------------------------------------------------------------------- /src/application/business/ConfigurationService.java: -------------------------------------------------------------------------------- 1 | package application.business; 2 | 3 | import java.util.List; 4 | 5 | import application.model.Configuration; 6 | 7 | public interface ConfigurationService { 8 | 9 | /** 10 | * persists a Configuration to the repository. 11 | * @param parameter the name of the new Configuration 12 | * @param value the value of the new Configuration 13 | */ 14 | int add(String parameter, String value); 15 | /** 16 | * returns the list of Configurations persisted in the repository. 17 | * @return a List list, which may be empty 18 | */ 19 | List findAll(); 20 | /** 21 | * looks for a Configuration in the repository whose parameter is *exactly* 22 | * the one passed as parameter. 23 | * @param parameter name of the Configuration parameter to be searched 24 | * @return the Configuration found with the given parameter name 25 | */ 26 | Configuration findByParameter(String parameter); 27 | /** 28 | * changes the value of a Configuration persisted in the repository. 29 | * @param parameter the parameter name of the Configuration 30 | * @param value the new value the Configuration will have 31 | * @return the number of affected rows 32 | */ 33 | int update(String parameter, String value); 34 | /** 35 | * searches for a Configuration in the repository. If it is found, it updates 36 | * its value. A new Configuration with the given parameter and value is 37 | * added otherwise. 38 | * @param parameter the name of the Configuration to be set 39 | * @param newValue the value of the Configuration to be added or updated 40 | */ 41 | void set(String parameter, String newValue); 42 | 43 | 44 | /** 45 | * syntax sugar for findByParameter("lastUpdateTime") 46 | * @return the value of the last update stored in the repository. 0 if it 47 | * has never been updated 48 | */ 49 | long getLastUpdateTime(); 50 | /** 51 | * syntax sugar for set("lastUpdateTime", {unixTime}) 52 | */ 53 | void setLastUpdateTime(); 54 | /** 55 | * syntax sugar for findByParameter("blockedAddress"). If not found, returns 56 | * the defaultBlockedAddress stored in the configuration files. 57 | * @return 58 | */ 59 | String getBlockedAddress(); 60 | /** 61 | * syntax sugar for set("blockedAddress", newBlockingAddress) 62 | * @param newBlockingAddress the new address to which the blocked hosts will 63 | * be redirected 64 | */ 65 | void setBlockedAddress(String newBlockingAddress); 66 | /** 67 | * syntax sugar for findByParameter("updateAtVihomaStartup"). 68 | * @return false if no value is found, or it is "no". True otherwise. 69 | */ 70 | boolean isUpdateAtVihomaStartupEnabled(); 71 | /** 72 | * syntax sugar for toggling the value of "updateAtVihomaStartup" 73 | * Configuration through the set method. Values can be "yes" or "no". 74 | */ 75 | void toggleUpdateAtVihomaStart(); 76 | /** 77 | * syntax sugar for findByParameter("webSource"). 78 | * @return the value found if not null, 'StevenBlack' + the enabled Steven 79 | * Black categories otherwise. 80 | */ 81 | String getWebSource(); 82 | /** 83 | * syntax sugar for set("webSource", newSource) 84 | * @param newSource the new source from where the blocked hosts list will be 85 | * downloaded. Must start with 'http://' (without quotes) 86 | */ 87 | void setWebSource(String newSource); 88 | /** 89 | * syntax sugar for set("StevenBlackCategories", String.valueOf(categories)). 90 | * @param categories the sum of the enabled categories values. They are 91 | * specified in the Host model class. 92 | */ 93 | void setStevenBlackCategories(int categories); 94 | /** 95 | * syntax sugar for findByParameter("StevenBlackCategories"). 96 | * @return 0 if the value found is null or empty, the sum of the enabled 97 | * categories otherwise. The value of each category is specified in the Host 98 | * model class 99 | */ 100 | int getStevenBlackCategories(); 101 | } 102 | -------------------------------------------------------------------------------- /src/application/business/CustomHostService.java: -------------------------------------------------------------------------------- 1 | package application.business; 2 | 3 | import java.util.List; 4 | 5 | import application.model.CustomHost; 6 | 7 | public interface CustomHostService { 8 | 9 | /** 10 | * persists a CustomHost to the repository. IP address must have the IPv4 11 | * or IPv6 format. Several custom hosts with the same domain name may coexist 12 | * in the database, but with different addresses. 13 | * @param domain the domain name of the CustomHost 14 | * @param address the IP address of the CustomHost 15 | * @return the number of hosts added 16 | */ 17 | int add(String domain, String address); 18 | /** 19 | * gets the list of CustomHosts persisted in the repository 20 | * @return the list of CustomHosts persisted in the repository 21 | */ 22 | List findAll(); 23 | /** 24 | * gets the CustomHosts with status Host.STATUS_ACTIVE persisted in the 25 | * repository 26 | * @return a List of the ACTIVE persisted CustomHosts 27 | */ 28 | List findAllActive(); 29 | /** 30 | * looks for CustomHosts in the repository whose domain name or IP address 31 | * contains the text passed as parameter. 32 | * @param filter the search term 33 | * @return a list of CustomHosts whose domain names or IP addresses 34 | * contain the filter value 35 | */ 36 | List findByDomainOrIp(String filter); 37 | /** 38 | * looks for CustomHosts in the repository whose status is the one passed as 39 | * parameter. The statuses available are specified in the Hosts model class. 40 | * @param status the search status term 41 | * @return a list of the CustomHosts whose status is the one passed as parameter 42 | */ 43 | List findByStatus(int status); 44 | /** 45 | * toggles the status of a CustomHost. The values available are Host.STATUS_ACTIVE 46 | * and Host.STATUS_DELETED 47 | * @param domain the domain name of the CustomHost whose status is to be toggled 48 | * @param address the address of the CustomHost whose status is to be toggled 49 | */ 50 | int toggleStatus(String domain, String address); 51 | /** 52 | * counts the number of CustomHosts persisted in the repository. 53 | * @return the number of CustomHosts in the repository 54 | */ 55 | int getHostsCount(); 56 | /** 57 | * deletes all the persisted CustomHosts. 58 | */ 59 | void deleteAll(); 60 | } 61 | -------------------------------------------------------------------------------- /src/application/business/HostService.java: -------------------------------------------------------------------------------- 1 | package application.business; 2 | 3 | import java.util.List; 4 | 5 | import application.model.Host; 6 | 7 | public interface HostService { 8 | 9 | /** 10 | * persists a Host to the repository. 11 | * @param domain the domain name of the host 12 | * @return the number of hosts persisted 13 | */ 14 | int addHost(String domain); 15 | /** 16 | * persists a Host to the repository. 17 | * @param domain the domain name of the host 18 | * @param category the category of the host 19 | * @return the number of hosts persisted 20 | */ 21 | int addHost(String domain, Integer category); 22 | /** 23 | * persists a list of Hosts to the repository. 24 | * @param hostsList the list of hosts to be persisted 25 | * @return the number of hosts persisted 26 | */ 27 | int addHosts(List hostsList); 28 | /** 29 | * counts the number of Hosts persisted in the repository. 30 | * @return the number of Hosts persisted in the repository. 31 | */ 32 | int getHostsCount(); 33 | /** 34 | * gets the list of Hosts persisted in the repository 35 | * @return the list of Hosts persisted in the repository 36 | */ 37 | List findAll(); 38 | /** 39 | * gets the Hosts with status Host.STATUS_ACTIVE persisted in the repository 40 | * @return a List of the ACTIVE persisted Hosts 41 | */ 42 | List findAllActive(); 43 | /** 44 | * toggles the status of a Host. The values available are Host.STATUS_ACTIVE 45 | * and Host.STATUS_DELETED 46 | * @param domain the domain name of the host whose status is to be toggled 47 | */ 48 | void toggleStatus(String domain); 49 | /** 50 | * looks for Hosts in the repository whose domain name contains 51 | * the text passed as parameter. 52 | * @param filter the search term 53 | * @return a list of Hosts whose domain names contain the filter value 54 | */ 55 | List findByDomain(String filter); 56 | /** 57 | * deletes all the persisted Hosts. 58 | */ 59 | void deleteAll(); 60 | /** 61 | * looks for Hosts in the repository whose category is the one passed as 62 | * parameter. The categories available are specified in the Hosts model class. 63 | * @param category the search term 64 | * @return a list of Hosts whose category equals the one passed as paremeter 65 | */ 66 | List findByCategory(int category); 67 | /** 68 | * replaces the persisted block hosts list by a new one which will be downloaded 69 | * from the program webSource Configuration. The user manually blocked hosts 70 | * and user manually disabled hosts are not replaced. 71 | * @return a list of the hosts downloaded from the web 72 | */ 73 | List updateDatabaseFromWeb(); 74 | /** 75 | * looks for Hosts in the repository whose status is the one passed as 76 | * parameter. The statuses available are specified in the Hosts model class. 77 | * @param status the search status term 78 | * @return a list of the Hosts whose status is the one passed as parameter 79 | */ 80 | List findByStatus(int status); 81 | } 82 | -------------------------------------------------------------------------------- /src/application/business/ServiceFactory.java: -------------------------------------------------------------------------------- 1 | package application.business; 2 | 3 | public interface ServiceFactory { 4 | 5 | /** 6 | * returns the gateway for the blocked Hosts services. It is a implementation 7 | * of the Abstract Factory Pattern. 8 | * @return a HostService object with the available operations for 9 | * blocked Hosts 10 | */ 11 | HostService forHost(); 12 | /** 13 | * returns the gateway for the CustomHosts services. It is a implementation 14 | * of the Abstract Factory Pattern. 15 | * @return a CustomHostService with the available operations for CustomHosts 16 | */ 17 | CustomHostService forCustomHost(); 18 | /** 19 | * returns the gateway for the Configuration services. It is a implementation 20 | * of the Abstract Factory Pattern. 21 | * @return a ConfigurationService with the available operations for 22 | * Configurations 23 | */ 24 | ConfigurationService forConfiguration(); 25 | } 26 | -------------------------------------------------------------------------------- /src/application/business/impl/ConfigurationServiceImpl.java: -------------------------------------------------------------------------------- 1 | package application.business.impl; 2 | 3 | import java.util.List; 4 | 5 | import application.business.ConfigurationService; 6 | import application.conf.Factory; 7 | import application.model.Configuration; 8 | import application.util.Logger; 9 | import application.util.properties.Settings; 10 | 11 | public class ConfigurationServiceImpl implements ConfigurationService { 12 | 13 | @Override 14 | public long getLastUpdateTime() { 15 | Configuration conf = this.findByParameter("lastUpdateTime"); 16 | return (null==conf)? 0L:Long.parseLong(conf.getValue()); 17 | } 18 | 19 | @Override 20 | public void setLastUpdateTime() { 21 | if (0==this.getLastUpdateTime()) 22 | this.add("lastUpdateTime", String.valueOf(System.currentTimeMillis()/1000)); 23 | else 24 | this.update("lastUpdateTime", String.valueOf(System.currentTimeMillis()/1000)); 25 | } 26 | 27 | @Override 28 | public int add(String parameter, String value) { 29 | int count = Factory.repository.forConfiguration() 30 | .add(new Configuration(parameter,value)); 31 | if (0 == count) 32 | Logger.err("ERROR ADDING CONFIGURATION: " + parameter + " = " + value); 33 | else 34 | Logger.log("NEW CONFIGURATION: " + parameter + " = " + value); 35 | 36 | return count; 37 | } 38 | 39 | @Override 40 | public List findAll() { 41 | return Factory.repository.forConfiguration().findAll(); 42 | } 43 | 44 | @Override 45 | public String getBlockedAddress() { 46 | Configuration conf = this.findByParameter("blockedAddress"); 47 | return (null == conf || "".equals(conf.getValue()))? 48 | Settings.get("defaultBlockedAddress"):conf.getValue(); 49 | } 50 | 51 | @Override 52 | public void setBlockedAddress(String newBlockingAddress) { 53 | set("blockedAddress", newBlockingAddress); 54 | } 55 | 56 | @Override 57 | public Configuration findByParameter(String parameter) throws IllegalArgumentException{ 58 | if (null == parameter) 59 | throw new IllegalArgumentException("no parameter provided"); 60 | 61 | return Factory.repository.forConfiguration().findByParameter(parameter); 62 | } 63 | 64 | @Override 65 | public int update(String parameter, String value) throws IllegalArgumentException{ 66 | if (null == parameter || null == value || "".equals(parameter)) 67 | throw new IllegalArgumentException("at least a non-empty parameter is needed"); 68 | 69 | int count = Factory.repository.forConfiguration().update(parameter, value); 70 | 71 | if (0 < count) 72 | Logger.log("CONFIGURATION UPDATED: " + parameter + " = " + value); 73 | 74 | return count; 75 | } 76 | 77 | @Override 78 | public void set(String parameter, String newValue) throws IllegalArgumentException{ 79 | if (null == parameter || null == newValue || "".equals(parameter)) 80 | throw new IllegalArgumentException("at least a non-empty parameter is needed"); 81 | 82 | Configuration conf = this.findByParameter(parameter); 83 | if (null == conf) 84 | add(parameter,newValue); 85 | else 86 | update(parameter,newValue); 87 | } 88 | 89 | @Override 90 | public boolean isUpdateAtVihomaStartupEnabled() { 91 | Configuration conf = this.findByParameter("updateAtVihomaStartup"); 92 | 93 | if (null == conf || "no".equals(conf.getValue())) 94 | return false; 95 | return true; 96 | } 97 | 98 | @Override 99 | public void toggleUpdateAtVihomaStart() { 100 | if (isUpdateAtVihomaStartupEnabled()) 101 | Factory.service.forConfiguration().set("updateAtVihomaStartup", "no"); 102 | else 103 | Factory.service.forConfiguration().set("updateAtVihomaStartup", "yes"); 104 | } 105 | 106 | @Override 107 | public String getWebSource() { 108 | Configuration conf = this.findByParameter("webSource"); 109 | 110 | return (null == conf || "".equals(conf.getValue()) 111 | || conf.getValue().startsWith(Settings.get("defaultWebSourceDomain")))? 112 | Settings.get("StevenBlack"+getStevenBlackCategories()) 113 | :conf.getValue(); 114 | } 115 | 116 | @Override 117 | public void setWebSource(String newSource) { 118 | set("webSource", newSource); 119 | } 120 | 121 | @Override 122 | public void setStevenBlackCategories(int categories) { 123 | set("StevenBlackCategories", String.valueOf(categories)); 124 | } 125 | 126 | @Override 127 | public int getStevenBlackCategories() { 128 | Configuration categories = this.findByParameter("StevenBlackCategories"); 129 | return (null == categories || "".equals(categories.getValue()))? 130 | 0:Integer.parseInt(categories.getValue()); 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/application/business/impl/CustomHostServiceImpl.java: -------------------------------------------------------------------------------- 1 | package application.business.impl; 2 | 3 | import java.util.List; 4 | 5 | import application.business.CustomHostService; 6 | import application.conf.Factory; 7 | import application.model.CustomHost; 8 | import application.model.Host; 9 | import application.util.Logger; 10 | 11 | public class CustomHostServiceImpl implements CustomHostService { 12 | 13 | @Override 14 | public int add(String domain, String address) { 15 | try { 16 | new CustomHost(domain, address); 17 | } catch (IllegalArgumentException e){ 18 | // the address is not valid; avoid addition 19 | Logger.err("ERROR ADDING DOMAIN " + domain + " with address " 20 | + address); 21 | return -1; 22 | } 23 | 24 | int count = Factory.repository.forCustomHost() 25 | .add(new CustomHost(domain,address)); 26 | if (0 == count) 27 | Logger.err("ERROR ADDING DOMAIN " + domain + " with address " 28 | + address); 29 | else 30 | Logger.log("NEW CUSTOM DOMAIN: " + domain + " at " + address); 31 | return count; 32 | } 33 | 34 | @Override 35 | public List findAll() { 36 | return Factory.repository.forCustomHost().findAll(); 37 | } 38 | 39 | @Override 40 | public int toggleStatus(String domain, String address) { 41 | if (null == domain) 42 | throw new RuntimeException("no host provided"); 43 | 44 | return Factory.repository.forCustomHost().toggleStatus(domain, address); 45 | } 46 | 47 | @Override 48 | public List findAllActive() { 49 | return findByStatus(Host.STATUS_ACTIVE); 50 | } 51 | 52 | @Override 53 | public List findByDomainOrIp(String filter) { 54 | return Factory.repository.forCustomHost().findByDomainOrIp(filter); 55 | } 56 | 57 | @Override 58 | public int getHostsCount() { 59 | return Factory.repository.forCustomHost().getHostsCount(); 60 | } 61 | 62 | @Override 63 | public void deleteAll() { 64 | Factory.repository.forCustomHost().deleteAll(); 65 | 66 | } 67 | 68 | @Override 69 | public List findByStatus(int status) { 70 | return Factory.repository.forCustomHost().findByStatus(status); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/application/business/impl/HostServiceImpl.java: -------------------------------------------------------------------------------- 1 | package application.business.impl; 2 | 3 | import java.util.List; 4 | 5 | import application.business.HostService; 6 | import application.conf.Factory; 7 | import application.model.Host; 8 | import application.util.Logger; 9 | import application.util.WebUtil; 10 | 11 | public class HostServiceImpl implements HostService{ 12 | 13 | @Override 14 | public int addHost(String domain){ 15 | if (null == domain || "".equals(domain)) 16 | return -1; 17 | 18 | return addHost(domain, Host.CATEGORY_VIHOMA); 19 | } 20 | 21 | @Override 22 | public int addHost(String domain, Integer category) { 23 | if (null == domain || "".equals(domain) || null == category) 24 | return -1; 25 | 26 | int count = Factory.repository.forHost().add(new Host(domain,category)); 27 | if (0 == count) 28 | Logger.err("ERROR BLOCKING DOMAIN " + domain + " with category " 29 | + category); 30 | else 31 | Logger.log("NEW BLOCKED DOMAIN: " + domain); 32 | return count; 33 | } 34 | 35 | @Override 36 | public int addHosts(List hostList) { 37 | if(null == hostList || hostList.isEmpty()) 38 | return 0; 39 | 40 | return Factory.repository.forHost().addHosts(hostList); 41 | } 42 | 43 | @Override 44 | public int getHostsCount() { 45 | return Factory.repository.forHost().getHostsCount(); 46 | } 47 | 48 | @Override 49 | public List findAll() { 50 | return Factory.repository.forHost().findAll(); 51 | } 52 | 53 | @Override 54 | public void toggleStatus(String domain) throws IllegalArgumentException{ 55 | if (null == domain) 56 | throw new IllegalArgumentException("no host provided"); 57 | 58 | Factory.repository.forHost().toggleHostStatus(domain); 59 | } 60 | 61 | @Override 62 | public List findAllActive() { 63 | return findByStatus(Host.STATUS_ACTIVE); 64 | } 65 | 66 | @Override 67 | public List findByDomain(String filter) { 68 | return Factory.repository.forHost().findByDomain(filter); 69 | } 70 | 71 | @Override 72 | public void deleteAll() { 73 | Factory.repository.forHost().deleteAll(); 74 | } 75 | 76 | @Override 77 | public List findByCategory(int category) { 78 | return Factory.repository.forHost().findByCategory(category); 79 | } 80 | 81 | @Override 82 | public List updateDatabaseFromWeb() { 83 | List hosts = WebUtil.getHostsFromWebSource( 84 | Factory.service.forConfiguration().getWebSource()); 85 | if (null != hosts && !hosts.isEmpty()) { 86 | List userAdded = findByCategory(Host.CATEGORY_VIHOMA); 87 | List deactivatedList = findByStatus(Host.STATUS_DELETED); 88 | deleteAll(); 89 | addHosts(hosts); 90 | for (Host user : userAdded) 91 | addHost(user.getDomain(), user.getCategory()); 92 | for (Host deactivated : deactivatedList) { 93 | addHost(deactivated.getDomain(), deactivated.getCategory()); 94 | toggleStatus(deactivated.getDomain()); 95 | } 96 | 97 | Factory.service.forConfiguration().setLastUpdateTime(); 98 | } 99 | return hosts; 100 | } 101 | 102 | @Override 103 | public List findByStatus(int status) { 104 | return Factory.repository.forHost().findByStatus(status); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/application/business/impl/ServiceFactoryImpl.java: -------------------------------------------------------------------------------- 1 | package application.business.impl; 2 | 3 | import application.business.ConfigurationService; 4 | import application.business.CustomHostService; 5 | import application.business.HostService; 6 | import application.business.ServiceFactory; 7 | 8 | public class ServiceFactoryImpl implements ServiceFactory { 9 | 10 | @Override 11 | public HostService forHost() { 12 | return new HostServiceImpl(); 13 | } 14 | 15 | @Override 16 | public CustomHostService forCustomHost() { 17 | return new CustomHostServiceImpl(); 18 | } 19 | 20 | @Override 21 | public ConfigurationService forConfiguration() { 22 | return new ConfigurationServiceImpl(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/application/business/repository/ConfigurationRepository.java: -------------------------------------------------------------------------------- 1 | package application.business.repository; 2 | 3 | import application.model.Configuration; 4 | 5 | public interface ConfigurationRepository extends Repository{ 6 | 7 | /** 8 | * @param parameter the name of the Configuration parameter to be searched 9 | * @return a Configuration object made up with the parameter and value found 10 | * in the repository 11 | */ 12 | Configuration findByParameter(String parameter); 13 | /** 14 | * @param parameter the name of the Configuration name to be updated 15 | * @param value the new value of the Configuration to be updated 16 | * @return the number of Configurations updated in the repository, -1 if an 17 | * error was produced 18 | */ 19 | int update(String parameter, String value); 20 | } 21 | -------------------------------------------------------------------------------- /src/application/business/repository/CustomHostRepository.java: -------------------------------------------------------------------------------- 1 | package application.business.repository; 2 | 3 | import java.util.List; 4 | 5 | import application.model.CustomHost; 6 | 7 | public interface CustomHostRepository extends Repository{ 8 | 9 | /** 10 | * toggles the status of a CustomHost. 11 | * @param domain the domain name of the CustomHost whose status is to be changed 12 | * @param address the address of the CustomHost whose status is to be toggled 13 | */ 14 | int toggleStatus(String domain, String address); 15 | /** 16 | * looks for CustomHosts in the repository whose domain name or IP address 17 | * contains the text passed as parameter. 18 | * @param term the search term 19 | * @return a list of the CustomHosts whose domain names or IP addresses contain 20 | * the term passed as parameter 21 | */ 22 | List findByDomainOrIp(String term); 23 | /** 24 | * looks for CustomHosts in the repository whose status is the one passed as 25 | * parameter 26 | * @param status the search status term 27 | * @return a list of the CustomHosts whose status is the one passed as parameter@return 28 | */ 29 | List findByStatus(int status); 30 | /** 31 | * counts the number of CustomHosts persisted in the repository. 32 | * @return the number of CustomHosts in the repository 33 | */ 34 | int getHostsCount(); 35 | /** 36 | * empties the CustomHost repository 37 | */ 38 | void deleteAll(); 39 | } 40 | -------------------------------------------------------------------------------- /src/application/business/repository/HostRepository.java: -------------------------------------------------------------------------------- 1 | package application.business.repository; 2 | 3 | import java.util.List; 4 | 5 | import application.model.Host; 6 | 7 | public interface HostRepository extends Repository{ 8 | 9 | /** 10 | * counts the number of Hosts in the repository 11 | * @return the number of Hosts persisted in the repository 12 | */ 13 | int getHostsCount(); 14 | /** 15 | * persists a list of Hosts to the repository. 16 | * @param hostsList the list of hosts to be persisted 17 | * @return 18 | */ 19 | int addHosts(List hostsList); 20 | /** 21 | * toggles the status of a Host 22 | * @param domain the domain name of the host whose status is to be toggled 23 | */ 24 | void toggleHostStatus(String domain); 25 | /** 26 | * looks for Hosts in the repository whose domain name contains 27 | * the text passed as parameter. 28 | * @param domain the search term 29 | * @return a list of Hosts whose domain names contain the filter value 30 | */ 31 | List findByDomain(String domain); 32 | /** 33 | * empties the Hosts repository 34 | */ 35 | void deleteAll(); 36 | /** 37 | * looks for Hosts in the repository whose category is the one passed as 38 | * parameter. The categories available are specified in the Hosts model class. 39 | * @param category the search term 40 | * @return a list of Hosts whose category equals the one passed as parameter 41 | */ 42 | List findByCategory(int category); 43 | /** 44 | * looks for Hosts in the repository whose status is the one passed as 45 | * parameter. 46 | * @param status the search term 47 | * @return a list of the Hosts whose status is the one passed as parameter 48 | */ 49 | List findByStatus(int status); 50 | } 51 | -------------------------------------------------------------------------------- /src/application/business/repository/Repository.java: -------------------------------------------------------------------------------- 1 | package application.business.repository; 2 | 3 | import java.util.List; 4 | 5 | public interface Repository { 6 | int add(T t); 7 | void delete(T t); 8 | T findById(Long id); 9 | List findAll(); 10 | } 11 | -------------------------------------------------------------------------------- /src/application/business/repository/RepositoryFactory.java: -------------------------------------------------------------------------------- 1 | package application.business.repository; 2 | 3 | public interface RepositoryFactory { 4 | 5 | HostRepository forHost(); 6 | CustomHostRepository forCustomHost(); 7 | ConfigurationRepository forConfiguration(); 8 | } 9 | -------------------------------------------------------------------------------- /src/application/conf/Factory.java: -------------------------------------------------------------------------------- 1 | package application.conf; 2 | 3 | import application.business.ServiceFactory; 4 | import application.business.repository.RepositoryFactory; 5 | 6 | /** 7 | * This class is implemented following the Abstract Factory Pattern. 8 | */ 9 | public class Factory { 10 | 11 | public static RepositoryFactory repository; 12 | public static ServiceFactory service; 13 | } 14 | -------------------------------------------------------------------------------- /src/application/model/Configuration.java: -------------------------------------------------------------------------------- 1 | package application.model; 2 | 3 | /** 4 | * This class represents a setting entity of the application. It is composed by a String 5 | * parameter attribute and a String value attribute. 6 | * 7 | */ 8 | public class Configuration { 9 | 10 | private String parameter, value; 11 | 12 | /** 13 | * initializes a Vihoma setting 14 | * @param parameter the name of the setting 15 | * @param value the value of the setting 16 | */ 17 | public Configuration(String parameter, String value) { 18 | this.parameter = parameter; 19 | this.value = value; 20 | } 21 | 22 | public String getParameter() { 23 | return parameter; 24 | } 25 | 26 | public void setParameter(String parameter) { 27 | this.parameter = parameter; 28 | } 29 | 30 | public String getValue() { 31 | return value; 32 | } 33 | 34 | public void setValue(String value) { 35 | this.value = value; 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/application/model/CustomHost.java: -------------------------------------------------------------------------------- 1 | package application.model; 2 | 3 | import application.util.WebUtil; 4 | import application.util.properties.Settings; 5 | import javafx.beans.property.SimpleStringProperty; 6 | import javafx.beans.property.StringProperty; 7 | 8 | /** 9 | * This class represents a CustomHost entity. It extends the Host class. It takes 10 | * the value of Host.CATEGORY_VIHOMA as default category. 11 | * @attribute address the IP address of the CustomHost 12 | */ 13 | public class CustomHost extends Host { 14 | 15 | private StringProperty address; 16 | 17 | public CustomHost() { 18 | super(); 19 | } 20 | 21 | /** 22 | * initializes a CustomHost object. 23 | * @param domain the domain name of the custom host 24 | * @param address the IP address of the custom host 25 | * @throws IllegalArgumentException if the address is 0.0.0.0 or does not 26 | * follow neither the IPv4 or IPv6 address formats 27 | */ 28 | public CustomHost(String domain, String address) throws IllegalArgumentException { 29 | super(domain,Host.CATEGORY_VIHOMA,Host.STATUS_ACTIVE,"",System.currentTimeMillis()/1000); 30 | if ("0.0.0.0".equals(domain)) 31 | throw new IllegalArgumentException(Settings.get("wrongCustomHostDomain")); 32 | setAddress(new SimpleStringProperty(address.trim())); 33 | } 34 | 35 | /** 36 | * 37 | * @param domain the domain name of the custom host 38 | * @param address the IP address of the custom host 39 | * @param status 40 | * @throws IllegalArgumentException if the address is 0.0.0.0 or does not 41 | * follow neither the IPv4 or IPv6 address formats 42 | */ 43 | public CustomHost(String domain, String address, int status) throws IllegalArgumentException { 44 | this(domain,address); 45 | setStatus(status); 46 | } 47 | 48 | public StringProperty addressProperty() { 49 | return address; 50 | } 51 | 52 | public String getAddress() { 53 | return address.get(); 54 | } 55 | 56 | /** 57 | * sets the address of the CustomHost 58 | * @param iP the IP address the CustomHost will have 59 | * @throws IllegalArgumentException if the iP address does not follow 60 | * neither the IPv4 or IPv6 address formats 61 | */ 62 | public void setAddress(StringProperty iP) throws IllegalArgumentException{ 63 | if (WebUtil.checkIpValidity(iP.get())) 64 | address = iP; 65 | else 66 | throw new IllegalArgumentException(Settings.get("wrongCustomHostIP")); 67 | } 68 | 69 | @Override 70 | public String toString() { 71 | return "CustomHost [getAddress()=" + getAddress() + super.toString() + "]"; 72 | } 73 | 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/application/model/Host.java: -------------------------------------------------------------------------------- 1 | package application.model; 2 | 3 | import javafx.beans.property.BooleanProperty; 4 | import javafx.beans.property.IntegerProperty; 5 | import javafx.beans.property.LongProperty; 6 | import javafx.beans.property.SimpleBooleanProperty; 7 | import javafx.beans.property.SimpleIntegerProperty; 8 | import javafx.beans.property.SimpleLongProperty; 9 | import javafx.beans.property.SimpleStringProperty; 10 | import javafx.beans.property.StringProperty; 11 | 12 | /** 13 | * This class represents a blocked Host entity. 14 | * @attribute domain the domain name of the host 15 | * @attribute category the category to which the host belongs (only CATEGORY_VIHOMA 16 | * available) 17 | * @attribute status each domain can be active (default) or deleted. If active, it 18 | * will be persisted to the hosts file. 19 | * @attribute updatedAt the unix time in which the host was added 20 | * @attribute comment additional information 21 | * @attribute STATUS_ACTIVE 1 22 | * @attribute STATUS_DELETED 0 23 | * @attribute CATEGORY_VIHOMA -1 24 | * @attribute CATEGORY_STEVENBLACK_FAKENEWS 1 25 | * @attribute CATEGORY_STEVENBLACK_GAMBLING 2 26 | * @attribute CATEGORY_STEVENBLACK_PORN 4 27 | * @attribute CATEGORY_STEVENBLACK_SOCIAL 8 28 | */ 29 | public class Host { 30 | 31 | private StringProperty domain; 32 | private IntegerProperty category; 33 | private IntegerProperty status; 34 | private LongProperty updatedAt; 35 | private StringProperty comment; 36 | 37 | public final static int STATUS_ACTIVE = 1; 38 | public final static int STATUS_DELETED = 0; 39 | 40 | public final static int CATEGORY_VIHOMA = -1; 41 | public final static int CATEGORY_STEVENBLACK_BASICS = 0; 42 | public final static int CATEGORY_STEVENBLACK_FAKENEWS = 1; 43 | public final static int CATEGORY_STEVENBLACK_GAMBLING = 2; 44 | public final static int CATEGORY_STEVENBLACK_PORN = 4; 45 | public final static int CATEGORY_STEVENBLACK_SOCIAL = 8; 46 | 47 | public Host() { 48 | 49 | } 50 | 51 | public Host(String domain) { 52 | this.domain = new SimpleStringProperty(domain.trim()); 53 | this.category = new SimpleIntegerProperty(CATEGORY_VIHOMA); 54 | this.status = new SimpleIntegerProperty(Host.STATUS_ACTIVE); 55 | this.updatedAt = new SimpleLongProperty(System.currentTimeMillis()/1000); 56 | this.comment = new SimpleStringProperty("Blocked by user"); 57 | } 58 | 59 | public Host(String domain, Integer category) { 60 | this(domain); 61 | this.category = new SimpleIntegerProperty(category); 62 | } 63 | 64 | public Host(String domain, Integer category, int status, String comment, long utime) { 65 | this(domain,category); 66 | this.status = new SimpleIntegerProperty(status); 67 | this.updatedAt = new SimpleLongProperty(utime); 68 | this.comment = new SimpleStringProperty(comment); 69 | } 70 | 71 | public StringProperty domainProperty() { 72 | return domain; 73 | } 74 | 75 | public String getDomain() { 76 | return domain.get(); 77 | } 78 | 79 | public void setDomain(String domain) { 80 | this.domain.set(domain); 81 | } 82 | 83 | public IntegerProperty categoryProperty() { 84 | return category; 85 | } 86 | 87 | public Integer getCategory() { 88 | return category.get(); 89 | } 90 | 91 | public void setCategory(Integer category) { 92 | this.category.set(category); 93 | } 94 | 95 | public IntegerProperty statusProperty() { 96 | return status; 97 | } 98 | 99 | public Integer getStatus() { 100 | return status.get(); 101 | } 102 | 103 | public void setStatus(Integer status) { 104 | this.status.set(status); 105 | } 106 | 107 | public BooleanProperty activeProperty() { 108 | return new SimpleBooleanProperty((status.get() & 1) == 1); 109 | } 110 | 111 | public Boolean isActive() { 112 | return (status.get() & 1) == 1; 113 | } 114 | 115 | public void setActive(Boolean active) { 116 | this.status.set((active? 1:0)); 117 | } 118 | 119 | public LongProperty UpdatedAtProperty() { 120 | return updatedAt; 121 | } 122 | 123 | public Long getUpdatedAt() { 124 | return updatedAt.get(); 125 | } 126 | 127 | public void setUpdatedAt(Long updatedAt) { 128 | this.updatedAt.set(updatedAt); 129 | } 130 | 131 | public StringProperty commentProperty() { 132 | return comment; 133 | } 134 | 135 | public String getComment() { 136 | return comment.get(); 137 | } 138 | 139 | public void setComment(String comment) { 140 | this.comment.set(comment); 141 | } 142 | 143 | @Override 144 | public String toString() { 145 | return "Host [getDomain()=" + getDomain() 146 | + ", getStatus()=" + getStatus() 147 | + ", getComment()=" + getComment() + ", getUpdatedAt()=" 148 | + getUpdatedAt() + "]"; 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/BaseSQLiteRepository.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite; 2 | 3 | import java.sql.Connection; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.Statement; 7 | 8 | public class BaseSQLiteRepository { 9 | 10 | protected Connection conn; 11 | protected Statement stmt; 12 | protected PreparedStatement pstmt; 13 | protected ResultSet rs; 14 | } 15 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/ConfigurationSQLiteRepository.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import application.business.repository.ConfigurationRepository; 8 | import application.model.Configuration; 9 | import application.persistence.sqlite.util.SQLiteJDBC; 10 | import application.util.properties.Settings; 11 | 12 | public class ConfigurationSQLiteRepository extends BaseSQLiteRepository implements ConfigurationRepository { 13 | 14 | @Override 15 | public int add(Configuration t) { 16 | String parameter = t.getParameter(); 17 | String value = t.getValue(); 18 | 19 | if (null == parameter || null == value) 20 | throw new IllegalArgumentException( 21 | Settings.get("parametersCannotBeNull")); 22 | 23 | try { 24 | conn = SQLiteJDBC.connect(); 25 | pstmt = conn.prepareStatement( 26 | Settings.get("sqlInsertConfiguration")); 27 | pstmt.setString(1, parameter); 28 | pstmt.setString(2, value); 29 | return pstmt.executeUpdate(); 30 | 31 | } catch (SQLException e) { 32 | // ignored 33 | } finally { 34 | SQLiteJDBC.close(pstmt, conn); 35 | } 36 | return 0; 37 | } 38 | 39 | @Override 40 | public void delete(Configuration t) { 41 | // TODO Auto-generated method stub 42 | 43 | } 44 | 45 | @Override 46 | public Configuration findById(Long id) { 47 | // TODO Auto-generated method stub 48 | return null; 49 | } 50 | 51 | @Override 52 | public List findAll() { 53 | List configs = new ArrayList(); 54 | try { 55 | conn = SQLiteJDBC.connect(); 56 | stmt = conn.createStatement(); 57 | rs = stmt.executeQuery(Settings.get("sqlSelectConfigurations")); 58 | while (rs.next()) 59 | configs.add(new Configuration( 60 | (String) rs.getString("parameter") 61 | , (String) rs.getString("value") 62 | )); 63 | 64 | } catch (SQLException e) { 65 | // ignored 66 | } finally { 67 | SQLiteJDBC.close(rs, stmt, conn); 68 | } 69 | return configs; 70 | } 71 | 72 | @Override 73 | public Configuration findByParameter(String parameter) { 74 | try { 75 | conn = SQLiteJDBC.connect(); 76 | pstmt = conn.prepareStatement(Settings.get("sqlSelectConfigurationByParameter")); 77 | pstmt.setString(1, parameter); 78 | rs = pstmt.executeQuery(); 79 | if (rs.next()) 80 | return new Configuration(parameter,(String) rs.getString("value")); 81 | } catch (SQLException e) { 82 | // ignored 83 | } finally { 84 | SQLiteJDBC.close(rs, stmt, conn); 85 | } 86 | return null; 87 | } 88 | 89 | @Override 90 | public int update(String parameter, String value) { 91 | try { 92 | conn = SQLiteJDBC.connect(); 93 | pstmt = conn.prepareStatement( 94 | Settings.get("sqlUpdateConfiguration")); 95 | pstmt.setString(2, parameter); 96 | pstmt.setString(1, value); 97 | return pstmt.executeUpdate(); 98 | } catch (SQLException e) { 99 | // ignored 100 | } finally { 101 | SQLiteJDBC.close(pstmt, conn); 102 | } 103 | return -1; 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/CustomHostSQLiteRepository.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import application.business.repository.CustomHostRepository; 8 | import application.model.CustomHost; 9 | import application.persistence.sqlite.util.SQLiteJDBC; 10 | import application.util.properties.Settings; 11 | 12 | public class CustomHostSQLiteRepository extends BaseSQLiteRepository implements CustomHostRepository { 13 | 14 | @Override 15 | public int add(CustomHost newHost) { 16 | try { 17 | conn = SQLiteJDBC.connect(); 18 | pstmt = conn.prepareStatement( 19 | Settings.get("sqlInsertCustomHost")); 20 | pstmt.setString(1, newHost.getDomain()); 21 | pstmt.setString(2, newHost.getAddress()); 22 | pstmt.setInt(3, newHost.getStatus()); 23 | return pstmt.executeUpdate(); 24 | 25 | } catch (SQLException e) { 26 | // ignored 27 | } finally { 28 | SQLiteJDBC.close(pstmt, conn); 29 | } 30 | return 0; 31 | } 32 | 33 | @Override 34 | public void delete(CustomHost t) { 35 | // TODO Auto-generated method stub 36 | 37 | } 38 | 39 | @Override 40 | public CustomHost findById(Long id) { 41 | // TODO Auto-generated method stub 42 | return null; 43 | } 44 | 45 | @Override 46 | public List findAll() { 47 | List hosts = new ArrayList(); 48 | try { 49 | conn = SQLiteJDBC.connect(); 50 | stmt = conn.createStatement(); 51 | rs = stmt.executeQuery(Settings.get("sqlSelectCustomHosts")); 52 | while (rs.next()) 53 | hosts.add(new CustomHost( 54 | (String) rs.getString("domain") 55 | , (String) rs.getString("address") 56 | , (int) rs.getInt("status")) 57 | ); 58 | } catch (SQLException e) { 59 | // ignored 60 | } finally { 61 | SQLiteJDBC.close(rs, stmt, conn); 62 | } 63 | return hosts; 64 | } 65 | 66 | @Override 67 | public int toggleStatus(String domain, String address) { 68 | try { 69 | conn = SQLiteJDBC.connect(); 70 | pstmt = conn.prepareStatement( 71 | Settings.get("sqlUpdateCustomHostToggleStatus")); 72 | pstmt.setString(1, domain); 73 | pstmt.setString(2, address); 74 | pstmt.setString(3, domain); 75 | pstmt.setString(4, address); 76 | pstmt.setString(5, domain); 77 | pstmt.setString(6, address); 78 | return pstmt.executeUpdate(); 79 | 80 | } catch (SQLException e) { 81 | // ignored 82 | } finally { 83 | SQLiteJDBC.close(pstmt, conn); 84 | } return -1; 85 | } 86 | 87 | @Override 88 | public List findByDomainOrIp(String filter) { 89 | List hosts = new ArrayList(); 90 | try { 91 | conn = SQLiteJDBC.connect(); 92 | pstmt = conn.prepareStatement( 93 | Settings.get("sqlSelectCustomHostsByDomainOrIp")); 94 | pstmt.setString(1, "%" + filter + "%"); 95 | pstmt.setString(2, "%" + filter + "%"); 96 | rs = pstmt.executeQuery(); 97 | while (rs.next()) 98 | hosts.add(new CustomHost( 99 | (String) rs.getString("domain") 100 | , (String) rs.getString("address") 101 | , rs.getInt("status") 102 | )); 103 | 104 | } catch (SQLException e) { 105 | // ignored 106 | } finally { 107 | SQLiteJDBC.close(rs, pstmt, conn); 108 | } 109 | return hosts; 110 | } 111 | 112 | @Override 113 | public int getHostsCount() { 114 | try { 115 | conn = SQLiteJDBC.connect(); 116 | int count = -1; 117 | stmt = conn.createStatement(); 118 | 119 | rs = stmt.executeQuery(Settings.get("sqlSelectCustomHostsCount")); 120 | if (rs.next()) 121 | count = (Integer) rs.getInt("total"); 122 | 123 | return count; 124 | } catch (SQLException e) { 125 | // ignored 126 | } finally { 127 | SQLiteJDBC.close(rs, stmt, conn); 128 | } 129 | return -1; 130 | } 131 | 132 | @Override 133 | public void deleteAll() { 134 | try { 135 | conn = SQLiteJDBC.connect(); 136 | stmt = conn.createStatement(); 137 | rs = stmt.executeQuery(Settings.get("sqlDeleteAllCustomHosts")); 138 | } catch (SQLException e) { 139 | //ignored 140 | } finally { 141 | SQLiteJDBC.close(rs, stmt, conn); 142 | } 143 | } 144 | 145 | @Override 146 | public List findByStatus(int status) { 147 | List hosts = new ArrayList(); 148 | try { 149 | conn = SQLiteJDBC.connect(); 150 | pstmt = conn.prepareStatement(Settings.get("sqlSelectCustomHostsByStatus")); 151 | pstmt.setInt(1, status); 152 | rs = pstmt.executeQuery(); 153 | while (rs.next()) 154 | hosts.add(new CustomHost( 155 | (String) rs.getString("domain") 156 | , (String) rs.getString("address") 157 | , (int) rs.getInt("status")) 158 | ); 159 | } catch (SQLException e) { 160 | // ignored 161 | } finally { 162 | SQLiteJDBC.close(rs, stmt, conn); 163 | } 164 | return hosts; 165 | } 166 | 167 | } 168 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/HostSQLiteRepository.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import application.business.repository.HostRepository; 8 | import application.model.Host; 9 | import application.persistence.sqlite.util.SQLiteJDBC; 10 | import application.util.properties.Settings; 11 | 12 | public class HostSQLiteRepository extends BaseSQLiteRepository implements HostRepository{ 13 | 14 | public int addHosts(List newHostsList) { 15 | try { 16 | conn = SQLiteJDBC.connect(); 17 | conn.setAutoCommit(false); 18 | pstmt = conn.prepareStatement( 19 | Settings.get("sqlInsertHost")); 20 | for (Host newHost : newHostsList) { 21 | pstmt.setString(1, newHost.getDomain()); 22 | pstmt.setInt(2, newHost.getCategory()); 23 | pstmt.setInt(3, newHost.getStatus()); 24 | pstmt.setString(4, newHost.getComment()); 25 | pstmt.setLong(5, newHost.getUpdatedAt()); 26 | pstmt.executeUpdate();} 27 | 28 | conn.commit(); 29 | return newHostsList.size(); 30 | } catch (SQLException e) { 31 | //ignored 32 | } finally { 33 | SQLiteJDBC.close(pstmt, conn); 34 | } 35 | return 0; 36 | 37 | } 38 | 39 | public int getHostsCount() { 40 | try { 41 | conn = SQLiteJDBC.connect(); 42 | int count = -1; 43 | stmt = conn.createStatement(); 44 | 45 | rs = stmt.executeQuery(Settings.get("sqlSelectHostsCount")); 46 | if (rs.next()) 47 | count = (Integer) rs.getInt("total"); 48 | 49 | return count; 50 | } catch (SQLException e) { 51 | //ignored 52 | } finally { 53 | SQLiteJDBC.close(rs, stmt, conn); 54 | } 55 | return -1; 56 | } 57 | 58 | @Override 59 | public List findAll() { 60 | List hosts = new ArrayList(); 61 | try { 62 | conn = SQLiteJDBC.connect(); 63 | stmt = conn.createStatement(); 64 | rs = stmt.executeQuery(Settings.get("sqlSelectHosts")); 65 | while (rs.next()) 66 | hosts.add(new Host( 67 | (String) rs.getString("domain") 68 | , rs.getInt("category") 69 | , rs.getInt("status") 70 | , (String) rs.getString("comment") 71 | , rs.getInt("updated_at") 72 | )); 73 | 74 | } catch (SQLException e) { 75 | //ignored 76 | } finally { 77 | SQLiteJDBC.close(rs, stmt, conn); 78 | } 79 | return hosts; 80 | } 81 | 82 | @Override 83 | public int add(Host newHost) { 84 | try {conn = SQLiteJDBC.connect(); 85 | pstmt = conn.prepareStatement( 86 | Settings.get("sqlInsertHost")); 87 | pstmt.setString(1, newHost.getDomain()); 88 | pstmt.setInt(2, newHost.getCategory()); 89 | pstmt.setInt(3, newHost.getStatus()); 90 | pstmt.setString(4, newHost.getComment()); 91 | pstmt.setLong(5, newHost.getUpdatedAt()); 92 | return pstmt.executeUpdate(); 93 | 94 | } catch (SQLException e) { 95 | //ignored 96 | } finally { 97 | SQLiteJDBC.close(pstmt, conn); 98 | } 99 | return 0; 100 | 101 | } 102 | 103 | @Override 104 | public void delete(Host t) { 105 | // TODO Auto-generated method stub 106 | 107 | } 108 | 109 | @Override 110 | public Host findById(Long id) { 111 | // TODO Auto-generated method stub 112 | return null; 113 | } 114 | 115 | @Override 116 | public void toggleHostStatus(String domain) { 117 | try { 118 | conn = SQLiteJDBC.connect(); 119 | pstmt = conn.prepareStatement( 120 | Settings.get("sqlUpdateHostToggleStatus")); 121 | pstmt.setString(1, domain); 122 | pstmt.setString(2, domain); 123 | pstmt.setString(3, domain); 124 | pstmt.executeUpdate(); 125 | 126 | } catch (SQLException e) { 127 | //ignored 128 | } finally { 129 | SQLiteJDBC.close(pstmt, conn); 130 | } 131 | } 132 | 133 | @Override 134 | public List findByDomain(String domain) { 135 | List hosts = new ArrayList(); 136 | try { 137 | conn = SQLiteJDBC.connect(); 138 | pstmt = conn.prepareStatement( 139 | Settings.get("sqlSelectHostsByDomain")); 140 | pstmt.setString(1, "%" + domain + "%"); 141 | rs = pstmt.executeQuery(); 142 | while (rs.next()) 143 | hosts.add(new Host( 144 | (String) rs.getString("domain") 145 | , rs.getInt("category") 146 | , rs.getInt("status") 147 | , (String) rs.getString("comment") 148 | , rs.getInt("updated_at") 149 | )); 150 | 151 | } catch (SQLException e) { 152 | //ignored 153 | } finally { 154 | SQLiteJDBC.close(rs, pstmt, conn); 155 | } 156 | return hosts; 157 | } 158 | 159 | @Override 160 | public void deleteAll() { 161 | try { 162 | conn = SQLiteJDBC.connect(); 163 | stmt = conn.createStatement(); 164 | rs = stmt.executeQuery(Settings.get("sqlDeleteAllHosts")); 165 | } catch (SQLException e) { 166 | //ignored 167 | } finally { 168 | SQLiteJDBC.close(rs, stmt, conn); 169 | } 170 | } 171 | 172 | @Override 173 | public List findByCategory(int category) { 174 | List hosts = new ArrayList(); 175 | try { 176 | conn = SQLiteJDBC.connect(); 177 | pstmt = conn.prepareStatement(Settings.get("sqlSelectHostsByCategory")); 178 | pstmt.setInt(1, category); 179 | rs = pstmt.executeQuery(); 180 | while (rs.next()) 181 | hosts.add(new Host( 182 | (String) rs.getString("domain") 183 | , rs.getInt("category") 184 | , rs.getInt("status") 185 | , (String) rs.getString("comment") 186 | , rs.getInt("updated_at") 187 | )); 188 | 189 | } catch (SQLException e) { 190 | //ignored 191 | } finally { 192 | SQLiteJDBC.close(rs, pstmt, conn); 193 | } 194 | return hosts; 195 | } 196 | 197 | @Override 198 | public List findByStatus(int status) { 199 | List hosts = new ArrayList(); 200 | try { 201 | conn = SQLiteJDBC.connect(); 202 | pstmt = conn.prepareStatement(Settings.get("sqlSelectHostsByStatus")); 203 | pstmt.setInt(1, status); 204 | rs = pstmt.executeQuery(); 205 | while (rs.next()) 206 | hosts.add(new Host( 207 | (String) rs.getString("domain") 208 | , rs.getInt("category") 209 | , rs.getInt("status") 210 | , (String) rs.getString("comment") 211 | , rs.getInt("updated_at") 212 | )); 213 | 214 | } catch (SQLException e) { 215 | //ignored 216 | } finally { 217 | SQLiteJDBC.close(rs, stmt, conn); 218 | } 219 | return hosts; 220 | } 221 | } 222 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/SQLiteRepositoryFactory.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite; 2 | 3 | import application.business.repository.ConfigurationRepository; 4 | import application.business.repository.CustomHostRepository; 5 | import application.business.repository.HostRepository; 6 | import application.business.repository.RepositoryFactory; 7 | 8 | public class SQLiteRepositoryFactory implements RepositoryFactory{ 9 | 10 | @Override 11 | public HostRepository forHost() { 12 | return new HostSQLiteRepository(); 13 | } 14 | 15 | @Override 16 | public CustomHostRepository forCustomHost() { 17 | return new CustomHostSQLiteRepository(); 18 | } 19 | 20 | @Override 21 | public ConfigurationRepository forConfiguration() { 22 | return new ConfigurationSQLiteRepository(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/application/persistence/sqlite/util/SQLiteJDBC.java: -------------------------------------------------------------------------------- 1 | package application.persistence.sqlite.util; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import java.sql.Statement; 8 | 9 | import application.util.Logger; 10 | import application.util.SystemUtil; 11 | import application.util.properties.Settings; 12 | 13 | public class SQLiteJDBC { 14 | 15 | private static SQLiteJDBC manager; 16 | 17 | /** 18 | * Connect to the database 19 | * 20 | * If the database does not exist, then SQLite automatically creates it. 21 | */ 22 | public static Connection connect() { 23 | 24 | try { 25 | String url = "jdbc:sqlite:" + SystemUtil.getVihomaFolderPath() + "vihoma.sqlite"; 26 | 27 | Connection conn = DriverManager.getConnection(url); 28 | 29 | return conn; 30 | } catch (SQLException e) { 31 | Logger.err(e.getMessage()); 32 | return null; 33 | } 34 | 35 | } 36 | 37 | /** 38 | * @param args the command line arguments 39 | */ 40 | public static void main(String[] args) { 41 | getManager().setUp(); 42 | } 43 | 44 | public static SQLiteJDBC getManager() { 45 | if (null == manager) { 46 | manager = new SQLiteJDBC(); 47 | manager.setUp(); 48 | } 49 | return manager; 50 | } 51 | 52 | /** 53 | * creates all the tables in the database and adds some minimal data. 54 | * If the db already exists, it's not changed. 55 | */ 56 | private void setUp() { 57 | // drop evrything (or delete file) 58 | Connection conn = connect(); 59 | try { 60 | conn.setAutoCommit(false); 61 | 62 | conn.createStatement().execute(Settings.get("sqlCreateCustomHostsTable")); 63 | conn.createStatement().execute(Settings.get("sqlCreateHostsTable")); 64 | conn.createStatement().execute(Settings.get("sqlCreateConfigurationTable")); 65 | 66 | conn.commit(); 67 | 68 | } catch (SQLException e) { 69 | Logger.err(e.toString()); 70 | } finally { 71 | close(conn); 72 | } 73 | } 74 | 75 | public static void close(ResultSet rs, Statement stmt, Connection conn) { 76 | close(rs); 77 | close(stmt,conn); 78 | } 79 | 80 | public static void close(ResultSet rs) { 81 | try { rs.close(); } catch (Exception e) { /* Ignore */} 82 | } 83 | 84 | public static void close(Statement stmt, Connection conn) { 85 | try { stmt.close(); } catch (Exception e) { /* Ignore */ } 86 | close(conn); 87 | } 88 | 89 | public static void close(Connection conn) { 90 | try { conn.close(); } catch (Exception e) { /* Ignore */ } 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /src/application/util/HostsFileManager.java: -------------------------------------------------------------------------------- 1 | package application.util; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.List; 8 | 9 | import application.model.CustomHost; 10 | import application.model.Host; 11 | import application.util.properties.Settings; 12 | 13 | /** 14 | * This class manages the persistence to the hosts file. 15 | * 16 | */ 17 | public class HostsFileManager { 18 | 19 | /** 20 | * shortcut for persistHostsFile({system hosts file path}, blockedHostsList, 21 | * blockedAddress, customHostsList). 22 | * @param blockedHostsList 23 | * @param blockedAddress 24 | * @param customHostsList 25 | * @throws IOException 26 | */ 27 | public static void persistHostsFile(List blockedHostsList, String blockedAddress, List customHostsList) throws IOException { 28 | persistHostsFile(SystemUtil.getHostsPath(),blockedHostsList, blockedAddress, customHostsList); 29 | } 30 | 31 | /** 32 | * persist the provided hosts list into the system hosts file. CustomHosts are 33 | * persisted before the blocked hosts. If the hosts file cannot be accessed, 34 | * the hosts are persisted in the Vihoma folder. 35 | * @param filePath 36 | * @param blockedHostsList the list of blocks which will be prepended by the 37 | * blockedAddress 38 | * @param blockedAddress ip address used to block (redirect) the list of blocked 39 | * hosts 40 | * @param customHostsList the list of the custom host to be persisted 41 | * @throws IOException if the filen cannot be found, or the user does not have 42 | * enough permissions to access it. 43 | */ 44 | public static void persistHostsFile(String filePath, List blockedHostsList, String blockedAddress, 45 | List customHostsList) throws IOException{ 46 | 47 | StringBuilder sb = new StringBuilder(); 48 | BufferedWriter writer; 49 | try { 50 | writer = new BufferedWriter(new FileWriter(filePath)); 51 | sb.append(Settings.get("hostsFileHeader")); 52 | 53 | sb.append("\r\n# CUSTOM hosts go here:\r\n\r\n"); 54 | for (CustomHost chost : customHostsList) 55 | sb.append(chost.getAddress()) 56 | .append(" ").append(chost.getDomain()) 57 | .append("\r\n"); 58 | 59 | sb.append("\r\n\r\n# BLOCKED hosts start here:\r\n\r\n"); 60 | for (Host host : blockedHostsList) 61 | sb.append(blockedAddress) 62 | .append(" ").append(host.getDomain()) 63 | .append("\r\n"); 64 | 65 | writer.write(sb.toString()); 66 | writer.close(); 67 | } catch (FileNotFoundException e) { 68 | Logger.err("HOST FILE NOT FOUND: " + e.getMessage()); 69 | persistHostsFile(SystemUtil.getVihomaFolderPath() + "hosts" 70 | , blockedHostsList, blockedAddress, customHostsList); 71 | } catch (IOException e) { 72 | Logger.err(e.getMessage()); 73 | throw e; 74 | } 75 | 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/application/util/Logger.java: -------------------------------------------------------------------------------- 1 | package application.util; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.FileWriter; 5 | import java.io.IOException; 6 | import java.sql.Timestamp; 7 | 8 | /** 9 | * saves system messages into log files inside the Vihoma system folder. 10 | * 11 | */ 12 | public class Logger { 13 | 14 | /** 15 | * saves the results of some of the processes of the program into the vihoma.log 16 | * file 17 | * @param message the message to save into the log file 18 | */ 19 | public static void log(String message) { 20 | if (null == message || "".equals(message)) { 21 | return; 22 | } 23 | 24 | String path = SystemUtil.getVihomaFolderPath() + "vihoma.log"; 25 | BufferedWriter writer; 26 | message = new Timestamp(System.currentTimeMillis()) + "\t" + message + "\r\n"; 27 | try { 28 | writer = new BufferedWriter(new FileWriter(path, true)); 29 | writer.append(message); 30 | writer.close(); 31 | } catch (IOException e) { 32 | System.out.println("Logger cannot access Vihoma folder"); 33 | } 34 | } 35 | 36 | /** 37 | * saves error messages into the vihoma.err log file 38 | * @param message the error to save into the log file 39 | */ 40 | public static void err(String message) { 41 | if (null == message || "".equals(message)) { 42 | return; 43 | } 44 | 45 | String path = SystemUtil.getVihomaFolderPath() + "vihoma.err"; 46 | BufferedWriter writer; 47 | message = new Timestamp(System.currentTimeMillis()) + "\t" + message + "\r\n"; 48 | try { 49 | writer = new BufferedWriter(new FileWriter(path, true)); 50 | writer.append(message); 51 | writer.close(); 52 | } catch (IOException e) { 53 | System.out.println("Logger cannot access Vihoma folder"); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/application/util/SystemUtil.java: -------------------------------------------------------------------------------- 1 | package application.util; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.io.UnsupportedEncodingException; 6 | import java.net.URISyntaxException; 7 | import java.net.URLDecoder; 8 | 9 | import application.util.properties.Settings; 10 | 11 | /** 12 | * This class provides filesystem related methods and the administrator permission 13 | * checker. 14 | */ 15 | public class SystemUtil { 16 | 17 | /** 18 | * gets the absolute path to the system hosts file depending on the operating 19 | * system where the program is being run. 20 | * @return %ROOT%\System32\drivers\etc\hosts on Windows os, /etc/hosts on 21 | * linux-based oses 22 | */ 23 | public static String getHostsPath() { 24 | String os = System.getProperty("os.name").toLowerCase(); 25 | if(os.indexOf("win") >= 0) 26 | return System.getenv("SystemRoot") + Settings.get("hostsFilePathWindows"); 27 | else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) 28 | return Settings.get("hostsFilePathLinux"); 29 | else if (os.indexOf("mac") >= 0) 30 | return Settings.get("hostsFilePathMac"); 31 | else if (os.indexOf("sunos") >= 0) 32 | return Settings.get("hostsFilePathSolaris"); 33 | 34 | throw new IllegalStateException("Cannot set os"); 35 | } 36 | 37 | /** 38 | * gets the absolute path to the folder where all local files (configuration, 39 | * logs, database) of Vihoma are stored. 40 | * @return %AppData%\Vihoma\ on Windows os, ~.local/vihoma/ on linux-based oses 41 | */ 42 | public static String getVihomaFolderPath() { 43 | String os = System.getProperty("os.name").toLowerCase(); 44 | if(os.indexOf("win") >= 0) 45 | return System.getProperty("user.home") + Settings.get("VihomaPathWindows"); 46 | else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0) 47 | return Settings.get("VihomaPathLinux"); 48 | else if (os.indexOf("mac") >= 0) 49 | return Settings.get("VihomaPathMac"); 50 | else if (os.indexOf("sunos") >= 0) 51 | return Settings.get("VihomaPathSolaris"); 52 | 53 | throw new IllegalStateException("Cannot set os"); 54 | } 55 | 56 | /** 57 | * tries to write a temporal file in the system's hosts folder. 58 | * @return true if the action is completed, false otherwise. 59 | */ 60 | public static boolean isAdmin() { 61 | try { 62 | File f = new File(getHostsPath()+".test"); 63 | f.createNewFile(); 64 | f.delete(); 65 | return true; 66 | } catch (IOException e) { 67 | return false; 68 | } 69 | } 70 | 71 | /** 72 | * removes the Vihoma system folder and its contents. 73 | */ 74 | public static void removeVihomaFolderPath() { 75 | try { 76 | File vihomaFolder = new File(getVihomaFolderPath()); 77 | for (File f : vihomaFolder.listFiles()) 78 | f.delete(); 79 | vihomaFolder.delete(); 80 | } catch (NullPointerException e) { 81 | // the vihoma folder cannot be removed, probably because of user 82 | // permissions. Logging here would re-create the files it is trying 83 | // to delete: do nothing 84 | } 85 | } 86 | 87 | /** 88 | * returns the system path to the running Vihoma jar. 89 | * @return the path to the Vihoma.jar file, an empty string if some error 90 | * occurs 91 | */ 92 | public static String getVihomaJarPath() { 93 | try { 94 | return URLDecoder.decode(SystemUtil.class.getProtectionDomain() 95 | .getCodeSource().getLocation().toURI().getPath(), "UTF-8") 96 | .substring(1); 97 | } catch (URISyntaxException | UnsupportedEncodingException e) { 98 | Logger.err(e.getMessage()); 99 | return ""; 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/application/util/WebUtil.java: -------------------------------------------------------------------------------- 1 | package application.util; 2 | 3 | import java.awt.Desktop; 4 | import java.io.BufferedReader; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.io.InputStreamReader; 8 | import java.net.HttpURLConnection; 9 | import java.net.URL; 10 | import java.nio.file.Files; 11 | import java.nio.file.StandardCopyOption; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import java.util.regex.Pattern; 15 | import java.util.zip.GZIPInputStream; 16 | 17 | import application.model.Host; 18 | import application.util.properties.Settings; 19 | 20 | public class WebUtil { 21 | 22 | /** 23 | * reads a standard hosts file and adds its domains to the database. 24 | * The file should have 0.0.0.0 as the blocked address. 25 | * @param source the HTTP URL from where the host file is downloaded. If null 26 | * or blank (""), it takes the default value, sbc.io/hosts/hosts 27 | * @return a list of Hosts. If the connection fails, null. 28 | */ 29 | public static List getHostsFromWebSource(String source) { 30 | URL url; 31 | try { 32 | url = new URL(source); 33 | HttpURLConnection con = (HttpURLConnection) url.openConnection(); 34 | con.setRequestProperty("Accept-Encoding", "gzip"); 35 | con.setRequestMethod("GET"); 36 | con.setConnectTimeout(4000); 37 | 38 | List hosts = new ArrayList(); 39 | 40 | if (200 == con.getResponseCode()) { 41 | BufferedReader in; 42 | if ("gzip".equals(con.getContentEncoding())) 43 | in = new BufferedReader(new InputStreamReader( 44 | new GZIPInputStream(con.getInputStream()))); 45 | else 46 | in = new BufferedReader( 47 | new InputStreamReader(con.getInputStream())); 48 | String inputLine; 49 | String domain = ""; 50 | while (null != (inputLine = in.readLine())) { 51 | if (inputLine.trim().startsWith("0.0.0.0")) { 52 | domain = inputLine.trim().split("0.0.0.0 ")[1]; 53 | if (!" ".equals(domain) && !"".equals(domain)) 54 | hosts.add(new Host((String)domain.split("#")[0].trim() 55 | , 0 56 | , Host.STATUS_ACTIVE 57 | ,"" 58 | , 0)); 59 | } 60 | } 61 | in.close(); 62 | con.disconnect(); 63 | return hosts; 64 | } else { 65 | throw new IOException(); 66 | } 67 | } catch (IOException e) { 68 | Logger.err(Settings.get("webSourceConnectionError") + "(" + source + ")"); 69 | return null; 70 | } 71 | 72 | } 73 | 74 | /** 75 | * validates an address with the IPv4 and IPv6 specification formats. 76 | * @param address the address to be validated 77 | * @return true if the address follows at least one of the specifications, 78 | * false otherwise. 79 | */ 80 | public static boolean checkIpValidity(String address) { 81 | List regex = new ArrayList(); 82 | // IPV4_REGEX 83 | regex.add("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"); 84 | // IPV6_HEX4DECCOMPRESSED_REGEX 85 | regex.add("\\\\A(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)(\\\\.(25[0-5]|2[0-4]\\\\d|[0-1]?\\\\d?\\\\d)){3}\\\\z"); 86 | // IPV6_6HEX4DEC_REGEX 87 | regex.add("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z"); 88 | // IPV6_HEXCOMPRESSED_REGEX 89 | regex.add("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z"); 90 | // IPV6_REGEX 91 | regex.add("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z"); 92 | 93 | for (String reg : regex) 94 | if (Pattern.matches(reg, address)) { 95 | return true; 96 | } 97 | return false; 98 | } 99 | 100 | /** 101 | * creates a temporal file with the HTML user guide and opens the browser to 102 | * show it to the user. 103 | * @return true if the file can be opened in the browser, false otherwise 104 | * (file not found, browser opening operation not supported..) 105 | */ 106 | public static boolean openHelp() { 107 | try { 108 | String base =//WebUtil.class.getProtectionDomain().getCodeSource() 109 | //.getLocation().getPath() 110 | SystemUtil.getHostsPath().split("hosts")[0] +".vihomahelp.tmp.html"; 111 | File tempHelp = 112 | new File(base); 113 | tempHelp.deleteOnExit(); 114 | Files.copy( 115 | WebUtil.class.getResourceAsStream( 116 | Settings.get("helpPathLocationEN")) 117 | , tempHelp.toPath() 118 | , StandardCopyOption.REPLACE_EXISTING); 119 | 120 | Desktop.getDesktop().browse(tempHelp.toURI()); 121 | return true; 122 | } catch (UnsupportedOperationException | IOException e) { 123 | Logger.err(e.getMessage()); 124 | return false; 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/application/util/WindowsUtil.java: -------------------------------------------------------------------------------- 1 | package application.util; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | /** 8 | * This class provides some Windows Operating System auxiliary methods. 9 | * 10 | */ 11 | public class WindowsUtil { 12 | 13 | /** 14 | * Queries the value of the DNScache start Windows registry. 15 | * @return true if the query does not return '0x4', false otherwise 16 | * @throws IOException if the query cannot be done 17 | */ 18 | public static boolean isDNSClientActivated() throws IOException { 19 | Process process = Runtime. 20 | getRuntime(). 21 | exec("reg query HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\Dnscache /v Start"); 22 | 23 | BufferedReader br = new BufferedReader( 24 | new InputStreamReader(process.getInputStream())); 25 | String line; 26 | StringBuilder sb = new StringBuilder(); 27 | while ((line = br.readLine()) != null) { 28 | sb.append(line); 29 | } 30 | br.close(); 31 | 32 | if (sb.toString().indexOf("0x4") == -1) 33 | return true; 34 | 35 | return false; 36 | } 37 | 38 | /** 39 | * updates the value of the DNScache start Windows registry. If the start 40 | * is disabled (0x4), it is changed to automatic (0x2), and otherwise. 41 | * @return true if the DNScache start Windows registry has changed 42 | */ 43 | public static boolean toggleWindowsDNSClient() { 44 | try { 45 | boolean wasActivated = isDNSClientActivated(); 46 | if (!wasActivated) 47 | Runtime. 48 | getRuntime(). 49 | exec("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\Dnscache /t REG_DWORD /v Start /d 2 /f"); 50 | else 51 | Runtime. 52 | getRuntime(). 53 | exec("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\Dnscache /t REG_DWORD /v Start /d 4 /f"); 54 | return wasActivated ^ isDNSClientActivated(); 55 | } catch (IOException e) { 56 | //The file can't be accessed (not enough permissions) 57 | Logger.err(e.getMessage()); 58 | return false; 59 | } 60 | } 61 | 62 | /** 63 | * checks if the Windows registry has an entry to run the program at the 64 | * operating system startup 65 | * @return true if the entry is found, false otherwise 66 | * @throws IOException 67 | */ 68 | public static boolean isRunAtStartup() throws IOException { 69 | Process process = Runtime. 70 | getRuntime(). 71 | exec("reg query HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"); 72 | 73 | BufferedReader br = new BufferedReader( 74 | new InputStreamReader(process.getInputStream())); 75 | String line; 76 | StringBuilder sb = new StringBuilder(); 77 | while ((line = br.readLine()) != null) { 78 | sb.append(line); 79 | } 80 | br.close(); 81 | 82 | if (sb.toString().indexOf("Vihoma") == -1) 83 | return false; 84 | 85 | return true; 86 | } 87 | 88 | /** 89 | * toggles the start of Vihoma at the windows start. It adds or removes an 90 | * entry to the Windows registry. 91 | * @return true if the Windows registry changed 92 | */ 93 | public static boolean toggleWindowsStartup() { 94 | try { 95 | boolean wasSetUp = isRunAtStartup(); 96 | if (!wasSetUp) { 97 | String path = (SystemUtil.getVihomaJarPath().split("vihoma.jar")[0]).replace('/', '\\') 98 | +"vihomaAdmin.bat quiet"; 99 | Runtime. 100 | getRuntime(). 101 | exec("reg add HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /t REG_SZ /v Vihoma /d \"" + path + "\" /f"); 102 | } 103 | else 104 | Runtime. 105 | getRuntime(). 106 | exec("reg delete HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /v Vihoma /f"); 107 | return wasSetUp ^ isRunAtStartup(); 108 | } catch (IOException e) { 109 | Logger.err(e.getMessage()); 110 | return false; 111 | } 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/application/util/properties/Messages.java: -------------------------------------------------------------------------------- 1 | package application.util.properties; 2 | 3 | import java.io.IOException; 4 | import java.util.Properties; 5 | 6 | /** 7 | * This class manages the file storing the messages that will be shown in the UI 8 | * layer to the user. If i18ned, the language file is changed here. 9 | * 10 | */ 11 | public class Messages{ 12 | 13 | private static String CONF_FILE = "messages_en.properties"; 14 | 15 | private static Messages instance; 16 | private static Properties properties; 17 | 18 | private Messages() { 19 | properties = new Properties(); 20 | changePropertiesFile(); 21 | } 22 | 23 | private static void changePropertiesFile() { 24 | try { 25 | properties.load(Settings.class.getClassLoader().getResourceAsStream(CONF_FILE)); 26 | } catch (IOException e) { 27 | throw new RuntimeException("Propeties file can not be loaded", e); 28 | } 29 | } 30 | 31 | public static String get(String key) { 32 | return getInstance().getProperty( key ); 33 | } 34 | 35 | private String getProperty(String key) { 36 | String value = properties.getProperty(key); 37 | if (value == null) { 38 | throw new RuntimeException("Property not found in config file"); 39 | } 40 | return value; 41 | } 42 | 43 | private static Messages getInstance() { 44 | if (instance == null) { 45 | instance = new Messages(); 46 | } 47 | return instance; 48 | } 49 | 50 | public static void setLanguage(String locale) { 51 | //TODO 52 | //if esES... CONF_FILE = x 53 | //if enEN... 54 | changePropertiesFile(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/application/util/properties/Settings.java: -------------------------------------------------------------------------------- 1 | package application.util.properties; 2 | 3 | import java.io.IOException; 4 | import java.util.Properties; 5 | 6 | /** 7 | * This class manages the file storing the internal text that will be used 8 | * in logs, system and web paths, and SQl queries. 9 | * 10 | */ 11 | public class Settings { 12 | 13 | private static final String CONF_FILE = "configuration.properties"; 14 | 15 | private static Settings instance; 16 | private Properties properties; 17 | 18 | private Settings() { 19 | properties = new Properties(); 20 | try { 21 | properties.load(Settings.class.getClassLoader().getResourceAsStream(CONF_FILE)); 22 | } catch (IOException e) { 23 | throw new RuntimeException("Propeties file can not be loaded", e); 24 | } 25 | } 26 | 27 | public static String get(String key) { 28 | return getInstance().getProperty( key ); 29 | } 30 | 31 | private String getProperty(String key) { 32 | String value = properties.getProperty(key); 33 | if (value == null) { 34 | throw new RuntimeException("Property not found in config file"); 35 | } 36 | return value; 37 | } 38 | 39 | private static Settings getInstance() { 40 | if (instance == null) { 41 | instance = new Settings(); 42 | } 43 | return instance; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/application/view/ErrorAdminController.java: -------------------------------------------------------------------------------- 1 | package application.view; 2 | 3 | import application.util.properties.Messages; 4 | import javafx.fxml.FXML; 5 | import javafx.scene.control.Label; 6 | import javafx.stage.Stage; 7 | 8 | /** 9 | * This controller will be used to show the user a screen requiring to run the 10 | * program with admin privileges. 11 | */ 12 | public class ErrorAdminController { 13 | 14 | @FXML 15 | private Label text; 16 | private Stage dialogStage; 17 | private boolean okClicked = false; 18 | 19 | /** 20 | * Initializes the controller class. This method is automatically called after 21 | * the fxml file has been loaded. 22 | */ 23 | @FXML 24 | protected void initialize() { 25 | text.setText(Messages.get("errorVihomaRequiresAdminRights")); 26 | } 27 | 28 | /** 29 | * Sets the stage of this dialog. 30 | * 31 | * @param dialogStage 32 | */ 33 | public void setDialogStage(Stage dialogStage) { 34 | this.dialogStage = dialogStage; 35 | } 36 | 37 | /** 38 | * Returns true if the user clicked OK, false otherwise. 39 | * 40 | * @return 41 | */ 42 | public boolean isOkClicked() { 43 | return okClicked; 44 | } 45 | 46 | /** 47 | * Called when the user clicks ok. 48 | */ 49 | @FXML 50 | protected void handleOk() { 51 | okClicked = true; 52 | dialogStage.close(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/application/view/ErrorAdminDialog.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/application/view/ErrorDialog.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/application/view/ErrorDialogController.java: -------------------------------------------------------------------------------- 1 | package application.view; 2 | 3 | import application.util.properties.Messages; 4 | import javafx.fxml.FXML; 5 | import javafx.scene.control.Label; 6 | import javafx.stage.Stage; 7 | 8 | /** 9 | * This controller will be used to show the user a screen notifying that an 10 | * unrecoverable error has been produced and that it is necessary to close the 11 | * application. 12 | */ 13 | public class ErrorDialogController { 14 | 15 | @FXML 16 | private Label text; 17 | private Stage dialogStage; 18 | private boolean okClicked = false; 19 | 20 | /** 21 | * Initializes the controller class. This method is automatically called after 22 | * the fxml file has been loaded. 23 | */ 24 | @FXML 25 | protected void initialize() { 26 | text.setText(Messages.get("errorDetectedClose")); 27 | } 28 | 29 | /** 30 | * Sets the stage of this dialog. 31 | * 32 | * @param dialogStage 33 | */ 34 | public void setDialogStage(Stage dialogStage) { 35 | this.dialogStage = dialogStage; 36 | } 37 | 38 | /** 39 | * Returns true if the user clicked OK, false otherwise. 40 | * 41 | * @return 42 | */ 43 | public boolean isOkClicked() { 44 | return okClicked; 45 | } 46 | 47 | /** 48 | * Called when the user clicks ok. 49 | */ 50 | @FXML 51 | protected void handleOk() { 52 | okClicked = true; 53 | dialogStage.close(); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/application/view/MainView.fxml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 90 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 138 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 |