Browse Source

trying to allow both standalone use and intergration in tomcat

Signed-off-by: Stephan Richter <s.richter@srsoftware.de>
sqlite
Stephan Richter 4 months ago
parent
commit
74e458fa65
  1. 5
      build.gradle
  2. 269
      config/clang-format
  3. 4
      config/formatting.xml
  4. 3
      de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/User.java
  5. 2
      de.srsoftware.oidc.light/build.gradle
  6. 28
      de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/Constants.java
  7. 61
      de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/LightOICD.java
  8. 15
      de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/Templates.java
  9. 32
      de.srsoftware.oidc.server/build.gradle
  10. 22
      de.srsoftware.oidc.server/src/main/java/de/srsoftware/oidc/server/Application.java

5
build.gradle

@ -1,7 +1,6 @@ @@ -1,7 +1,6 @@
plugins {
id 'java'
id "com.diffplug.spotless" version "6.25.0"
}
group = 'de.srsoftware'
@ -25,9 +24,9 @@ spotless { @@ -25,9 +24,9 @@ spotless {
target '*/src/*/java/**/*.java'
removeUnusedImports()
importOrder()
eclipse('4.26').configFile('config/formatting.xml')
clangFormat('18.1.8').style('file:config/clang-format')
licenseHeader '/* © SRSoftware $YEAR */' // or licenseHeaderFile
}
}
compileJava.dependsOn 'spotlessApply'
compileJava.dependsOn 'spotlessApply'

269
config/clang-format

@ -0,0 +1,269 @@ @@ -0,0 +1,269 @@
---
Language: Java
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseColons: false
AlignEscapedNewlines: Left
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAfterAttributes: Never
BreakAfterJavaFieldAnnotations: false
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit: 999
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 16
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
KeepEmptyLinesAtEOF: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: NextLine
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
PPIndentWidth: -1
QualifierAlignment: Leave
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
- ParseTestProto
- ParsePartialTestProto
CanonicalDelimiter: pb
BasedOnStyle: google
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Auto
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 16
UseTab: Always
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
...

4
config/formatting.xml

@ -113,7 +113,7 @@ @@ -113,7 +113,7 @@
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/>
<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/>
<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/>
<setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.force_if_else_statement_brace" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="2"/>
@ -310,7 +310,7 @@ @@ -310,7 +310,7 @@
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="true"/>
<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/>
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="999"/>

3
de.srsoftware.oidc.api/src/main/java/de/srsoftware/oidc/api/User.java

@ -1,5 +1,4 @@ @@ -1,5 +1,4 @@
/* © SRSoftware 2024 */
package de.srsoftware.oidc.api;
public class User {
}
public class User {}

2
de.srsoftware.oidc.light/build.gradle

@ -11,7 +11,7 @@ repositories { @@ -11,7 +11,7 @@ repositories {
}
dependencies {
compileOnly 'javax.servlet:javax.servlet-api:4.0.1'
compileOnly 'jakarta.servlet:jakarta.servlet-api:6.1.0'
implementation 'ch.qos.logback:logback-core:1.5.6'
implementation 'ch.qos.logback:logback-classic:1.5.6'
implementation 'org.slf4j:slf4j-api:2.0.13'

28
de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/Constants.java

@ -2,19 +2,19 @@ @@ -2,19 +2,19 @@
package de.srsoftware.oidc.light;
public class Constants {
public static final String BODY = "body";
public static final String EMAIL = "email";
public static final String ERR_PAGE_NOT_FOUND = "page_not_found";
public static final String BODY = "body";
public static final String EMAIL = "email";
public static final String ERR_PAGE_NOT_FOUND = "page_not_found";
public static final String ERR_REDIRECT_FAILED = "redirect_failed";
public static final String HEAD = "head";
public static final String MESSAGES = "messages.txt";
public static final String PAGE_LOGIN = "login";
public static final String PAGE_START = "start";
public static final String PAGE_WELCOME = "welcome";
public static final String PASSWORD = "password";
public static final String TARGET = "target";
public static final String TITLE = "title";
public static final String TITLE_LOGIN = "title_login";
public static final String TITLE_WELCOME = "title_welcom";
public static final String USER = "user";
public static final String HEAD = "head";
public static final String MESSAGES = "messages.txt";
public static final String PAGE_LOGIN = "login";
public static final String PAGE_START = "start";
public static final String PAGE_WELCOME = "welcome";
public static final String PASSWORD = "password";
public static final String TARGET = "target";
public static final String TITLE = "title";
public static final String TITLE_LOGIN = "title_login";
public static final String TITLE_WELCOME = "title_welcom";
public static final String USER = "user";
}

61
de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/LightOICD.java

@ -5,22 +5,23 @@ import static de.srsoftware.oidc.light.Constants.*; @@ -5,22 +5,23 @@ import static de.srsoftware.oidc.light.Constants.*;
import static de.srsoftware.oidc.light.Templates.braced;
import de.srsoftware.oidc.api.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet(urlPatterns = "/")
@WebServlet("/web")
public class LightOICD extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(LightOICD.class);
private static final Logger LOG = LoggerFactory.getLogger(LightOICD.class);
private static final Templates templates;
static {
try {
templates = Templates.singleton();
@ -31,28 +32,28 @@ public class LightOICD extends HttpServlet { @@ -31,28 +32,28 @@ public class LightOICD extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
var uri = req.getRequestURI();
var path = Arrays.stream(uri.split("/")).skip(1).collect(Collectors.toList());
if (path.isEmpty()) {
path.add(PAGE_START);
}
var path = relativePath(req);
var optUser = loadUser(req);
handleGet(path, optUser, req, resp).ifPresent(resp.getWriter()::println);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
var uri = req.getRequestURI();
var path = Arrays.stream(uri.split("/")).skip(1).collect(Collectors.toList());
if (path.isEmpty()) {
path.add(PAGE_START);
}
var path = relativePath(req);
var optUser = loadUser(req);
handlePost(path, optUser, req, resp).ifPresent(resp.getWriter()::println);
}
public List<String> relativePath(HttpServletRequest req) {
var cp = req.getContextPath();
var uri = req.getRequestURI();
if (uri.startsWith(cp)) uri = uri.substring(cp.length()); // strip context path → relative path!
var path = Arrays.stream(uri.split("/")).skip(1).collect(Collectors.toList());
if (path.isEmpty()) path.add(PAGE_START);
return path;
}
private Optional<String> handleGet(List<String> path, Optional<User> optUser, HttpServletRequest req, HttpServletResponse resp) {
String token = path.remove(0);
if (optUser.isPresent()) {
@ -61,7 +62,7 @@ public class LightOICD extends HttpServlet { @@ -61,7 +62,7 @@ public class LightOICD extends HttpServlet {
case PAGE_START:
return pageStart(user, req, resp);
case PAGE_WELCOME:
return pageWelcome(user,req, resp);
return pageWelcome(user, req, resp);
}
}
@ -76,7 +77,6 @@ public class LightOICD extends HttpServlet { @@ -76,7 +77,6 @@ public class LightOICD extends HttpServlet {
}
private Optional<String> handlePost(List<String> path, Optional<User> optUser, HttpServletRequest req, HttpServletResponse resp) {
String token = path.remove(0);
if (optUser.isPresent()) {
@ -98,21 +98,18 @@ public class LightOICD extends HttpServlet { @@ -98,21 +98,18 @@ public class LightOICD extends HttpServlet {
private Optional<User> loadUser(HttpServletRequest req) {
HttpSession session = req.getSession();
if (session.getAttribute(USER) instanceof User user) {
return Optional.of(user);
}
if (session.getAttribute(USER) instanceof User user) return Optional.of(user);
return Optional.empty();
}
private Optional<String> pageLogin(HttpServletRequest req, HttpServletResponse resp) {
LOG.debug("pageLogin(…)");
try {
var title = templates.message(TITLE_LOGIN).orElse(TITLE_LOGIN);
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var login = templates.get("login.snippet", Map.of(USER, "Darling", EMAIL, "", PASSWORD, "")).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
resp.setContentType("text/html");
resp.getWriter().println(page);
return Optional.empty();
@ -130,9 +127,9 @@ public class LightOICD extends HttpServlet { @@ -130,9 +127,9 @@ public class LightOICD extends HttpServlet {
LOG.debug("pageWelcome(…)");
try {
var title = templates.message(TITLE_WELCOME).orElse(TITLE_WELCOME);
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var login = templates.get("welcome.snippet", Map.of(USER, "Darling", EMAIL, "", PASSWORD, "")).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
resp.setContentType("text/html");
resp.getWriter().println(page);
return Optional.empty();
@ -153,9 +150,9 @@ public class LightOICD extends HttpServlet { @@ -153,9 +150,9 @@ public class LightOICD extends HttpServlet {
}
try {
var title = templates.message(TITLE_LOGIN).orElse(TITLE_LOGIN);
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var head = templates.get("head.snippet", Map.of(TITLE, title)).get();
var login = templates.get("login.snippet", Map.of(USER, "Darling", EMAIL, email, PASSWORD, "")).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
var page = templates.get("scaffold.html", Map.of(BODY, login, HEAD, head)).get();
resp.setContentType("text/html");
resp.getWriter().println(page);
return Optional.empty();

15
de.srsoftware.oidc.light/src/main/java/de/srsoftware/oidc/light/Templates.java

@ -15,12 +15,13 @@ import org.slf4j.Logger; @@ -15,12 +15,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Templates {
private static Templates singleton = null;
private static Logger LOG = LoggerFactory.getLogger(Templates.class);
private Path dir = searchTemplates();
private Map<String, String> messages = null;
private static Templates singleton = null;
private static Logger LOG = LoggerFactory.getLogger(Templates.class);
private Path dir = searchTemplates();
private Map<String, String> messages = null;
public Templates() throws FileNotFoundException {}
public Templates() throws FileNotFoundException {
}
private static Path searchTemplates() throws FileNotFoundException {
return searchTemplates(new File(System.getProperty("user.dir"))).map(File::toPath).orElseThrow(() -> new FileNotFoundException("Missing template directory"));
@ -57,12 +58,10 @@ public class Templates { @@ -57,12 +58,10 @@ public class Templates {
LOG.warn("Failed to read {}", path, e);
return Optional.empty();
}
}
private String replaceKeys(String text, Map<String, String> replacements) {
for (Map.Entry<String, String> replacement : replacements.entrySet())
text = text.replace(braced(replacement.getKey()), replacement.getValue());
for (Map.Entry<String, String> replacement : replacements.entrySet()) text = text.replace(braced(replacement.getKey()), replacement.getValue());
return text;
}

32
de.srsoftware.oidc.server/build.gradle

@ -0,0 +1,32 @@ @@ -0,0 +1,32 @@
plugins {
id 'java'
}
group = 'de.srsoftware'
version = '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation 'org.eclipse.jetty:jetty-server:11.0.14'
implementation 'org.eclipse.jetty:jetty-webapp:11.0.22'
implementation project(':de.srsoftware.oidc.light')
}
test {
useJUnitPlatform()
}
jar {
manifest {
attributes "Main-Class": "de.srsoftware.oidc.server.Application"
}
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}

22
de.srsoftware.oidc.server/src/main/java/de/srsoftware/oidc/server/Application.java

@ -0,0 +1,22 @@ @@ -0,0 +1,22 @@
/* © SRSoftware 2024 */
package de.srsoftware.oidc.server;
import de.srsoftware.oidc.light.LightOICD;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
public class Application {
private static Server webserver;
public static void main(String[] args) throws Exception {
webserver = new Server(8080);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/web");
context.addServlet(LightOICD.class, "/");
webserver.setHandler(context);
webserver.start();
webserver.join();
}
}
Loading…
Cancel
Save