use of com.twinsoft.convertigo.beans.core.UrlMappingOperation in project convertigo by convertigo.
the class UrlMappingTreeObject method treeObjectAdded.
@Override
public void treeObjectAdded(TreeObjectEvent treeObjectEvent) {
super.treeObjectAdded(treeObjectEvent);
TreeObject treeObject = (TreeObject) treeObjectEvent.getSource();
if (treeObject instanceof DatabaseObjectTreeObject) {
DatabaseObject databaseObject = (DatabaseObject) treeObject.getObject();
try {
boolean needReload = false;
UrlMapping urlMapping = getObject();
// An UrlMappingOperation has been added : add all path parameters
if (databaseObject instanceof UrlMappingOperation) {
if (urlMapping.equals(databaseObject.getParent())) {
UrlMappingOperation operation = (UrlMappingOperation) databaseObject;
if (operation.bNew) {
for (String variableName : urlMapping.getPathVariableNames()) {
UrlMappingParameter parameter = null;
try {
parameter = operation.getParameterByName(variableName);
} catch (EngineException e) {
try {
parameter = new PathParameter();
parameter.setName(variableName);
parameter.bNew = true;
operation.add(parameter);
operation.hasChanged = true;
needReload = true;
} catch (EngineException ex) {
ConvertigoPlugin.logException(ex, "Error when adding the parameter \"" + variableName + "\"");
}
}
}
}
if (needReload) {
ConvertigoPlugin.getDefault().getProjectExplorerView().reloadTreeObject(this);
}
}
}
} catch (Exception e) {
ConvertigoPlugin.logWarning(e, "Could not reload in tree Mapping \"" + databaseObject.getName() + "\" !");
}
}
}
use of com.twinsoft.convertigo.beans.core.UrlMappingOperation in project convertigo by convertigo.
the class UrlMappingTreeObject method treeObjectPropertyChanged.
@Override
public void treeObjectPropertyChanged(TreeObjectEvent treeObjectEvent) {
super.treeObjectPropertyChanged(treeObjectEvent);
String propertyName = (String) treeObjectEvent.propertyName;
propertyName = ((propertyName == null) ? "" : propertyName);
TreeObject treeObject = (TreeObject) treeObjectEvent.getSource();
if (treeObject instanceof DatabaseObjectTreeObject) {
DatabaseObject databaseObject = (DatabaseObject) treeObject.getObject();
// Case Mapping path has changed
if ("path".equals(propertyName)) {
if (treeObject.equals(this)) {
try {
UrlMapping urlMapping = (UrlMapping) databaseObject;
String oldPath = (String) treeObjectEvent.oldValue;
List<String> oldPathVariableNames = urlMapping.getPathVariableNames(oldPath);
List<String> newPathVariableNames = urlMapping.getPathVariableNames();
if (!oldPathVariableNames.equals(newPathVariableNames)) {
int oldLen = oldPathVariableNames.size();
int newLen = newPathVariableNames.size();
/*MessageBox messageBox = new MessageBox(viewer.getControl().getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setMessage("Do you really want to update mapping path parameters?");
messageBox.setText("Update parameters\"?");
int ret = messageBox.open();*/
int ret = SWT.YES;
if (ret == SWT.YES) {
// case of deletion
if (newLen < oldLen) {
for (String variableName : oldPathVariableNames) {
if (!newPathVariableNames.contains(variableName)) {
for (UrlMappingOperation operation : urlMapping.getOperationList()) {
for (UrlMappingParameter parameter : operation.getParameterList()) {
if (parameter.getName().equals(variableName)) {
if (parameter.getType().equals(Type.Path)) {
try {
parameter.delete();
operation.remove(parameter);
operation.hasChanged = true;
} catch (EngineException e) {
ConvertigoPlugin.logException(e, "Error when deleting the parameter \"" + variableName + "\"");
}
}
}
}
}
}
}
} else // case of rename
if (newLen == oldLen) {
for (int i = 0; i < oldLen; i++) {
String variableName = oldPathVariableNames.get(i);
for (UrlMappingOperation operation : urlMapping.getOperationList()) {
for (UrlMappingParameter parameter : operation.getParameterList()) {
if (parameter.getName().equals(variableName)) {
if (parameter.getType().equals(Type.Path)) {
try {
parameter.setName(newPathVariableNames.get(i));
parameter.hasChanged = true;
} catch (EngineException e) {
ConvertigoPlugin.logException(e, "Error when renaming the parameter \"" + variableName + "\"");
}
}
}
}
}
}
} else // case of creation
{
for (String variableName : newPathVariableNames) {
for (UrlMappingOperation operation : urlMapping.getOperationList()) {
UrlMappingParameter parameter = null;
try {
parameter = operation.getParameterByName(variableName);
} catch (EngineException e) {
try {
parameter = new PathParameter();
parameter.setName(variableName);
parameter.bNew = true;
operation.add(parameter);
} catch (EngineException ex) {
ConvertigoPlugin.logException(ex, "Error when adding the parameter \"" + variableName + "\"");
}
}
}
}
}
ConvertigoPlugin.getDefault().getProjectExplorerView().reloadTreeObject(this);
}
}
} catch (Exception e) {
ConvertigoPlugin.logWarning(e, "Could not reload in tree Mapping \"" + databaseObject.getName() + "\" !");
}
}
}
}
}
use of com.twinsoft.convertigo.beans.core.UrlMappingOperation in project convertigo by convertigo.
the class RestApiServlet method service.
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getCharacterEncoding() == null) {
try {
// Set encoding if needed
request.setCharacterEncoding("UTF-8");
} catch (Exception e) {
throw new ServletException(e);
}
}
try {
if (EnginePropertiesManager.getPropertyAsBoolean(PropertyName.XSRF_API)) {
HttpUtils.checkXSRF(request, response);
}
HttpSessionListener.checkSession(request);
} catch (Throwable e) {
throw new ServletException(e.getMessage(), e);
}
if (Engine.isEngineMode() && KeyManager.getCV(Session.EmulIDURLMAPPER) < 1) {
String msg;
if (KeyManager.has(Session.EmulIDURLMAPPER) && KeyManager.hasExpired(Session.EmulIDURLMAPPER)) {
Engine.logEngine.error(msg = "Key expired for the URL Mapper.");
throw new ServletException(new KeyExpiredException(msg));
}
Engine.logEngine.error(msg = "No key for the URL Mapper.");
throw new ServletException(new MaxCvsExceededException(msg));
}
HttpServletRequestTwsWrapper wrapped_request = new HttpServletRequestTwsWrapper(request);
request = wrapped_request;
try {
HttpSessionListener.checkSession(request);
} catch (TASException e) {
HttpUtils.terminateSession(request.getSession());
throw new RuntimeException(e);
}
HttpSession httpSession = request.getSession();
LogParameters logParameters = GenericUtils.cast(httpSession.getAttribute(RestApiServlet.class.getCanonicalName()));
if (logParameters == null) {
httpSession.setAttribute(RestApiServlet.class.getCanonicalName(), logParameters = new LogParameters());
logParameters.put(mdcKeys.ContextID.toString().toLowerCase(), httpSession.getId());
}
Log4jHelper.mdcSet(logParameters);
logParameters.put(mdcKeys.ClientIP.toString().toLowerCase(), request.getRemoteAddr());
String encoded = request.getParameter(Parameter.RsaEncoded.getName());
if (encoded != null) {
String query = Engine.theApp.rsaManager.decrypt(encoded, request.getSession());
wrapped_request.clearParameters();
wrapped_request.addQuery(query);
}
String method = request.getMethod();
String uri = request.getRequestURI();
String query = request.getQueryString();
Engine.logEngine.debug("(RestApiServlet) Requested URI: " + method + " " + uri);
boolean isYaml = request.getParameter("YAML") != null;
boolean isJson = request.getParameter("JSON") != null;
if ("GET".equalsIgnoreCase(method) && (query == null || query.isEmpty()) && (uri.endsWith("/" + SwaggerUtils.servletMappingPath) || uri.endsWith("/" + OpenApiUtils.servletMappingPath))) {
isJson = true;
}
// Generate YAML/JSON definition (swagger specific)
if ("GET".equalsIgnoreCase(method) && (isYaml || isJson)) {
try {
String requestUrl = HttpUtils.originalRequestURL(request);
// force endpoint in definition
try {
String endPointUrl = EnginePropertiesManager.getProperty(PropertyName.APPLICATION_SERVER_CONVERTIGO_ENDPOINT);
if (endPointUrl != null && !endPointUrl.isEmpty()) {
requestUrl = endPointUrl + (uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? uri.substring(uri.indexOf("/" + SwaggerUtils.servletMappingPath)) : uri.substring(uri.indexOf("/" + OpenApiUtils.servletMappingPath)));
Engine.logEngine.debug("(RestApiServlet) Force requestUrl: " + requestUrl);
} else {
Engine.logEngine.debug("(RestApiServlet) Set requestUrl: " + requestUrl);
}
} catch (Throwable t) {
Engine.logEngine.error("(RestApiServlet) Unable to retrieve server endpoint url: ", t);
}
Engine.logEngine.debug("(RestApiServlet) Projects path: " + new File(Engine.PROJECTS_PATH).getAbsolutePath());
String output = uri.indexOf("/" + SwaggerUtils.servletMappingPath) != -1 ? buildSwaggerDefinition(requestUrl, request.getParameter("__project"), isYaml) : buildOpenApiDefinition(requestUrl, request.getParameter("__project"), isYaml);
response.setCharacterEncoding("UTF-8");
response.setContentType((isYaml ? MimeType.Yaml : MimeType.Json).value());
Writer writer = response.getWriter();
writer.write(output);
Engine.logEngine.debug("(RestApiServlet) Definition sent :\n" + output);
} catch (Exception e) {
throw new ServletException(e);
}
} else // Handle REST request
{
long t0 = System.currentTimeMillis();
try {
Collection<UrlMapper> collection = RestApiManager.getInstance().getUrlMappers();
if (collection.size() > 0) {
if (method.equalsIgnoreCase("OPTIONS")) {
String origin = HeaderName.Origin.getHeader(request);
if (origin != null) {
Set<String> methods = new HashSet<String>();
String corsOrigin = null;
for (UrlMapper urlMapper : collection) {
String co = HttpUtils.filterCorsOrigin(urlMapper.getProject().getCorsOrigin(), origin);
if (co != null) {
if (corsOrigin == null || co.length() > corsOrigin.length()) {
corsOrigin = co;
}
urlMapper.addMatchingMethods(wrapped_request, methods);
}
}
HttpUtils.applyCorsHeaders(request, response, corsOrigin, String.join(", ", methods));
}
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
// Found a matching operation
UrlMappingOperation urlMappingOperation = null;
List<UrlAuthentication> urlAuthentications = null;
for (UrlMapper urlMapper : collection) {
urlMappingOperation = urlMapper.getMatchingOperation(request);
if (urlMappingOperation != null) {
urlAuthentications = urlMapper.getAuthenticationList();
break;
}
}
// Handle request
if (urlMappingOperation != null) {
StringBuffer buf;
// Request headers
if (Engine.logEngine.isDebugEnabled()) {
buf = new StringBuffer();
buf.append("(RestApiServlet) Request headers:\n");
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
buf.append(" " + headerName + "=" + headerValue + "\n");
}
Engine.logEngine.debug(buf.toString());
Engine.logEngine.debug("(RestApiServlet) Request parameters: " + Collections.list(request.getParameterNames()));
}
// The response content
String content = null;
// Check for authentication
if (urlMappingOperation.isTargetAuthenticationContextRequired()) {
// Case Authentications are defined for mapper
if (urlAuthentications != null) {
boolean authenticated = false;
int len = urlAuthentications.size();
if (len > 0) {
for (UrlAuthentication urlAuthentication : urlAuthentications) {
// Handle Auth request
response.reset();
RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
urlAuthentication.handleAuthRequest(request, response);
// Check user has been authenticated
authenticated = SessionAttribute.authenticatedUser.string(request.getSession()) != null;
if (authenticated) {
break;
}
}
// Handle User request
if (authenticated) {
response.reset();
RequestAttribute.responseHeader.set(request, new HashMap<String, String>());
RequestAttribute.responseStatus.set(request, new HashMap<Integer, String>());
content = urlMappingOperation.handleRequest(request, response);
}
} else // HTTP authentication required
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
} else // HTTP authentication required
{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
} else // Handle User request
{
content = urlMappingOperation.handleRequest(request, response);
}
// Set response status
ServletUtils.applyCustomStatus(request, response);
Engine.logEngine.debug("(RestApiServlet) Response status code: " + response.getStatus());
// Set response headers
ServletUtils.applyCustomHeaders(request, response);
if (Engine.logEngine.isDebugEnabled()) {
buf = new StringBuffer();
buf.append("(RestApiServlet) Response headers:\n");
Collection<String> headerNames = response.getHeaderNames();
for (String headerName : headerNames) {
String headerValue = response.getHeader(headerName);
buf.append(" " + headerName + "=" + headerValue + "\n");
}
Engine.logEngine.debug(buf.toString());
}
// terminate session to avoid max session exceeded (case new session initiated for authentication)
if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
if (urlMappingOperation instanceof com.twinsoft.convertigo.beans.rest.AbstractRestOperation) {
com.twinsoft.convertigo.beans.rest.AbstractRestOperation aro = (com.twinsoft.convertigo.beans.rest.AbstractRestOperation) urlMappingOperation;
if (aro.isTerminateSession()) {
Engine.logEngine.debug("(RestApiServlet) requireEndOfContext because of required authentication");
request.setAttribute("convertigo.requireEndOfContext", true);
}
}
}
if (content != null) {
Writer writer = response.getWriter();
writer.write(content);
}
Engine.logEngine.debug("(RestApiServlet) Request successfully handled");
} else {
Engine.logEngine.debug("(RestApiServlet) No matching operation for request");
super.service(request, response);
}
} else {
Engine.logEngine.debug("(RestApiServlet) No mapping defined");
super.service(request, response);
}
} catch (Exception e) {
throw new ServletException(e);
} finally {
Requester requester = (Requester) request.getAttribute("convertigo.requester");
if (requester != null) {
Engine.logEngine.debug("(RestApiServlet) processRequestEnd, onFinally");
processRequestEnd(request, requester);
onFinally(request);
} else {
Engine.logEngine.debug("(RestApiServlet) terminate session");
try {
HttpUtils.terminateSession(httpSession);
} catch (Exception e) {
Engine.logEngine.warn("(RestApiServlet) unabled to terminate session", e);
}
}
long t1 = System.currentTimeMillis();
Engine.theApp.pluginsManager.fireHttpServletRequestEnd(request, t0, t1);
}
}
}
use of com.twinsoft.convertigo.beans.core.UrlMappingOperation in project convertigo by convertigo.
the class OpenApiUtils method writeOpenApiToFile.
private static void writeOpenApiToFile(final String requestUrl, final UrlMapper urlMapper, final File yamlFile, boolean useExternalRef) throws Exception {
synchronized (lockObject) {
if (yamlFile.exists() && Engine.isEngineMode())
return;
Long t0 = System.currentTimeMillis();
Project project = urlMapper.getProject();
String projectName = project.getName();
String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
OpenAPI openAPI = parseCommon(requestUrl, project);
List<Tag> tags = new ArrayList<>();
Tag tag = new Tag();
tag.setName(project.getName());
tag.setDescription(project.getComment());
tags.add(tag);
openAPI.setTags(tags);
if (openAPI.getComponents() == null) {
openAPI.components(new Components());
}
// Security
Map<String, SecurityScheme> securitySchemes = openAPI.getComponents().getSecuritySchemes();
for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
if (AuthenticationType.Basic.equals(authentication.getType())) {
if (securitySchemes == null || !securitySchemes.containsKey("basicAuth")) {
SecurityScheme securitySchemesItem = new SecurityScheme();
securitySchemesItem.setType(SecurityScheme.Type.HTTP);
securitySchemesItem.setScheme("basic");
openAPI.getComponents().addSecuritySchemes("basicAuth", securitySchemesItem);
SecurityRequirement securityRequirement = new SecurityRequirement();
securityRequirement.addList("basicAuth", new ArrayList<String>());
openAPI.addSecurityItem(securityRequirement);
}
}
}
List<String> refList = new ArrayList<String>();
List<String> opIdList = new ArrayList<String>();
// Paths
Paths paths = new Paths();
try {
for (UrlMapping urlMapping : urlMapper.getMappingList()) {
PathItem item = new PathItem();
for (UrlMappingOperation umo : urlMapping.getOperationList()) {
Operation operation = new Operation();
operation.setOperationId(getOperationId(opIdList, umo, false));
operation.setDescription(umo.getComment());
operation.setSummary(umo.getComment());
// Tags
List<String> list = Arrays.asList("" + project.getName());
operation.setTags(list);
// 1 - add path parameters
for (String pathVarName : urlMapping.getPathVariableNames()) {
PathParameter parameter = new PathParameter();
parameter.setName(pathVarName);
// retrieve parameter description from bean
UrlMappingParameter ump = null;
try {
ump = umo.getParameterByName(pathVarName);
} catch (Exception e) {
}
if (ump != null && ump.getType() == Type.Path) {
parameter.setDescription(ump.getComment());
Schema<?> schema = getSchema(ump);
if (schema != null) {
parameter.setSchema(schema);
}
}
operation.addParametersItem(parameter);
}
// 2 - add other parameters
for (UrlMappingParameter ump : umo.getParameterList()) {
Parameter parameter = null;
if (ump.getType() == Type.Query) {
parameter = new QueryParameter();
} else if (ump.getType() == Type.Form) {
addFormParameter(operation, ump);
} else if (ump.getType() == Type.Body) {
addBodyParameter(operation, ump, oasDirUrl, refList, useExternalRef);
} else if (ump.getType() == Type.Header) {
parameter = new HeaderParameter();
} else if (ump.getType() == Type.Path) {
// ignore : should have been treated before
}
if (parameter != null) {
// Query | Header
parameter.setName(ump.getName());
parameter.setDescription(ump.getComment());
parameter.setRequired(ump.isRequired());
// parameter.setAllowEmptyValue(allowEmptyValue);
Schema<?> schema = getSchema(ump);
if (schema != null) {
parameter.setSchema(schema);
}
// add parameter
if (ump.isExposed()) {
operation.addParametersItem(parameter);
}
}
}
// Responses
List<String> produces = new ArrayList<String>();
if (umo instanceof AbstractRestOperation) {
DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
if (dataOutput.equals(DataContent.toJson)) {
produces = Arrays.asList(MimeType.Json.value());
} else if (dataOutput.equals(DataContent.toXml)) {
produces = Arrays.asList(MimeType.Xml.value());
} else {
produces = Arrays.asList(MimeType.Json.value(), MimeType.Xml.value());
}
}
ApiResponses responses = new ApiResponses();
operation.setResponses(responses);
for (UrlMappingResponse umr : umo.getResponseList()) {
String statusCode = umr.getStatusCode();
if (!statusCode.isEmpty()) {
if (!responses.containsKey(statusCode)) {
ApiResponse response = new ApiResponse();
response.setDescription(umr.getStatusText());
responses.addApiResponse(statusCode, response);
String modelReference = ((IMappingRefModel) umr).getModelReference();
if (!modelReference.isEmpty() && !produces.isEmpty()) {
if (modelReference.indexOf(".jsonschema") != -1) {
modelReference = modelReference.replace(".jsonschema#/definitions/", ".json#/components/schemas/");
modelReference = oasDirUrl + modelReference;
}
Content content = new Content();
response.setContent(content);
for (String mt : produces) {
MediaType mediaType = new MediaType();
content.addMediaType(mt, mediaType);
ObjectSchema schema = new ObjectSchema();
if (!refList.contains(modelReference)) {
refList.add(modelReference);
}
if (!useExternalRef && modelReference.indexOf('#') != -1) {
modelReference = modelReference.substring(modelReference.indexOf('#'));
}
schema.set$ref(modelReference);
mediaType.setSchema(schema);
}
}
}
}
}
if (umo.getMethod().equals(HttpMethodType.DELETE.name())) {
item.setDelete(operation);
} else if (umo.getMethod().equals(HttpMethodType.GET.name())) {
item.setGet(operation);
} else if (umo.getMethod().equals(HttpMethodType.HEAD.name())) {
item.setHead(operation);
} else if (umo.getMethod().equals(HttpMethodType.OPTIONS.name())) {
item.setOptions(operation);
} else if (umo.getMethod().equals(HttpMethodType.POST.name())) {
item.setPost(operation);
} else if (umo.getMethod().equals(HttpMethodType.PUT.name())) {
item.setPut(operation);
} else if (umo.getMethod().equals(HttpMethodType.TRACE.name())) {
item.setTrace(operation);
}
}
paths.addPathItem(urlMapping.getPathWithPrefix(), item);
}
} catch (Exception e) {
e.printStackTrace();
Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
}
openAPI.setPaths(paths);
// Models and Schemas
try {
Map<String, JSONObject> modelMap = new HashMap<String, JSONObject>(1000);
String models = getModels(oasDirUrl, urlMapper, modelMap);
/*System.out.println("refList");
for (String keyRef: refList) {
System.out.println(keyRef);
}
System.out.println("modelMap");
for (String keyRef: modelMap.keySet()) {
System.out.println(keyRef);
}*/
Set<String> done = new HashSet<String>();
JSONObject jsonModels = new JSONObject(models);
for (String keyRef : refList) {
addModelsFromMap(done, modelMap, keyRef, jsonModels);
}
OpenAPI oa = new OpenAPI();
String s = Json.pretty(oa.info(new Info()));
JSONObject json = new JSONObject(s);
json.put("components", new JSONObject());
json.getJSONObject("components").put("schemas", jsonModels);
JsonNode rootNode = Json.mapper().readTree(json.toString());
OpenAPIDeserializer ds = new OpenAPIDeserializer();
SwaggerParseResult result = ds.deserialize(rootNode);
@SuppressWarnings("rawtypes") Map<String, Schema> map = result.getOpenAPI().getComponents().getSchemas();
openAPI.getComponents().schemas(map);
modelMap.clear();
} catch (Throwable t) {
t.printStackTrace();
Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate models", t);
}
// write yaml
try {
FileUtils.write(yamlFile, prettyPrintYaml(openAPI), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
Engine.logEngine.error("Unexpected exception while writing project YAML file", e);
} finally {
Long t1 = System.currentTimeMillis();
Engine.logEngine.info("YAML file for " + projectName + " project written in " + (t1 - t0) + " ms");
}
}
}
Aggregations