use of io.undertow.util.HttpString in project light-session-4j by networknt.
the class RedisSessionSingleIT method getTestHandler.
static RoutingHandler getTestHandler() {
return Handlers.routing().add(Methods.GET, "/get", exchange -> {
SessionManager sessionManager = SingletonServiceFactory.getBean(SessionManager.class);
Session session = sessionManager.getSession(exchange);
if (session == null) {
session = sessionManager.createSession(exchange);
session.setAttribute(COUNT, 0);
logger.debug("first time access create a session and count is 0 sessionId = " + session.getId());
}
Integer count = (Integer) session.getAttribute(COUNT);
logger.debug("not the first time, get count from session = " + count + " sessionId = " + session.getId());
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
});
}
use of io.undertow.util.HttpString in project light-session-4j by networknt.
the class MapSessionManagerTest method getTestHandler.
static RoutingHandler getTestHandler() {
return Handlers.routing().add(Methods.GET, "/get", exchange -> {
SessionManager sessionManager = SingletonServiceFactory.getBean(SessionManager.class);
Session session = sessionManager.getSession(exchange);
if (session == null) {
session = sessionManager.createSession(exchange);
session.setAttribute(COUNT, 0);
logger.debug("first time access create a session and count is 0 sessionId = " + session.getId());
}
Integer count = (Integer) session.getAttribute(COUNT);
logger.debug("not the first time, get count from session = " + count + " sessionId = " + session.getId());
exchange.getResponseHeaders().add(new HttpString(COUNT), count.toString());
session.setAttribute(COUNT, ++count);
});
}
use of io.undertow.util.HttpString in project light-4j by networknt.
the class Handler method addPathChain.
/**
* Add a PathChain (having a non-null path) to the handler data structures.
*/
private static void addPathChain(PathChain pathChain) {
HttpString method = new HttpString(pathChain.getMethod());
// Use a random integer as the id for a given path.
Integer randInt = new Random().nextInt();
while (handlerListById.containsKey(randInt.toString())) {
randInt = new Random().nextInt();
}
// Flatten out the execution list from a mix of middleware chains and handlers.
List<HttpHandler> handlers = getHandlersFromExecList(pathChain.getExec());
if (handlers.size() > 0) {
// If a matcher already exists for the given type, at to that instead of
// creating a new one.
PathTemplateMatcher<String> pathTemplateMatcher = methodToMatcherMap.containsKey(method) ? methodToMatcherMap.get(method) : new PathTemplateMatcher<>();
if (pathTemplateMatcher.get(pathChain.getPath()) == null) {
pathTemplateMatcher.add(pathChain.getPath(), randInt.toString());
}
methodToMatcherMap.put(method, pathTemplateMatcher);
handlerListById.put(randInt.toString(), handlers);
}
}
use of io.undertow.util.HttpString in project light-codegen by networknt.
the class CodegenMultipleHandler method handle.
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
// generate a destination folder name.
String output = HashUtil.generateUUID();
String zipFile = output + ".zip";
String projectFolder = codegenWebConfig.getTmpFolder() + separator + output;
List<Map<String, Object>> generators = (List<Map<String, Object>>) ((Map<String, Object>) input).get("generators");
if (generators == null || generators.size() == 0) {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_MISSING_GENERATOR_ITEM));
}
try {
for (Map<String, Object> generatorMap : generators) {
String framework = (String) generatorMap.get("framework");
if (!FrameworkRegistry.getInstance().getFrameworks().contains(framework)) {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_FRAMEWORK, framework));
}
String modelType = (String) generatorMap.get("modelType");
// the model can be JsonNode or String depending on the framework
Object model = null;
if ("C".equals(modelType)) {
String modelText = (String) generatorMap.get("modelText");
if (GraphqlGenerator.FRAMEWORK.equals(framework)) {
model = modelText;
} else {
// json or yaml?
if (modelText.startsWith("{") || modelText.startsWith("[")) {
// This is a json string.
model = Generator.jsonMapper.readTree(modelText);
} else {
// This is a yaml string
model = Generator.yamlMapper.readTree(modelText);
}
}
} else if ("U".equals(modelType)) {
String modelUrl = (String) generatorMap.get("modelUrl");
// make sure it is a valid URL.
if (Utils.isUrl(modelUrl)) {
// if it is a json file.
if (modelUrl.endsWith(".json")) {
model = Generator.jsonMapper.readTree((Utils.urlToByteArray(new URL(modelUrl))));
} else if (modelUrl.endsWith(".yml") || modelUrl.endsWith(".yaml")) {
model = Generator.yamlMapper.readTree(Utils.urlToByteArray(new URL(modelUrl)));
} else {
model = new String(Utils.urlToByteArray(new URL(modelUrl)), StandardCharsets.UTF_8);
}
} else {
// return an error here for invalid model URL.
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_MODEL_URL, modelUrl));
}
}
String configType = (String) generatorMap.get("configType");
JsonNode config = null;
if ("C".equals(configType)) {
String configText = (String) generatorMap.get("configText");
configText = configText.trim();
// the config must be json.
if (configText.startsWith("{") || configText.startsWith("[")) {
config = Generator.jsonMapper.readTree(configText);
} else {
config = Generator.yamlMapper.readTree(configText);
}
} else if ("U".equals(configType)) {
String configUrl = (String) generatorMap.get("configUrl");
configUrl = configUrl.trim();
if (configUrl.endsWith(".json")) {
config = Generator.jsonMapper.readTree(Utils.urlToByteArray(new URL(configUrl)));
} else if (configUrl.endsWith(".yml") || configUrl.endsWith(".yaml")) {
config = Generator.yamlMapper.readTree(Utils.urlToByteArray(new URL(configUrl)));
} else {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_CONFIG_URL_EXTENSION, configUrl));
}
}
Generator generator = FrameworkRegistry.getInstance().getGenerator(framework);
generator.generate(projectFolder, model, config);
}
} catch (Exception e) {
logger.error("Exception:", e);
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_GENERATOR_EXCEPTION, e.getMessage()));
}
try {
// TODO generated code is in tmp folder, zip and move to the target folder
NioUtils.create(codegenWebConfig.getZipFolder() + separator + zipFile, projectFolder);
// delete the project folder.
Files.walk(Paths.get(projectFolder), FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile).peek(System.out::println).forEach(File::delete);
// check if any zip file that needs to be deleted from zipFolder
NioUtils.deleteOldFiles(codegenWebConfig.getZipFolder(), codegenWebConfig.getZipKeptMinute());
} catch (Exception e) {
logger.error("Exception:", e);
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_COMPRESSION_EXCEPTION, e.getMessage()));
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/zip").add(new HttpString("Content-Disposition"), "attachment");
// return the zip file
File file = new File(codegenWebConfig.getZipFolder() + separator + zipFile);
return NioUtils.toByteBuffer(file);
}
use of io.undertow.util.HttpString in project light-codegen by networknt.
the class CodegenSingleHandler method handle.
@Override
public ByteBuffer handle(HttpServerExchange exchange, Object input) {
// generate a destination folder name.
String output = HashUtil.generateUUID();
String zipFile = output + ".zip";
String projectFolder = codegenWebConfig.getTmpFolder() + separator + output;
Map<String, Object> generatorMap = (Map<String, Object>) input;
if (logger.isDebugEnabled())
logger.debug("dataMap = " + JsonMapper.toJson(generatorMap));
if (generatorMap == null) {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_MISSING_GENERATOR_ITEM));
}
String framework = (String) generatorMap.get("framework");
if (!FrameworkRegistry.getInstance().getFrameworks().contains(framework)) {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_FRAMEWORK, framework));
}
try {
String modelType = (String) generatorMap.get("modelType");
// the model can be Any or String depending on the framework
Object model = null;
if ("C".equals(modelType)) {
String modelText = (String) generatorMap.get("modelText");
modelText = modelText.trim();
// based on the framework, we decide the format.
if (GraphqlGenerator.FRAMEWORK.equals(framework)) {
model = modelText;
} else {
// json or yaml?
if (modelText.startsWith("{") || modelText.startsWith("[")) {
// This is a json string.
model = Generator.jsonMapper.readTree(modelText);
} else {
// This is a yaml string
model = Generator.yamlMapper.readTree(modelText);
}
}
} else if ("U".equals(modelType)) {
String modelUrl = (String) generatorMap.get("modelUrl");
// make sure it is a valid URL.
if (Utils.isUrl(modelUrl)) {
// if it is a json file.
if (modelUrl.endsWith(".json")) {
model = Generator.jsonMapper.readTree(Utils.urlToByteArray(new URL(modelUrl)));
} else if (modelUrl.endsWith(".yml") || modelUrl.endsWith(".yaml")) {
model = Generator.yamlMapper.readTree(Utils.urlToByteArray(new URL(modelUrl)));
} else {
model = new String(Utils.urlToByteArray(new URL(modelUrl)), StandardCharsets.UTF_8);
}
} else {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_MODEL_URL, modelUrl));
}
}
String configType = (String) generatorMap.get("configType");
JsonNode config = null;
if ("C".equals(configType)) {
String configText = (String) generatorMap.get("configText");
configText = configText.trim();
// the config must be json.
if (configText.startsWith("{") || configText.startsWith("[")) {
config = Generator.jsonMapper.readTree(configText);
} else {
config = Generator.yamlMapper.readTree(configText);
}
} else if ("U".equals(configType)) {
String configUrl = (String) generatorMap.get("configUrl");
configUrl = configUrl.trim();
// make sure that the file extension is .json
if (configUrl.endsWith(".json")) {
config = Generator.jsonMapper.readTree(Utils.urlToByteArray(new URL(configUrl)));
} else if (configUrl.endsWith(".yml") || configUrl.endsWith(".yaml")) {
config = Generator.yamlMapper.readTree(Utils.urlToByteArray(new URL(configUrl)));
} else {
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_INVALID_CONFIG_URL_EXTENSION, configUrl));
}
}
Generator generator = FrameworkRegistry.getInstance().getGenerator(framework);
generator.generate(projectFolder, model, config);
} catch (Exception e) {
logger.error("Exception:", e);
// return an error status to the user.
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_GENERATOR_EXCEPTION, e.getMessage()));
}
try {
NioUtils.create(codegenWebConfig.getZipFolder() + separator + zipFile, projectFolder);
// delete the project folder.
Files.walk(Paths.get(projectFolder), FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile).peek(System.out::println).forEach(File::delete);
// check if any zip file that needs to be deleted from zipFolder
NioUtils.deleteOldFiles(codegenWebConfig.getZipFolder(), codegenWebConfig.getZipKeptMinute());
} catch (Exception e) {
logger.error("Exception:", e);
return NioUtils.toByteBuffer(getStatus(exchange, STATUS_COMPRESSION_EXCEPTION, e.getMessage()));
}
exchange.getResponseHeaders().add(new HttpString("Content-Type"), "application/zip").add(new HttpString("Content-Disposition"), "attachment");
// return the zip file
File file = new File(codegenWebConfig.getZipFolder() + separator + zipFile);
return NioUtils.toByteBuffer(file);
}
Aggregations