Skip to content

Commit

Permalink
fixes #158 make OpenApiHelper a singleton with an init method and loa…
Browse files Browse the repository at this point in the history
…d it in each handler
  • Loading branch information
stevehu committed Dec 18, 2020
1 parent 8a52cf0 commit 2065785
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 27 deletions.
5 changes: 5 additions & 0 deletions openapi-helper/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
<artifactId>config</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package com.networknt.openapi;

import com.networknt.config.Config;
import com.networknt.oas.OpenApiParser;
import com.networknt.oas.model.OpenApi3;
import com.networknt.oas.model.SecurityScheme;
Expand All @@ -41,27 +40,15 @@
* @author Steve Hu
*/
public class OpenApiHelper {

static final String OPENAPI_YML_CONFIG = "openapi.yml";
static final String OPENAPI_YAML_CONFIG = "openapi.yaml";
static final String OPENAPI_JSON_CONFIG = "openapi.json";

static final Logger logger = LoggerFactory.getLogger(OpenApiHelper.class);

public static OpenApi3 openApi3;
public static List<String> oauth2Names;
public static String basePath;
private static OpenApiHelper INSTANCE = null;

static {
private OpenApiHelper(String spec) {
try {
// first try to load the specification into a string regardless it is in YAML or JSON.
String spec = Config.getInstance().getStringFromFile(OPENAPI_YML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_YAML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_JSON_CONFIG);
}
}
openApi3 = (OpenApi3) new OpenApiParser().parse(spec, new URL("https://oas.lightapi.net/"));
} catch (MalformedURLException e) {
logger.error("MalformedURLException", e);
Expand All @@ -73,9 +60,25 @@ public class OpenApiHelper {
oauth2Names = getOAuth2Name();
basePath = getBasePath();
}

}

public static OpenApiHelper getInstance() {
if(INSTANCE == null) {
return null;
}
return INSTANCE;
}

public synchronized static OpenApiHelper init(String spec) {
if(INSTANCE != null) {
return INSTANCE;
}
INSTANCE = new OpenApiHelper(spec);
return INSTANCE;
}

public static Optional<NormalisedPath> findMatchingApiPath(final NormalisedPath requestPath) {
public Optional<NormalisedPath> findMatchingApiPath(final NormalisedPath requestPath) {
if(OpenApiHelper.openApi3 != null) {
return OpenApiHelper.openApi3.getPaths().keySet()
.stream()
Expand All @@ -87,7 +90,7 @@ public static Optional<NormalisedPath> findMatchingApiPath(final NormalisedPath
}
}

private static List<String> getOAuth2Name() {
private List<String> getOAuth2Name() {
List<String> names = new ArrayList<>();
Map<String, SecurityScheme> defMap = openApi3.getSecuritySchemes();
if(defMap != null) {
Expand All @@ -100,7 +103,7 @@ private static List<String> getOAuth2Name() {
return names;
}

private static String getBasePath() {
private String getBasePath() {

String basePath = "";
String url = null;
Expand All @@ -119,7 +122,7 @@ private static String getBasePath() {
return basePath;
}

private static boolean pathMatches(final NormalisedPath requestPath, final NormalisedPath apiPath) {
private boolean pathMatches(final NormalisedPath requestPath, final NormalisedPath apiPath) {
if (requestPath.parts().size() != apiPath.parts().size()) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.networknt.openapi;

import com.networknt.oas.OpenApiParser;
import com.networknt.config.Config;
import org.junit.Assert;
import org.junit.Test;

Expand All @@ -26,6 +26,8 @@
public class OpenApiHelperTest {
@Test
public void testOAuth2Name() {
String spec = Config.getInstance().getStringFromFile("openapi.yaml");
OpenApiHelper.init(spec);
Assert.assertEquals(1, OpenApiHelper.oauth2Names.size());
Assert.assertEquals("petstore_auth", OpenApiHelper.oauth2Names.get(0));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ public class OpenApiHandler implements MiddlewareHandler {
static final Logger logger = LoggerFactory.getLogger(OpenApiHandler.class);

public static final String CONFIG_NAME = "openapi";

static final String OPENAPI_YML_CONFIG = "openapi.yml";
static final String OPENAPI_YAML_CONFIG = "openapi.yaml";
static final String OPENAPI_JSON_CONFIG = "openapi.json";

public static final AttachmentKey<Map<String, Object>> DESERIALIZED_QUERY_PARAMETERS = AttachmentKey.create(Map.class);
public static final AttachmentKey<Map<String, Object>> DESERIALIZED_PATH_PARAMETERS = AttachmentKey.create(Map.class);
public static final AttachmentKey<Map<String, Object>> DESERIALIZED_HEADER_PARAMETERS = AttachmentKey.create(Map.class);
Expand All @@ -64,16 +67,22 @@ public class OpenApiHandler implements MiddlewareHandler {
static final String STATUS_METHOD_NOT_ALLOWED = "ERR10008";

private volatile HttpHandler next;

public OpenApiHandler() {

String spec = Config.getInstance().getStringFromFile(OPENAPI_YML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_YAML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_JSON_CONFIG);
}
}
OpenApiHelper.init(spec);
}


@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.getInstance().findMatchingApiPath(requestPath);
if (!maybeApiPath.isPresent()) {
setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import com.networknt.config.Config;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.networknt.handler.config.EndpointSource;
Expand All @@ -35,6 +37,10 @@ public class OpenApiEndpointSourceTest {
"/v1/pets/{petId}@get",
"/v1/pets/{petId}@delete"
));
static {
String spec = Config.getInstance().getStringFromFile("openapi.yaml");
OpenApiHelper.init(spec);
}

@Test
public void testFindBasePath() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
*/
public class JwtVerifyHandler implements MiddlewareHandler, IJwtVerifyHandler {
static final Logger logger = LoggerFactory.getLogger(JwtVerifyHandler.class);
static final String OPENAPI_YML_CONFIG = "openapi.yml";
static final String OPENAPI_YAML_CONFIG = "openapi.yaml";
static final String OPENAPI_JSON_CONFIG = "openapi.json";

static final String OPENAPI_SECURITY_CONFIG = "openapi-security";
static final String ENABLE_VERIFY_SCOPE = "enableVerifyScope";
Expand Down Expand Up @@ -81,7 +84,18 @@ public class JwtVerifyHandler implements MiddlewareHandler, IJwtVerifyHandler {

private volatile HttpHandler next;

public JwtVerifyHandler() {}
public JwtVerifyHandler() {
if(OpenApiHelper.getInstance() == null) {
String spec = Config.getInstance().getStringFromFile(OPENAPI_YML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_YAML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_JSON_CONFIG);
}
}
OpenApiHelper.init(spec);
}
}

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
Expand Down Expand Up @@ -115,7 +129,7 @@ public void handleRequest(final HttpServerExchange exchange) throws Exception {
OpenApiOperation openApiOperation = (OpenApiOperation)auditInfo.get(Constants.OPENAPI_OPERATION_STRING);
if(openApiOperation == null) {
final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.getInstance().findMatchingApiPath(requestPath);
if (!maybeApiPath.isPresent()) {
setExchangeStatus(exchange, STATUS_INVALID_REQUEST_PATH);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ private Object convertStrToObjTree(String s) {
private OpenApiOperation getOpenApiOperation(String uri, String httpMethod) throws URISyntaxException {
String uriWithoutQuery = new URI(uri).getPath();
NormalisedPath requestPath = new ApiNormalisedPath(uriWithoutQuery);
Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
Optional<NormalisedPath> maybeApiPath = OpenApiHelper.getInstance().findMatchingApiPath(requestPath);
if (!maybeApiPath.isPresent()) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
public class ValidatorHandler implements MiddlewareHandler {
public static final String OPENAPI_CONFIG_NAME = "openapi-validator";
public static final String CONFIG_NAME = "validator";
static final String OPENAPI_YML_CONFIG = "openapi.yml";
static final String OPENAPI_YAML_CONFIG = "openapi.yaml";
static final String OPENAPI_JSON_CONFIG = "openapi.json";

static final String STATUS_MISSING_OPENAPI_OPERATION = "ERR10012";

Expand All @@ -64,6 +67,16 @@ public class ValidatorHandler implements MiddlewareHandler {
ResponseValidator responseValidator;

public ValidatorHandler() {
if(OpenApiHelper.getInstance() == null) {
String spec = Config.getInstance().getStringFromFile(OPENAPI_YML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_YAML_CONFIG);
if(spec == null) {
spec = Config.getInstance().getStringFromFile(OPENAPI_JSON_CONFIG);
}
}
OpenApiHelper.init(spec);
}
final SchemaValidator schemaValidator = new SchemaValidator(OpenApiHelper.openApi3);
this.requestValidator = new RequestValidator(schemaValidator);
this.responseValidator = new ResponseValidator();
Expand Down

0 comments on commit 2065785

Please sign in to comment.