diff --git a/.buildpath b/.buildpath index cf9cdf2..2119916 100644 --- a/.buildpath +++ b/.buildpath @@ -1,7 +1,7 @@ - - - - - - - + + + + + + + diff --git a/.classpath b/.classpath index 4436e4c..0babe36 100644 --- a/.classpath +++ b/.classpath @@ -1,21 +1,21 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project index 1b29135..0f11882 100644 --- a/.project +++ b/.project @@ -1,29 +1,29 @@ - - - ChatServer - - - - - - org.eclipse.vjet.eclipse.core.builder - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.vjet.core.nature - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - - + + + ChatServer + + + + + + org.eclipse.vjet.eclipse.core.builder + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.vjet.core.nature + org.eclipse.m2e.core.maven2Nature + org.eclipse.jdt.core.javanature + + diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 5648b30..cbd0dab 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,106 +1,106 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullable.secondary= -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=ignore -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning -org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=ignore +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=ignore +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.vjet.eclipse.core.prefs b/.settings/org.eclipse.vjet.eclipse.core.prefs index 46d2bef..6e8a644 100644 --- a/.settings/org.eclipse.vjet.eclipse.core.prefs +++ b/.settings/org.eclipse.vjet.eclipse.core.prefs @@ -1,2 +1,2 @@ -eclipse.preferences.version=1 -initialized_project_from_v4classpath=true +eclipse.preferences.version=1 +initialized_project_from_v4classpath=true diff --git a/main/resources/META-INF/log4j.properties b/main/resources/META-INF/log4j.properties index 48095a7..991393c 100644 --- a/main/resources/META-INF/log4j.properties +++ b/main/resources/META-INF/log4j.properties @@ -1,17 +1,17 @@ -log4j.rootLogger=debug, stdout, R - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout - -# Pattern to output the caller's file name and line number. -log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n - -log4j.appender.R=org.apache.log4j.RollingFileAppender -log4j.appender.R.File=example.log - -log4j.appender.R.MaxFileSize=100KB -# Keep one backup file -log4j.appender.R.MaxBackupIndex=1 - -log4j.appender.R.layout=org.apache.log4j.PatternLayout -log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n +log4j.rootLogger=debug, stdout, R + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout + +# Pattern to output the caller's file name and line number. +log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n + +log4j.appender.R=org.apache.log4j.RollingFileAppender +log4j.appender.R.File=example.log + +log4j.appender.R.MaxFileSize=100KB +# Keep one backup file +log4j.appender.R.MaxBackupIndex=1 + +log4j.appender.R.layout=org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n diff --git a/main/resources/META-INF/persistence.xml b/main/resources/META-INF/persistence.xml index e2963d1..d3530b5 100644 --- a/main/resources/META-INF/persistence.xml +++ b/main/resources/META-INF/persistence.xml @@ -1,12 +1,12 @@ - - - - - - - + + + + + + + \ No newline at end of file diff --git a/pages/.idea/inspectionProfiles/Project_Default.xml b/pages/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index fda1b09..0000000 --- a/pages/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - \ No newline at end of file diff --git a/pages/.idea/inspectionProfiles/profiles_settings.xml b/pages/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 6933c1e..0000000 --- a/pages/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/pages/.idea/modules.xml b/pages/.idea/modules.xml deleted file mode 100644 index bb70234..0000000 --- a/pages/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/pages/.idea/pages.iml b/pages/.idea/pages.iml deleted file mode 100644 index c956989..0000000 --- a/pages/.idea/pages.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/pages/.idea/vcs.xml b/pages/.idea/vcs.xml deleted file mode 100644 index 6c0b863..0000000 --- a/pages/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/pages/.idea/workspace.xml b/pages/.idea/workspace.xml deleted file mode 100644 index fb3a6b4..0000000 --- a/pages/.idea/workspace.xml +++ /dev/null @@ -1,566 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - true - - - - - - - - - - - - Spelling - - - - - SpellCheckingInspection - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - project - - - - - - - - - - - - - - - - project - - - true - - bdd - - DIRECTORY - - false - - - - - - - - - - - - - - - - - - - - - - - 1469522327377 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pages/css/style.css b/pages/css/style.css index 67b0d11..0fca267 100644 --- a/pages/css/style.css +++ b/pages/css/style.css @@ -1,44 +1,44 @@ -body { - background-color: #EEE; -} - -#errormsg, #successmsg { - display: none; -} - -#errormsg { - background-color: #8c0000; - border-color: #ff0000; - border-style: solid; - border-width: 2px; - color: #ff0000; -} - -#successmsg { - background-color: #188c00; - border-color: #00ff00; - border-style: solid; - border-width: 2px; - color: #00ff00; -} - -#sidebar { - float: right; - width: 300px; -} - -#loginregisterbox { - margin: auto; - width: 300px; -} - -#usercontent { - margin: auto; - width: 75%; -} - -#msginput { - width: 100%; - height: 30px; - max-width: 100%; +body { + background-color: #EEE; +} + +#errormsg, #successmsg { + display: none; +} + +#errormsg { + background-color: #8c0000; + border-color: #ff0000; + border-style: solid; + border-width: 2px; + color: #ff0000; +} + +#successmsg { + background-color: #188c00; + border-color: #00ff00; + border-style: solid; + border-width: 2px; + color: #00ff00; +} + +#sidebar { + float: right; + width: 300px; +} + +#loginregisterbox { + margin: auto; + width: 300px; +} + +#usercontent { + margin: auto; + width: 75%; +} + +#msginput { + width: 100%; + height: 30px; + max-width: 100%; } \ No newline at end of file diff --git a/pages/index.html b/pages/index.html index a8da097..0d3248f 100644 --- a/pages/index.html +++ b/pages/index.html @@ -1,86 +1,86 @@ - - - ChatServer - - - - - - - - -
-
- -
-
-

Login

-
- - - - - - - - - - - - -
E-mail: - -
Password: - -
- -
-
-
-
-

Register

-
- - - - - - - - - - - - - - - - - - - - -
Name: - -
E-mail: - -
Password - -
Password confirm - -
- -
-
-
-
-
-
- -
- + + + ChatServer + + + + + + + + +
+
+ +
+
+

Login

+
+ + + + + + + + + + + + +
E-mail: + +
Password: + +
+ +
+
+
+
+

Register

+
+ + + + + + + + + + + + + + + + + + + + +
Name: + +
E-mail: + +
Password + +
Password confirm + +
+ +
+
+
+
+
+
+ +
+ diff --git a/pages/js/login.js b/pages/js/login.js index abc2912..3fce792 100644 --- a/pages/js/login.js +++ b/pages/js/login.js @@ -1,17 +1,17 @@ -/** - * Created by Norbi on 2016-07-26. - */ -function login(form) { //TODO: Detect Enter - var json = JSON.stringify(getFormData($(form))); - $.ajax({ - url: "/login", data: json, method: "POST", success: function (result) { - if (result != "Success") { - var errormsg = document.getElementById("errormsg"); - errormsg.innerHTML = result; - errormsg.style = "display: block"; - } - else - location.reload(true); - } - }); -} +/** + * Created by Norbi on 2016-07-26. + */ +function login(form) { //TODO: Detect Enter + var json = JSON.stringify(getFormData($(form))); + $.ajax({ + url: "/login", data: json, method: "POST", success: function (result) { + if (result != "Success") { + var errormsg = document.getElementById("errormsg"); + errormsg.innerHTML = result; + errormsg.style = "display: block"; + } + else + location.reload(true); + } + }); +} diff --git a/pages/js/message.js b/pages/js/message.js index c8b69ef..d1cbd2d 100644 --- a/pages/js/message.js +++ b/pages/js/message.js @@ -1,4 +1,4 @@ -$('#msginput').keypress(function(e) { - if (e.which == '\r'.charCodeAt(0)) - document.write(document.getElementById("msginput").value); -}); +$('#msginput').keypress(function(e) { + if (e.which == '\r'.charCodeAt(0)) + document.write(document.getElementById("msginput").value); +}); diff --git a/pages/js/register.js b/pages/js/register.js index eac6cc5..3e41d0e 100644 --- a/pages/js/register.js +++ b/pages/js/register.js @@ -1,17 +1,17 @@ -/** - * Created by Norbi on 2016-07-27. - */ -function register(form) { - var json = JSON.stringify(getFormData($(form))); - $.ajax({ - url: "/register", data: json, method: "POST", success: function (result) { - if (result != "Success") { - var errormsg = document.getElementById("errormsg"); - errormsg.innerHTML = result; - errormsg.style = "display: block"; - } - else - location.reload(true); - } - }); -} +/** + * Created by Norbi on 2016-07-27. + */ +function register(form) { + var json = JSON.stringify(getFormData($(form))); + $.ajax({ + url: "/register", data: json, method: "POST", success: function (result) { + if (result != "Success") { + var errormsg = document.getElementById("errormsg"); + errormsg.innerHTML = result; + errormsg.style = "display: block"; + } + else + location.reload(true); + } + }); +} diff --git a/pages/js/utils.js b/pages/js/utils.js index 6f4af7b..7739879 100644 --- a/pages/js/utils.js +++ b/pages/js/utils.js @@ -1,13 +1,13 @@ -/** - * Created by Norbi on 2016-07-27. - */ -function getFormData($form) { - var unindexed_array = $form.serializeArray(); - var indexed_array = {}; - - $.map(unindexed_array, function (n, i) { - indexed_array[n['name']] = n['value']; - }); - - return indexed_array; -} +/** + * Created by Norbi on 2016-07-27. + */ +function getFormData($form) { + var unindexed_array = $form.serializeArray(); + var indexed_array = {}; + + $.map(unindexed_array, function (n, i) { + indexed_array[n['name']] = n['value']; + }); + + return indexed_array; +} diff --git a/pages/notfound.html b/pages/notfound.html index 9d61e2f..ce6cbe9 100644 --- a/pages/notfound.html +++ b/pages/notfound.html @@ -1,5 +1,5 @@ - - -

404 Not found

-

The requested page cannot be found.

- + + +

404 Not found

+

The requested page cannot be found.

+ diff --git a/pom.xml b/pom.xml index fdd526e..8819e72 100644 --- a/pom.xml +++ b/pom.xml @@ -1,78 +1,78 @@ - - 4.0.0 - ChatServer - ChatServer - 0.0.1-SNAPSHOT - - src - - - maven-compiler-plugin - 3.5.1 - - 1.8 - 1.8 - - - - - - - org.apache.derby - derby - 10.12.1.1 - - - org.apache.derby - derbyclient - 10.12.1.1 - - - - org.hibernate - hibernate-core - 5.2.1.Final - - - - commons-io - commons-io - 2.5 - - - org.reflections - reflections - 0.9.10 - runtime - - - - org.jsoup - jsoup - 1.9.2 - - - - org.apache.logging.log4j - log4j-core - 2.6.2 - - - - org.apache.logging.log4j - log4j-api - 2.6.2 - - - - org.json - json - 20160212 - - - - 1.8 - 1.8 - + + 4.0.0 + ChatServer + ChatServer + 0.0.1-SNAPSHOT + + src + + + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + org.apache.derby + derby + 10.12.1.1 + + + org.apache.derby + derbyclient + 10.12.1.1 + + + + org.hibernate + hibernate-core + 5.2.1.Final + + + + commons-io + commons-io + 2.5 + + + org.reflections + reflections + 0.9.10 + runtime + + + + org.jsoup + jsoup + 1.9.2 + + + + org.apache.logging.log4j + log4j-core + 2.6.2 + + + + org.apache.logging.log4j + log4j-api + 2.6.2 + + + + org.json + json + 20160212 + + + + 1.8 + 1.8 + \ No newline at end of file diff --git a/src/io/github/norbipeti/chat/server/IOHelper.java b/src/io/github/norbipeti/chat/server/IOHelper.java index 5c2f97a..55dac68 100644 --- a/src/io/github/norbipeti/chat/server/IOHelper.java +++ b/src/io/github/norbipeti/chat/server/IOHelper.java @@ -1,178 +1,178 @@ -package io.github.norbipeti.chat.server; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.time.Period; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.HashMap; -import java.util.UUID; -import java.util.function.Function; - -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.db.DataProvider; -import io.github.norbipeti.chat.server.db.domain.User; -import io.github.norbipeti.chat.server.page.Page; - -public class IOHelper { - public static void SendResponse(int code, String content, HttpExchange exchange) throws IOException { - exchange.sendResponseHeaders(code, content.length()); - IOUtils.write(content, exchange.getResponseBody(), StandardCharsets.UTF_8); - exchange.getResponseBody().close(); - } - - public static boolean SendPage(int code, Page page, HttpExchange exchange) throws IOException { - String content = GetPage(page, exchange); - SendResponse(code, content, exchange); - return true; - } - - public static String GetPage(Page page, HttpExchange exchange) throws IOException { - File file = new File(page.GetHTMLPath()); - if (!file.exists()) { - SendResponse(501, - "

501 Not Implemented

The page \"" + page.GetName() + "\" cannot be found on disk.", - exchange); - return null; - } - return ReadFile(file); - } - - public static String ReadFile(File file) throws FileNotFoundException, IOException { - FileInputStream inputStream = new FileInputStream(file); - String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); - return content; - } - - @Deprecated - public static HashMap GetPOST(HttpExchange exchange) throws IOException { - if (exchange.getRequestBody().available() == 0) - return new HashMap<>(); - try { - String[] content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1).split("\\&"); - HashMap vars = new HashMap<>(); - for (String var : content) { - String[] spl = var.split("\\="); - if (spl.length == 1) - vars.put(spl[0], ""); - else - vars.put(spl[0], spl[1]); - } - return vars; - } catch (Exception e) { - e.printStackTrace(); - return new HashMap<>(); - } - } - - public static JSONObject GetPOSTJSON(HttpExchange exchange) throws IOException { - if (exchange.getRequestBody().available() == 0) - return null; - try { - String content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1); - JSONObject obj = new JSONObject(content); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static boolean SendModifiedPage(int code, Page page, Function modifyfunc, - HttpExchange exchange) throws IOException { - String content = GetPage(page, exchange); - if (content == null) - return false; - Document doc = Jsoup.parse(content); - doc = modifyfunc.apply(doc); - SendResponse(200, doc.html(), exchange); - return true; - } - - public static void LoginUser(HttpExchange exchange, User user, DataProvider provider) { - provider.SetValues(() -> user.setSessionid(UUID.randomUUID())); - System.out.println("Logging in user: " + user); - ZonedDateTime expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(2, 0, 0)); - exchange.getResponseHeaders().add("Set-Cookie", - "user_id=" + user.getId() + "; expires=" + expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME)); - exchange.getResponseHeaders().add("Set-Cookie", - "session_id=" + user.getSessionid() + "; expires=" + expiretime); - } - - public static void LogoutUser(HttpExchange exchange, User user) { - user.setSessionid(new UUID(0, 0)); - SendLogoutHeaders(exchange); - } - - private static void SendLogoutHeaders(HttpExchange exchange) { - String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT"; - exchange.getResponseHeaders().add("Set-Cookie", "user_id=del; expires=" + expiretime); - exchange.getResponseHeaders().add("Set-Cookie", "session_id=del; expires=" + expiretime); - } - - public static void Redirect(String url, HttpExchange exchange) throws IOException { - exchange.getResponseHeaders().add("Location", url); - IOHelper.SendResponse(303, "If you can see this, click here to continue", exchange); - } - - public static HashMap GetCookies(HttpExchange exchange) { - if (!exchange.getRequestHeaders().containsKey("Cookie")) - return new HashMap<>(); - HashMap map = new HashMap<>(); - for (String cheader : exchange.getRequestHeaders().get("Cookie")) { - String[] spl = cheader.split("\\;\\s*"); - for (String s : spl) { - String[] kv = s.split("\\="); - if (kv.length < 2) - continue; - map.put(kv[0], kv[1]); - } - } - return map; - } - - /** - * Get logged in user. It may also send logout headers if the cookies are - * invalid. - * - * @param exchange - * @return The logged in user or null if not logged in. - */ - public static User GetLoggedInUser(HttpExchange exchange) { - HashMap cookies = GetCookies(exchange); - System.out.println("Cookies: " + cookies); - if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id")) - return null; - System.out.println("Cookies found"); - try (DataProvider provider = new DataProvider()) { - User user = provider.getUser(Long.parseLong(cookies.get("user_id"))); - System.out.println("User: " + user); - System.out.println("session_id: " + cookies.get("session_id")); - if (user != null) - System.out.println("Equals: " + UUID.fromString(cookies.get("session_id")).equals(user.getSessionid())); - if (user != null && cookies.get("session_id") != null - && UUID.fromString(cookies.get("session_id")).equals(user.getSessionid())) - return user; - else - SendLogoutHeaders(exchange); - } - return null; - } - - public static void SendResponse(int code, Function action, HttpExchange exchange) - throws IOException { - Document doc = new Document(""); - doc = action.apply(doc); - SendResponse(200, doc.html(), exchange); - } -} +package io.github.norbipeti.chat.server; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Period; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.HashMap; +import java.util.UUID; +import java.util.function.Function; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.db.DataProvider; +import io.github.norbipeti.chat.server.db.domain.User; +import io.github.norbipeti.chat.server.page.Page; + +public class IOHelper { + public static void SendResponse(int code, String content, HttpExchange exchange) throws IOException { + exchange.sendResponseHeaders(code, content.length()); + IOUtils.write(content, exchange.getResponseBody(), StandardCharsets.UTF_8); + exchange.getResponseBody().close(); + } + + public static boolean SendPage(int code, Page page, HttpExchange exchange) throws IOException { + String content = GetPage(page, exchange); + SendResponse(code, content, exchange); + return true; + } + + public static String GetPage(Page page, HttpExchange exchange) throws IOException { + File file = new File(page.GetHTMLPath()); + if (!file.exists()) { + SendResponse(501, + "

501 Not Implemented

The page \"" + page.GetName() + "\" cannot be found on disk.", + exchange); + return null; + } + return ReadFile(file); + } + + public static String ReadFile(File file) throws FileNotFoundException, IOException { + FileInputStream inputStream = new FileInputStream(file); + String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); + return content; + } + + @Deprecated + public static HashMap GetPOST(HttpExchange exchange) throws IOException { + if (exchange.getRequestBody().available() == 0) + return new HashMap<>(); + try { + String[] content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1).split("\\&"); + HashMap vars = new HashMap<>(); + for (String var : content) { + String[] spl = var.split("\\="); + if (spl.length == 1) + vars.put(spl[0], ""); + else + vars.put(spl[0], spl[1]); + } + return vars; + } catch (Exception e) { + e.printStackTrace(); + return new HashMap<>(); + } + } + + public static JSONObject GetPOSTJSON(HttpExchange exchange) throws IOException { + if (exchange.getRequestBody().available() == 0) + return null; + try { + String content = IOUtils.toString(exchange.getRequestBody(), StandardCharsets.ISO_8859_1); + JSONObject obj = new JSONObject(content); + return obj; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public static boolean SendModifiedPage(int code, Page page, Function modifyfunc, + HttpExchange exchange) throws IOException { + String content = GetPage(page, exchange); + if (content == null) + return false; + Document doc = Jsoup.parse(content); + doc = modifyfunc.apply(doc); + SendResponse(200, doc.html(), exchange); + return true; + } + + public static void LoginUser(HttpExchange exchange, User user, DataProvider provider) { + provider.SetValues(() -> user.setSessionid(UUID.randomUUID())); + System.out.println("Logging in user: " + user); + ZonedDateTime expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(2, 0, 0)); + exchange.getResponseHeaders().add("Set-Cookie", + "user_id=" + user.getId() + "; expires=" + expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME)); + exchange.getResponseHeaders().add("Set-Cookie", + "session_id=" + user.getSessionid() + "; expires=" + expiretime); + } + + public static void LogoutUser(HttpExchange exchange, User user) { + user.setSessionid(new UUID(0, 0)); + SendLogoutHeaders(exchange); + } + + private static void SendLogoutHeaders(HttpExchange exchange) { + String expiretime = "Sat, 19 Mar 2016 23:33:00 GMT"; + exchange.getResponseHeaders().add("Set-Cookie", "user_id=del; expires=" + expiretime); + exchange.getResponseHeaders().add("Set-Cookie", "session_id=del; expires=" + expiretime); + } + + public static void Redirect(String url, HttpExchange exchange) throws IOException { + exchange.getResponseHeaders().add("Location", url); + IOHelper.SendResponse(303, "If you can see this, click here to continue", exchange); + } + + public static HashMap GetCookies(HttpExchange exchange) { + if (!exchange.getRequestHeaders().containsKey("Cookie")) + return new HashMap<>(); + HashMap map = new HashMap<>(); + for (String cheader : exchange.getRequestHeaders().get("Cookie")) { + String[] spl = cheader.split("\\;\\s*"); + for (String s : spl) { + String[] kv = s.split("\\="); + if (kv.length < 2) + continue; + map.put(kv[0], kv[1]); + } + } + return map; + } + + /** + * Get logged in user. It may also send logout headers if the cookies are + * invalid. + * + * @param exchange + * @return The logged in user or null if not logged in. + */ + public static User GetLoggedInUser(HttpExchange exchange) { + HashMap cookies = GetCookies(exchange); + System.out.println("Cookies: " + cookies); + if (!cookies.containsKey("user_id") || !cookies.containsKey("session_id")) + return null; + System.out.println("Cookies found"); + try (DataProvider provider = new DataProvider()) { + User user = provider.getUser(Long.parseLong(cookies.get("user_id"))); + System.out.println("User: " + user); + System.out.println("session_id: " + cookies.get("session_id")); + if (user != null) + System.out.println("Equals: " + UUID.fromString(cookies.get("session_id")).equals(user.getSessionid())); + if (user != null && cookies.get("session_id") != null + && UUID.fromString(cookies.get("session_id")).equals(user.getSessionid())) + return user; + else + SendLogoutHeaders(exchange); + } + return null; + } + + public static void SendResponse(int code, Function action, HttpExchange exchange) + throws IOException { + Document doc = new Document(""); + doc = action.apply(doc); + SendResponse(200, doc.html(), exchange); + } +} diff --git a/src/io/github/norbipeti/chat/server/Main.java b/src/io/github/norbipeti/chat/server/Main.java index b6e80d4..ea76852 100644 --- a/src/io/github/norbipeti/chat/server/Main.java +++ b/src/io/github/norbipeti/chat/server/Main.java @@ -1,109 +1,109 @@ -package io.github.norbipeti.chat.server; - -import java.lang.reflect.Modifier; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Set; - -import org.apache.logging.log4j.Level; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.core.LoggerContext; -import org.apache.logging.log4j.core.config.Configuration; -import org.apache.logging.log4j.core.config.LoggerConfig; -import org.reflections.Reflections; -import org.reflections.scanners.SubTypesScanner; -import org.reflections.util.ClasspathHelper; -import org.reflections.util.ConfigurationBuilder; - -import com.sun.net.httpserver.HttpServer; -import io.github.norbipeti.chat.server.db.*; -import io.github.norbipeti.chat.server.db.domain.*; -import io.github.norbipeti.chat.server.page.*; - -public class Main { - // public static final HashMap Pages = new HashMap(); - - public static void main(String[] args) { // http://stackoverflow.com/questions/9266632/access-restriction-is-not-accessible-due-to-restriction-on-required-library/10642163#10642163 - try { // rt.jar Javadoc: - // https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/ - // https://docs.oracle.com/javase/8/docs/api/ - System.out.println(System.getProperty("java.class.path")); // TODO: - // log4j - LoggerContext ctx = (LoggerContext) LogManager.getContext(false); - Configuration config = ctx.getConfiguration(); - LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); - loggerConfig.setLevel(Level.WARN); - ctx.updateLoggers(); // This causes all Loggers to refetch - // information from their LoggerConfig. - System.out.println("Loading database..."); - try (DataProvider provider = new DataProvider()) { - User user = new User(); - user.setName("asd"); - user.setEmail("test@test.com"); - User user2 = new User(); - user2.setName("Teszt"); - user2.setEmail("test2@test.com"); - user2.getContacts().add(user); - provider.addUser(user); - List users = provider.getUsers(); - user = users.get(0); - user.getContacts().add(user2); - provider.addUser(user2); - users = provider.getUsers(); - user2 = users.get(1); - System.out.println(users); - System.out.println("1st's contact: " + user.getContacts().get(0)); - System.out.println("2nd's contact: " + user2.getContacts().get(0)); - Conversation convo = new Conversation(); - convo.getUsers().add(user); - convo.getUsers().add(user2); - Message msg = new Message(); - msg.setSender(user); - msg.setTime(new Date()); - msg.setMessage("Teszt 1"); - convo.getMesssages().add(msg); - Message msg2 = new Message(); - msg2.setSender(user2); - msg2.setTime(new Date()); - msg2.setMessage("Teszt 2"); - convo.getMesssages().add(msg2); - provider.addConversation(convo); - } - System.out.println("Starting webserver..."); - HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 10); - Reflections rf = new Reflections( - new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(Page.class.getClassLoader())) - .addClassLoader(Page.class.getClassLoader()).addScanners(new SubTypesScanner()) - .filterInputsBy((String pkg) -> pkg.contains("io.github.norbipeti.chat.server.page"))); - Set> pages = rf.getSubTypesOf(Page.class); - for (Class page : pages) { - try { - if (Modifier.isAbstract(page.getModifiers())) - continue; - Page p = page.newInstance(); - addPage(server, p); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - server.start(); - System.out.println("Ready... Press Enter to stop."); - System.in.read(); - System.out.println("Stopping..."); - server.stop(1); - } catch (Exception e) { - e.printStackTrace(); - } - System.out.println("Stopped"); - } - - private static void addPage(HttpServer server, Page page) { - server.createContext("/" + page.GetName(), page); - } +package io.github.norbipeti.chat.server; + +import java.lang.reflect.Modifier; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.reflections.Reflections; +import org.reflections.scanners.SubTypesScanner; +import org.reflections.util.ClasspathHelper; +import org.reflections.util.ConfigurationBuilder; + +import com.sun.net.httpserver.HttpServer; +import io.github.norbipeti.chat.server.db.*; +import io.github.norbipeti.chat.server.db.domain.*; +import io.github.norbipeti.chat.server.page.*; + +public class Main { + // public static final HashMap Pages = new HashMap(); + + public static void main(String[] args) { // http://stackoverflow.com/questions/9266632/access-restriction-is-not-accessible-due-to-restriction-on-required-library/10642163#10642163 + try { // rt.jar Javadoc: + // https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/ + // https://docs.oracle.com/javase/8/docs/api/ + System.out.println(System.getProperty("java.class.path")); // TODO: + // log4j + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); + loggerConfig.setLevel(Level.WARN); + ctx.updateLoggers(); // This causes all Loggers to refetch + // information from their LoggerConfig. + System.out.println("Loading database..."); + try (DataProvider provider = new DataProvider()) { + User user = new User(); + user.setName("asd"); + user.setEmail("test@test.com"); + User user2 = new User(); + user2.setName("Teszt"); + user2.setEmail("test2@test.com"); + user2.getContacts().add(user); + provider.addUser(user); + List users = provider.getUsers(); + user = users.get(0); + user.getContacts().add(user2); + provider.addUser(user2); + users = provider.getUsers(); + user2 = users.get(1); + System.out.println(users); + System.out.println("1st's contact: " + user.getContacts().get(0)); + System.out.println("2nd's contact: " + user2.getContacts().get(0)); + Conversation convo = new Conversation(); + convo.getUsers().add(user); + convo.getUsers().add(user2); + Message msg = new Message(); + msg.setSender(user); + msg.setTime(new Date()); + msg.setMessage("Teszt 1"); + convo.getMesssages().add(msg); + Message msg2 = new Message(); + msg2.setSender(user2); + msg2.setTime(new Date()); + msg2.setMessage("Teszt 2"); + convo.getMesssages().add(msg2); + provider.addConversation(convo); + } + System.out.println("Starting webserver..."); + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 10); + Reflections rf = new Reflections( + new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(Page.class.getClassLoader())) + .addClassLoader(Page.class.getClassLoader()).addScanners(new SubTypesScanner()) + .filterInputsBy((String pkg) -> pkg.contains("io.github.norbipeti.chat.server.page"))); + Set> pages = rf.getSubTypesOf(Page.class); + for (Class page : pages) { + try { + if (Modifier.isAbstract(page.getModifiers())) + continue; + Page p = page.newInstance(); + addPage(server, p); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + server.start(); + System.out.println("Ready... Press Enter to stop."); + System.in.read(); + System.out.println("Stopping..."); + server.stop(1); + } catch (Exception e) { + e.printStackTrace(); + } + System.out.println("Stopped"); + } + + private static void addPage(HttpServer server, Page page) { + server.createContext("/" + page.GetName(), page); + } } \ No newline at end of file diff --git a/src/io/github/norbipeti/chat/server/db/DataProvider.java b/src/io/github/norbipeti/chat/server/db/DataProvider.java index 4a95175..f4a3ffb 100644 --- a/src/io/github/norbipeti/chat/server/db/DataProvider.java +++ b/src/io/github/norbipeti/chat/server/db/DataProvider.java @@ -1,87 +1,87 @@ -package io.github.norbipeti.chat.server.db; - -import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.TypedQuery; - -import io.github.norbipeti.chat.server.db.domain.*; - -public class DataProvider implements AutoCloseable { - private EntityManagerFactory emf; - - public DataProvider() { - emf = Persistence.createEntityManagerFactory("ChatServerPU"); - } - - public void addUser(User user) { - save(user); - } - - public void addConversation(Conversation convo) { - save(convo); - } - - private void save(Object object) { - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - em.persist(object); - em.getTransaction().commit(); - em.close(); - } - - public List getUsers() { - return get(User.class); - } - - public List getMessages() { - return get(Message.class); - } - - public List getConversations() { - return get(Conversation.class); - } - - private List get(Class cl) { - EntityManager em = emf.createEntityManager(); - TypedQuery query = em.createQuery("SELECT x FROM " + cl.getSimpleName() + " x", cl); - List results = query.getResultList(); - em.close(); - return results; - } - - public void removeUser(User user) { - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - User managedUser = em.find(User.class, user.getId()); - em.remove(managedUser); - em.getTransaction().commit(); - em.close(); - } - - public User getUser(Long id) { - return get(User.class, id); - } - - private T get(Class cl, Long id) { - EntityManager em = emf.createEntityManager(); - T result = em.find(cl, id); - em.close(); - return result; - } - - public void SetValues(Runnable action) { - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - action.run(); - em.getTransaction().commit(); - em.close(); - } - - @Override - public void close() { - if (emf != null) - emf.close(); - } -} +package io.github.norbipeti.chat.server.db; + +import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.TypedQuery; + +import io.github.norbipeti.chat.server.db.domain.*; + +public class DataProvider implements AutoCloseable { + private EntityManagerFactory emf; + + public DataProvider() { + emf = Persistence.createEntityManagerFactory("ChatServerPU"); + } + + public void addUser(User user) { + save(user); + } + + public void addConversation(Conversation convo) { + save(convo); + } + + private void save(Object object) { + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + em.persist(object); + em.getTransaction().commit(); + em.close(); + } + + public List getUsers() { + return get(User.class); + } + + public List getMessages() { + return get(Message.class); + } + + public List getConversations() { + return get(Conversation.class); + } + + private List get(Class cl) { + EntityManager em = emf.createEntityManager(); + TypedQuery query = em.createQuery("SELECT x FROM " + cl.getSimpleName() + " x", cl); + List results = query.getResultList(); + em.close(); + return results; + } + + public void removeUser(User user) { + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + User managedUser = em.find(User.class, user.getId()); + em.remove(managedUser); + em.getTransaction().commit(); + em.close(); + } + + public User getUser(Long id) { + return get(User.class, id); + } + + private T get(Class cl, Long id) { + EntityManager em = emf.createEntityManager(); + T result = em.find(cl, id); + em.close(); + return result; + } + + public void SetValues(Runnable action) { + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + action.run(); + em.getTransaction().commit(); + em.close(); + } + + @Override + public void close() { + if (emf != null) + emf.close(); + } +} diff --git a/src/io/github/norbipeti/chat/server/db/domain/Conversation.java b/src/io/github/norbipeti/chat/server/db/domain/Conversation.java index c2f296a..77a519e 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Conversation.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Conversation.java @@ -1,51 +1,51 @@ -package io.github.norbipeti.chat.server.db.domain; - -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.*; - -@Entity -public class Conversation { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", unique = true, nullable = false) - private Long id; - @ElementCollection(fetch=FetchType.EAGER) - @OneToMany(cascade = CascadeType.ALL) - private List messsages; - @ElementCollection(fetch = FetchType.EAGER) - @ManyToMany(cascade = CascadeType.ALL) - private List users; - @Version - @GeneratedValue - private int Version; - - public List getMesssages() { - if (messsages == null) - messsages = new ArrayList<>(); - return messsages; - } - - public void setMesssages(List messsages) { - this.messsages = messsages; - } - - public List getUsers() { - if (users == null) - users = new ArrayList<>(); - return users; - } - - public void setUsers(List users) { - this.users = users; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } -} +package io.github.norbipeti.chat.server.db.domain; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.*; + +@Entity +public class Conversation { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @ElementCollection(fetch=FetchType.EAGER) + @OneToMany(cascade = CascadeType.ALL) + private List messsages; + @ElementCollection(fetch = FetchType.EAGER) + @ManyToMany(cascade = CascadeType.ALL) + private List users; + @Version + @GeneratedValue + private int Version; + + public List getMesssages() { + if (messsages == null) + messsages = new ArrayList<>(); + return messsages; + } + + public void setMesssages(List messsages) { + this.messsages = messsages; + } + + public List getUsers() { + if (users == null) + users = new ArrayList<>(); + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } +} diff --git a/src/io/github/norbipeti/chat/server/db/domain/Message.java b/src/io/github/norbipeti/chat/server/db/domain/Message.java index 889b01a..45ff93f 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/Message.java +++ b/src/io/github/norbipeti/chat/server/db/domain/Message.java @@ -1,62 +1,62 @@ -package io.github.norbipeti.chat.server.db.domain; - -import java.util.Date; - -import javax.persistence.*; - -@Entity -public class Message { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", unique = true, nullable = false) - private Long id; - @ManyToOne(cascade=CascadeType.ALL) - private User sender; - private Date time; - private String message; - @ManyToOne(cascade=CascadeType.ALL) - private Conversation conversation; - @Version - @GeneratedValue - private int Version; - - public User getSender() { - return sender; - } - - public void setSender(User sender) { - this.sender = sender; - } - - public Date getTime() { - return time; - } - - public void setTime(Date time) { - this.time = time; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Conversation getConversation() { - return conversation; - } - - public void setConversation(Conversation conversation) { - this.conversation = conversation; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } -} +package io.github.norbipeti.chat.server.db.domain; + +import java.util.Date; + +import javax.persistence.*; + +@Entity +public class Message { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + @ManyToOne(cascade=CascadeType.ALL) + private User sender; + private Date time; + private String message; + @ManyToOne(cascade=CascadeType.ALL) + private Conversation conversation; + @Version + @GeneratedValue + private int Version; + + public User getSender() { + return sender; + } + + public void setSender(User sender) { + this.sender = sender; + } + + public Date getTime() { + return time; + } + + public void setTime(Date time) { + this.time = time; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Conversation getConversation() { + return conversation; + } + + public void setConversation(Conversation conversation) { + this.conversation = conversation; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } +} diff --git a/src/io/github/norbipeti/chat/server/db/domain/User.java b/src/io/github/norbipeti/chat/server/db/domain/User.java index f11b3bf..821412e 100644 --- a/src/io/github/norbipeti/chat/server/db/domain/User.java +++ b/src/io/github/norbipeti/chat/server/db/domain/User.java @@ -1,115 +1,115 @@ -package io.github.norbipeti.chat.server.db.domain; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import javax.persistence.*; - -@Entity -@Table(name = "\"User\"") -public class User { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", unique = true, nullable = false) - private Long id; - private String name; - private String email; - private String password; - @ElementCollection(fetch = FetchType.EAGER) - private List contacts; - private String salt; - @Column(columnDefinition = "CHAR(16) FOR BIT DATA") - private UUID sessionid; - @Version - @GeneratedValue - private int Version; - @ElementCollection(fetch = FetchType.EAGER) - @ManyToMany(cascade = CascadeType.ALL) - public List conversations; - - public List getContacts() { - if (contacts == null) - contacts = new ArrayList<>(); - return contacts; - } - - public void setContacts(List contacts) { - this.contacts = contacts; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - @Override - public String toString() { - List c = null; - if (contacts != null) { - c = new ArrayList<>(); - for (User u : contacts) - c.add(u.name); - } - return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + ", contacts=" + c - + ", sessionid=" + sessionid + "]"; // TODO: SessionID null - // after getting from db - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String getSalt() { - return salt; - } - - public void setSalt(String salt) { - this.salt = salt; - } - - public UUID getSessionid() { - return sessionid; - } - - public void setSessionid(UUID sessionid) { - this.sessionid = sessionid; - } - - public List getConversations() { - if (conversations == null) - conversations = new ArrayList<>(); - return conversations; - } - - public void setConversations(List conversations) { - this.conversations = conversations; - } - - public User() { - - } -} +package io.github.norbipeti.chat.server.db.domain; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import javax.persistence.*; + +@Entity +@Table(name = "\"User\"") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", unique = true, nullable = false) + private Long id; + private String name; + private String email; + private String password; + @ElementCollection(fetch = FetchType.EAGER) + private List contacts; + private String salt; + @Column(columnDefinition = "CHAR(16) FOR BIT DATA") + private UUID sessionid; + @Version + @GeneratedValue + private int Version; + @ElementCollection(fetch = FetchType.EAGER) + @ManyToMany(cascade = CascadeType.ALL) + public List conversations; + + public List getContacts() { + if (contacts == null) + contacts = new ArrayList<>(); + return contacts; + } + + public void setContacts(List contacts) { + this.contacts = contacts; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + @Override + public String toString() { + List c = null; + if (contacts != null) { + c = new ArrayList<>(); + for (User u : contacts) + c.add(u.name); + } + return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + ", contacts=" + c + + ", sessionid=" + sessionid + "]"; // TODO: SessionID null + // after getting from db + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSalt() { + return salt; + } + + public void setSalt(String salt) { + this.salt = salt; + } + + public UUID getSessionid() { + return sessionid; + } + + public void setSessionid(UUID sessionid) { + this.sessionid = sessionid; + } + + public List getConversations() { + if (conversations == null) + conversations = new ArrayList<>(); + return conversations; + } + + public void setConversations(List conversations) { + this.conversations = conversations; + } + + public User() { + + } +} diff --git a/src/io/github/norbipeti/chat/server/page/IndexPage.java b/src/io/github/norbipeti/chat/server/page/IndexPage.java index 35d3dea..90f5605 100644 --- a/src/io/github/norbipeti/chat/server/page/IndexPage.java +++ b/src/io/github/norbipeti/chat/server/page/IndexPage.java @@ -1,60 +1,60 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; - -import org.jsoup.nodes.Element; - -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.ssl.internal.ssl.Provider; - -import io.github.norbipeti.chat.server.IOHelper; -import io.github.norbipeti.chat.server.db.DataProvider; -import io.github.norbipeti.chat.server.db.domain.Conversation; -import io.github.norbipeti.chat.server.db.domain.Message; -import io.github.norbipeti.chat.server.db.domain.User; - -public class IndexPage extends Page { - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - // final User user = IOHelper.GetLoggedInUser(exchange); - TODO - final User user = new User(); - user.setEmail("test@test.com"); - user.setName("Norbi"); - user.setId(3L); - if (user == null) - IOHelper.SendModifiedPage(200, this, (doc) -> { - doc.getElementById("userbox").remove(); - doc.getElementById("usercontent").remove(); - return doc; - }, exchange); - else - IOHelper.SendModifiedPage(200, this, (doc) -> { - doc.getElementById("loginbox").remove(); - doc.getElementById("registerbox").remove(); - Element userbox = doc.getElementById("userbox"); - userbox.html(userbox.html().replace("", user.getName())); - Element channelmessages = doc.getElementById("channelmessages"); - try (DataProvider provider = new DataProvider()) { - Conversation convo = provider.getConversations().get(0); //TODO - for (Message message : convo.getMesssages()) { - Element msgelement = channelmessages.appendElement("div"); - Element header = msgelement.appendElement("p"); - header.text(message.getSender().getName() + " - " + message.getTime()); - Element body = msgelement.appendElement("p"); - body.text(message.getMessage()); - } - } - return doc; - }, exchange); - } // TODO: - // Validation - // at - // registration - - @Override - public String GetName() { - return ""; - } - -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; + +import org.jsoup.nodes.Element; + +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.ssl.internal.ssl.Provider; + +import io.github.norbipeti.chat.server.IOHelper; +import io.github.norbipeti.chat.server.db.DataProvider; +import io.github.norbipeti.chat.server.db.domain.Conversation; +import io.github.norbipeti.chat.server.db.domain.Message; +import io.github.norbipeti.chat.server.db.domain.User; + +public class IndexPage extends Page { + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + // final User user = IOHelper.GetLoggedInUser(exchange); - TODO + final User user = new User(); + user.setEmail("test@test.com"); + user.setName("Norbi"); + user.setId(3L); + if (user == null) + IOHelper.SendModifiedPage(200, this, (doc) -> { + doc.getElementById("userbox").remove(); + doc.getElementById("usercontent").remove(); + return doc; + }, exchange); + else + IOHelper.SendModifiedPage(200, this, (doc) -> { + doc.getElementById("loginbox").remove(); + doc.getElementById("registerbox").remove(); + Element userbox = doc.getElementById("userbox"); + userbox.html(userbox.html().replace("", user.getName())); + Element channelmessages = doc.getElementById("channelmessages"); + try (DataProvider provider = new DataProvider()) { + Conversation convo = provider.getConversations().get(0); //TODO + for (Message message : convo.getMesssages()) { + Element msgelement = channelmessages.appendElement("div"); + Element header = msgelement.appendElement("p"); + header.text(message.getSender().getName() + " - " + message.getTime()); + Element body = msgelement.appendElement("p"); + body.text(message.getMessage()); + } + } + return doc; + }, exchange); + } // TODO: + // Validation + // at + // registration + + @Override + public String GetName() { + return ""; + } + +} diff --git a/src/io/github/norbipeti/chat/server/page/LoginPage.java b/src/io/github/norbipeti/chat/server/page/LoginPage.java index 3dc48f0..d4131c1 100644 --- a/src/io/github/norbipeti/chat/server/page/LoginPage.java +++ b/src/io/github/norbipeti/chat/server/page/LoginPage.java @@ -1,49 +1,49 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; -import org.json.JSONObject; -import org.mindrot.jbcrypt.BCrypt; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.IOHelper; -import io.github.norbipeti.chat.server.db.DataProvider; -import io.github.norbipeti.chat.server.db.domain.User; - -public class LoginPage extends Page { - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - JSONObject post = IOHelper.GetPOSTJSON(exchange); - if (post == null || !post.has("email") || !post.has("pass")) { - IOHelper.Redirect("/", exchange); - return; - } - try (DataProvider provider = new DataProvider()) { - User loginuser = null; - for (User user : provider.getUsers()) { - if (user.getEmail().equals(post.get("email"))) { - loginuser = user; - break; - } - } - if (loginuser == null || !BCrypt.checkpw(post.getString("pass"), loginuser.getPassword())) { - IOHelper.SendResponse(200, (doc) -> { - doc.appendElement("p").text("The username or password is invalid."); - return doc; - }, exchange); - return; - } - IOHelper.LoginUser(exchange, loginuser, provider); - IOHelper.SendResponse(200, "Success", exchange); - } catch (Exception e) { - throw e; - } - } - - @Override - public String GetName() { - return "login"; - } - -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; +import org.json.JSONObject; +import org.mindrot.jbcrypt.BCrypt; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.IOHelper; +import io.github.norbipeti.chat.server.db.DataProvider; +import io.github.norbipeti.chat.server.db.domain.User; + +public class LoginPage extends Page { + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + JSONObject post = IOHelper.GetPOSTJSON(exchange); + if (post == null || !post.has("email") || !post.has("pass")) { + IOHelper.Redirect("/", exchange); + return; + } + try (DataProvider provider = new DataProvider()) { + User loginuser = null; + for (User user : provider.getUsers()) { + if (user.getEmail().equals(post.get("email"))) { + loginuser = user; + break; + } + } + if (loginuser == null || !BCrypt.checkpw(post.getString("pass"), loginuser.getPassword())) { + IOHelper.SendResponse(200, (doc) -> { + doc.appendElement("p").text("The username or password is invalid."); + return doc; + }, exchange); + return; + } + IOHelper.LoginUser(exchange, loginuser, provider); + IOHelper.SendResponse(200, "Success", exchange); + } catch (Exception e) { + throw e; + } + } + + @Override + public String GetName() { + return "login"; + } + +} diff --git a/src/io/github/norbipeti/chat/server/page/MessageAjaxPage.java b/src/io/github/norbipeti/chat/server/page/MessageAjaxPage.java index 06cb43c..8640182 100644 --- a/src/io/github/norbipeti/chat/server/page/MessageAjaxPage.java +++ b/src/io/github/norbipeti/chat/server/page/MessageAjaxPage.java @@ -1,20 +1,20 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; - -import com.sun.net.httpserver.HttpExchange; - -public class MessageAjaxPage extends Page { - - @Override - public String GetName() { - return "message"; - } - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - // TODO Auto-generated method stub - - } - -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; + +import com.sun.net.httpserver.HttpExchange; + +public class MessageAjaxPage extends Page { + + @Override + public String GetName() { + return "message"; + } + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + // TODO Auto-generated method stub + + } + +} diff --git a/src/io/github/norbipeti/chat/server/page/NotFoundPage.java b/src/io/github/norbipeti/chat/server/page/NotFoundPage.java index c33e979..409aced 100644 --- a/src/io/github/norbipeti/chat/server/page/NotFoundPage.java +++ b/src/io/github/norbipeti/chat/server/page/NotFoundPage.java @@ -1,28 +1,28 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.IOHelper; - -public class NotFoundPage extends Page { - - @Override - public String GetName() { - return "notfound"; - } - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - IOHelper.SendPage(404, this, exchange); - } - - public NotFoundPage() { - if (Instance != null) - throw new UnsupportedOperationException("There can only be one instance of a page."); - Instance = this; - } - - public static NotFoundPage Instance; -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.IOHelper; + +public class NotFoundPage extends Page { + + @Override + public String GetName() { + return "notfound"; + } + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + IOHelper.SendPage(404, this, exchange); + } + + public NotFoundPage() { + if (Instance != null) + throw new UnsupportedOperationException("There can only be one instance of a page."); + Instance = this; + } + + public static NotFoundPage Instance; +} diff --git a/src/io/github/norbipeti/chat/server/page/Page.java b/src/io/github/norbipeti/chat/server/page/Page.java index 5323da1..fd22539 100644 --- a/src/io/github/norbipeti/chat/server/page/Page.java +++ b/src/io/github/norbipeti/chat/server/page/Page.java @@ -1,55 +1,55 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; -import java.io.PrintStream; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.io.output.ByteArrayOutputStream; - -import com.sun.net.httpserver.*; - -import io.github.norbipeti.chat.server.IOHelper; -import io.github.norbipeti.chat.server.Main; - -/** - * Add to {@link Main}.Pages - * - */ -public abstract class Page implements HttpHandler { - public abstract String GetName(); - - public final String GetHTMLPath() { - if (GetName().length() == 0) - return "pages/index.html"; - return new StringBuilder("pages/").append(GetName()).append(".html").toString(); - } - - @Override - public void handle(HttpExchange exchange) { - try { - if (!getDo404() || exchange.getRequestURI().getPath().equals("/" + GetName())) - handlePage(exchange); - else { - IOHelper.SendPage(404, NotFoundPage.Instance, exchange); - } - } catch (Exception e) { - e.printStackTrace(); - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream str = new PrintStream(baos); - str.print("

500 Internal Server Error

");
-				e.printStackTrace(str);
-				str.print("
"); - IOHelper.SendResponse(500, baos.toString(StandardCharsets.ISO_8859_1), exchange); - } catch (Exception e1) { - e1.printStackTrace(); - } - } - } - - public abstract void handlePage(HttpExchange exchange) throws IOException; - - public boolean getDo404() { - return true; - } -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.output.ByteArrayOutputStream; + +import com.sun.net.httpserver.*; + +import io.github.norbipeti.chat.server.IOHelper; +import io.github.norbipeti.chat.server.Main; + +/** + * Add to {@link Main}.Pages + * + */ +public abstract class Page implements HttpHandler { + public abstract String GetName(); + + public final String GetHTMLPath() { + if (GetName().length() == 0) + return "pages/index.html"; + return new StringBuilder("pages/").append(GetName()).append(".html").toString(); + } + + @Override + public void handle(HttpExchange exchange) { + try { + if (!getDo404() || exchange.getRequestURI().getPath().equals("/" + GetName())) + handlePage(exchange); + else { + IOHelper.SendPage(404, NotFoundPage.Instance, exchange); + } + } catch (Exception e) { + e.printStackTrace(); + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream str = new PrintStream(baos); + str.print("

500 Internal Server Error

");
+				e.printStackTrace(str);
+				str.print("
"); + IOHelper.SendResponse(500, baos.toString(StandardCharsets.ISO_8859_1), exchange); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + } + + public abstract void handlePage(HttpExchange exchange) throws IOException; + + public boolean getDo404() { + return true; + } +} diff --git a/src/io/github/norbipeti/chat/server/page/RegisterPage.java b/src/io/github/norbipeti/chat/server/page/RegisterPage.java index c563e77..487ee8f 100644 --- a/src/io/github/norbipeti/chat/server/page/RegisterPage.java +++ b/src/io/github/norbipeti/chat/server/page/RegisterPage.java @@ -1,72 +1,72 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.IOException; -import org.json.JSONObject; -import org.mindrot.jbcrypt.BCrypt; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.IOHelper; -import io.github.norbipeti.chat.server.db.DataProvider; -import io.github.norbipeti.chat.server.db.domain.User; - -public class RegisterPage extends Page { - @Override - public void handlePage(HttpExchange exchange) throws IOException { - JSONObject post = IOHelper.GetPOSTJSON(exchange); - if (post != null) { - String errormsg = CheckValues(post, "name", "email", "pass", "pass2"); - if (errormsg.length() > 0) { - final String msg = errormsg; - IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); - return; // TODO: Use JavaScript too, for error checks - } - try (DataProvider provider = new DataProvider()) { - for (User user : provider.getUsers()) { - if (post.get("email").equals(user.getEmail())) { - errormsg += "

An user with this name already exists

"; - break; - } - } - if (!post.get("pass").equals(post.get("pass2"))) - errormsg += "

The passwords don't match

"; - if (errormsg.length() > 0) { - final String msg = errormsg; - IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); - return; - } - User user = new User(); - user.setName(post.getString("name")); - user.setEmail(post.getString("email")); - user.setSalt(BCrypt.gensalt()); // http://www.mindrot.org/projects/jBCrypt/ - user.setPassword(BCrypt.hashpw(post.getString("pass"), user.getSalt())); - provider.addUser(user); - User managedUser = provider.getUser(user.getId()); - IOHelper.LoginUser(exchange, managedUser, provider); - IOHelper.SendResponse(200, "Success", exchange); - } catch (Exception e) { - throw e; - } - return; - } - IOHelper.Redirect("/", exchange); - } - - private String CheckValues(JSONObject post, String... values) { - String errormsg = ""; - for (String value : values) - if (!CheckValue(post.getString(value))) - errormsg += "

" + value + " can't be empty

"; - return errormsg; - } - - private boolean CheckValue(String val) { - return val != null && val.length() > 0; - } - - @Override - public String GetName() { - return "register"; - } - -} +package io.github.norbipeti.chat.server.page; + +import java.io.IOException; +import org.json.JSONObject; +import org.mindrot.jbcrypt.BCrypt; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.IOHelper; +import io.github.norbipeti.chat.server.db.DataProvider; +import io.github.norbipeti.chat.server.db.domain.User; + +public class RegisterPage extends Page { + @Override + public void handlePage(HttpExchange exchange) throws IOException { + JSONObject post = IOHelper.GetPOSTJSON(exchange); + if (post != null) { + String errormsg = CheckValues(post, "name", "email", "pass", "pass2"); + if (errormsg.length() > 0) { + final String msg = errormsg; + IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); + return; // TODO: Use JavaScript too, for error checks + } + try (DataProvider provider = new DataProvider()) { + for (User user : provider.getUsers()) { + if (post.get("email").equals(user.getEmail())) { + errormsg += "

An user with this name already exists

"; + break; + } + } + if (!post.get("pass").equals(post.get("pass2"))) + errormsg += "

The passwords don't match

"; + if (errormsg.length() > 0) { + final String msg = errormsg; + IOHelper.SendResponse(200, (doc) -> doc.html(msg).ownerDocument(), exchange); + return; + } + User user = new User(); + user.setName(post.getString("name")); + user.setEmail(post.getString("email")); + user.setSalt(BCrypt.gensalt()); // http://www.mindrot.org/projects/jBCrypt/ + user.setPassword(BCrypt.hashpw(post.getString("pass"), user.getSalt())); + provider.addUser(user); + User managedUser = provider.getUser(user.getId()); + IOHelper.LoginUser(exchange, managedUser, provider); + IOHelper.SendResponse(200, "Success", exchange); + } catch (Exception e) { + throw e; + } + return; + } + IOHelper.Redirect("/", exchange); + } + + private String CheckValues(JSONObject post, String... values) { + String errormsg = ""; + for (String value : values) + if (!CheckValue(post.getString(value))) + errormsg += "

" + value + " can't be empty

"; + return errormsg; + } + + private boolean CheckValue(String val) { + return val != null && val.length() > 0; + } + + @Override + public String GetName() { + return "register"; + } + +} diff --git a/src/io/github/norbipeti/chat/server/page/ScriptsPage.java b/src/io/github/norbipeti/chat/server/page/ScriptsPage.java index 0eb8cdd..78fbf0a 100644 --- a/src/io/github/norbipeti/chat/server/page/ScriptsPage.java +++ b/src/io/github/norbipeti/chat/server/page/ScriptsPage.java @@ -1,34 +1,34 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.File; -import java.io.IOException; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.IOHelper; - -public class ScriptsPage extends Page { - - @Override - public boolean getDo404() { - return false; - } - - @Override - public String GetName() { - return "js/"; - } - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - if (exchange.getRequestURI().getPath().startsWith("/js/")) { - File jsfile = new File("pages", exchange.getRequestURI().getPath()); - if (!jsfile.exists()) - IOHelper.SendResponse(404, "

JavaScript file not found

", exchange); - else - IOHelper.SendResponse(200, IOHelper.ReadFile(jsfile), exchange); - } - else - System.out.println(exchange.getRequestURI().getPath()); - } -} +package io.github.norbipeti.chat.server.page; + +import java.io.File; +import java.io.IOException; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.IOHelper; + +public class ScriptsPage extends Page { + + @Override + public boolean getDo404() { + return false; + } + + @Override + public String GetName() { + return "js/"; + } + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + if (exchange.getRequestURI().getPath().startsWith("/js/")) { + File jsfile = new File("pages", exchange.getRequestURI().getPath()); + if (!jsfile.exists()) + IOHelper.SendResponse(404, "

JavaScript file not found

", exchange); + else + IOHelper.SendResponse(200, IOHelper.ReadFile(jsfile), exchange); + } + else + System.out.println(exchange.getRequestURI().getPath()); + } +} diff --git a/src/io/github/norbipeti/chat/server/page/StylePage.java b/src/io/github/norbipeti/chat/server/page/StylePage.java index 23bcdab..a4900c5 100644 --- a/src/io/github/norbipeti/chat/server/page/StylePage.java +++ b/src/io/github/norbipeti/chat/server/page/StylePage.java @@ -1,35 +1,35 @@ -package io.github.norbipeti.chat.server.page; - -import java.io.File; -import java.io.IOException; - -import com.sun.net.httpserver.HttpExchange; - -import io.github.norbipeti.chat.server.IOHelper; - -public class StylePage extends Page { - - @Override - public boolean getDo404() { - return false; - } - - @Override - public String GetName() { - return "css/"; - } - - @Override - public void handlePage(HttpExchange exchange) throws IOException { - if (exchange.getRequestURI().getPath().startsWith("/css/")) { - File cssfile = new File("pages", exchange.getRequestURI().getPath()); - if (!cssfile.exists()) - IOHelper.SendResponse(404, "

CSS file not found

", exchange); - else { - exchange.getResponseHeaders().add("Content-Type", "text/css"); - IOHelper.SendResponse(200, IOHelper.ReadFile(cssfile), exchange); - } - } else - System.out.println(exchange.getRequestURI().getPath()); - } -} +package io.github.norbipeti.chat.server.page; + +import java.io.File; +import java.io.IOException; + +import com.sun.net.httpserver.HttpExchange; + +import io.github.norbipeti.chat.server.IOHelper; + +public class StylePage extends Page { + + @Override + public boolean getDo404() { + return false; + } + + @Override + public String GetName() { + return "css/"; + } + + @Override + public void handlePage(HttpExchange exchange) throws IOException { + if (exchange.getRequestURI().getPath().startsWith("/css/")) { + File cssfile = new File("pages", exchange.getRequestURI().getPath()); + if (!cssfile.exists()) + IOHelper.SendResponse(404, "

CSS file not found

", exchange); + else { + exchange.getResponseHeaders().add("Content-Type", "text/css"); + IOHelper.SendResponse(200, IOHelper.ReadFile(cssfile), exchange); + } + } else + System.out.println(exchange.getRequestURI().getPath()); + } +}