use of com.twinsoft.convertigo.beans.core.UrlAuthentication in project convertigo by convertigo.
the class SwaggerUtils method parse.
public static Swagger parse(String requestUrl, UrlMapper urlMapper) {
Project project = urlMapper.getProject();
String projectName = project.getName();
String oasDirUrl = requestUrl.substring(0, requestUrl.indexOf("/" + servletMappingPath)) + "/projects/" + projectName + "/" + jsonSchemaDirectory + "/";
Swagger swagger = parseCommon(requestUrl, project);
List<Tag> tags = new ArrayList<Tag>();
Tag tag = new Tag();
tag.setName(urlMapper.getProject().getName());
tag.setDescription(urlMapper.getProject().getComment());
tags.add(tag);
swagger.setTags(tags);
// Security
Map<String, SecuritySchemeDefinition> securityDefinitions = swagger.getSecurityDefinitions();
for (UrlAuthentication authentication : urlMapper.getAuthenticationList()) {
if (AuthenticationType.Basic.equals(authentication.getType())) {
if (securityDefinitions == null || !securityDefinitions.containsKey("basicAuth")) {
BasicAuthDefinition basicAuthDefinition = new BasicAuthDefinition();
swagger.addSecurityDefinition("basicAuth", basicAuthDefinition);
SecurityRequirement securityRequirement = new SecurityRequirement();
securityRequirement.requirement("basicAuth", new ArrayList<String>());
swagger.addSecurity(securityRequirement);
}
}
}
// Models and Schemas
Map<String, Model> swagger_models = new HashMap<String, Model>();
try {
String models = getModels(oasDirUrl, urlMapper);
if (!models.isEmpty()) {
ObjectMapper mapper = Json.mapper();
JsonNode definitionNode = mapper.readTree(models);
for (Iterator<Entry<String, JsonNode>> it = GenericUtils.cast(definitionNode.fields()); it.hasNext(); ) {
Entry<String, JsonNode> entry = it.next();
swagger_models.put(entry.getKey().toString(), mapper.convertValue(entry.getValue(), Model.class));
}
}
} catch (Exception e) {
e.printStackTrace();
Engine.logEngine.warn("Unexpected exception while reading UrlMapper defined models", e);
}
swagger.setDefinitions(swagger_models);
// Mappings
Map<String, Path> swagger_paths = new HashMap<String, Path>();
try {
for (UrlMapping urlMapping : urlMapper.getMappingList()) {
Path swagger_path = new Path();
for (UrlMappingOperation umo : urlMapping.getOperationList()) {
Operation s_operation = new Operation();
s_operation.setOperationId(umo.getQName());
s_operation.setDescription(umo.getComment());
s_operation.setSummary(umo.getComment());
// Operation produces
if (umo instanceof AbstractRestOperation) {
DataContent dataOutput = ((AbstractRestOperation) umo).getOutputContent();
if (dataOutput.equals(DataContent.toJson)) {
s_operation.setProduces(Arrays.asList(MimeType.Json.value()));
} else if (dataOutput.equals(DataContent.toXml)) {
s_operation.setProduces(Arrays.asList(MimeType.Xml.value()));
} else {
s_operation.setProduces(Arrays.asList(MimeType.Json.value(), MimeType.Xml.value()));
}
}
// Operation tags
List<String> list = Arrays.asList("" + project.getName());
s_operation.setTags(list);
// Operation consumes
List<String> consumes = new ArrayList<String>();
// Operation parameters
List<Parameter> s_parameters = new ArrayList<Parameter>();
// 1 - add path parameters
for (String pathVarName : urlMapping.getPathVariableNames()) {
PathParameter s_parameter = new PathParameter();
s_parameter.setName(pathVarName);
s_parameter.setRequired(true);
s_parameter.setType("string");
// retrieve parameter description from bean
UrlMappingParameter ump = null;
try {
ump = umo.getParameterByName(pathVarName);
} catch (Exception e) {
}
if (ump != null && ump.getType() == Type.Path) {
s_parameter.setDescription(ump.getComment());
s_parameter.setType(ump.getInputType().toLowerCase());
Object value = ump.getValueOrNull();
if (value != null) {
s_parameter.setDefaultValue(String.valueOf(value));
}
}
s_parameters.add(s_parameter);
}
// 2 - add other parameters
for (UrlMappingParameter ump : umo.getParameterList()) {
Parameter s_parameter = null;
if (ump.getType() == Type.Query) {
s_parameter = new QueryParameter();
} else if (ump.getType() == Type.Form) {
s_parameter = new FormParameter();
} else if (ump.getType() == Type.Body) {
s_parameter = new BodyParameter();
if (ump instanceof IMappingRefModel) {
String modelReference = ((IMappingRefModel) ump).getModelReference();
if (!modelReference.isEmpty()) {
if (modelReference.indexOf(".jsonschema") != -1) {
modelReference = oasDirUrl + modelReference;
}
RefModel refModel = new RefModel(modelReference);
((BodyParameter) s_parameter).setSchema(refModel);
}
}
} else if (ump.getType() == Type.Header) {
s_parameter = new HeaderParameter();
} else if (ump.getType() == Type.Path) {
// ignore : should have been treated before
}
if (s_parameter != null) {
s_parameter.setName(ump.getName());
s_parameter.setDescription(ump.getComment());
s_parameter.setRequired(ump.isRequired());
if (s_parameter instanceof SerializableParameter) {
boolean isArray = ump.isMultiValued() || ump.isArray();
String _type = isArray ? "array" : ump.getDataType().name().toLowerCase();
String _collectionFormat = ump.isMultiValued() ? "multi" : (isArray ? "csv" : null);
Property _items = isArray ? getItems(ump.getDataType()) : null;
((SerializableParameter) s_parameter).setType(_type);
((SerializableParameter) s_parameter).setCollectionFormat(_collectionFormat);
((SerializableParameter) s_parameter).setItems(_items);
Object value = ump.getValueOrNull();
if (value != null) {
String collection = ((SerializableParameter) s_parameter).getCollectionFormat();
if (collection != null && collection.equals("multi")) {
Property items = new StringProperty();
// items.setDefault(String.valueOf(value));
((SerializableParameter) s_parameter).setItems(items);
// ((SerializableParameter) s_parameter).setEnumValue(Arrays.asList("val1","val2","val3"));
} else {
((AbstractSerializableParameter<?>) s_parameter).setDefaultValue(String.valueOf(value));
}
}
}
DataContent dataInput = ump.getInputContent();
if (dataInput.equals(DataContent.toJson)) {
if (!consumes.contains(MimeType.Json.value())) {
consumes.add(MimeType.Json.value());
}
} else if (dataInput.equals(DataContent.toXml)) {
if (!consumes.contains(MimeType.Xml.value())) {
consumes.add(MimeType.Xml.value());
}
}
// swagger-ui workaround for invalid request content-type for POST
if (ump.getType() == Type.Form) {
if (!DataType.File.equals(ump.getDataType())) {
if (!consumes.contains(MimeType.WwwForm.value())) {
consumes.add(MimeType.WwwForm.value());
}
} else {
if (!consumes.contains("multipart/form-data")) {
consumes.add("multipart/form-data");
}
}
}
// add parameter
if (ump.isExposed()) {
s_parameters.add(s_parameter);
}
}
}
s_operation.setParameters(s_parameters);
if (!consumes.isEmpty()) {
s_operation.setConsumes(consumes);
}
// Set operation responses
Map<String, Response> responses = new HashMap<String, Response>();
for (UrlMappingResponse umr : umo.getResponseList()) {
String statusCode = umr.getStatusCode();
if (!statusCode.isEmpty()) {
if (!responses.containsKey(statusCode)) {
Response response = new Response();
// response.setDescription(umr.getComment());
response.setDescription(umr.getStatusText());
if (umr instanceof IMappingRefModel) {
String modelReference = ((IMappingRefModel) umr).getModelReference();
if (!modelReference.isEmpty()) {
if (modelReference.indexOf(".jsonschema") != -1) {
modelReference = oasDirUrl + modelReference;
}
RefProperty refProperty = new RefProperty(modelReference);
response.setResponseSchema(new PropertyModelConverter().propertyToModel(refProperty));
}
}
responses.put(statusCode, response);
}
}
}
if (responses.isEmpty()) {
Response resp200 = new Response();
resp200.description("successful operation");
responses.put("200", resp200);
}
s_operation.setResponses(responses);
// Add operation to path
String s_method = umo.getMethod().toLowerCase();
swagger_path.set(s_method, s_operation);
}
swagger_paths.put(urlMapping.getPathWithPrefix(), swagger_path);
}
} catch (Exception e) {
e.printStackTrace();
Engine.logEngine.error("Unexpected exception while parsing UrlMapper to generate definition", e);
}
swagger.setPaths(swagger_paths);
return swagger;
}
use of com.twinsoft.convertigo.beans.core.UrlAuthentication in project convertigo by convertigo.
the class ProjectExplorerView method loadDatabaseObject.
private void loadDatabaseObject(TreeParent parentTreeObject, DatabaseObject parentDatabaseObject, ProjectLoadingJob projectLoadingJob, final IProgressMonitor monitor) throws EngineException, IOException {
try {
new WalkHelper() {
// recursion parameters
TreeParent parentTreeObject;
ProjectLoadingJob projectLoadingJob;
// sibling parameters
ObjectsFolderTreeObject currentTreeFolder = null;
public void init(DatabaseObject databaseObject, TreeParent parentTreeObject, ProjectLoadingJob projectLoadingJob) throws Exception {
this.parentTreeObject = parentTreeObject;
this.projectLoadingJob = projectLoadingJob;
walkInheritance = true;
super.init(databaseObject);
}
protected ObjectsFolderTreeObject getFolder(TreeParent treeParent, int folderType) {
ObjectsFolderTreeObject ofto = null;
for (TreeObject to : treeParent.getChildren()) {
if (to instanceof ObjectsFolderTreeObject) {
if (((ObjectsFolderTreeObject) to).folderType == folderType) {
ofto = (ObjectsFolderTreeObject) to;
break;
}
}
}
if (ofto == null) {
ofto = new ObjectsFolderTreeObject(viewer, folderType);
treeParent.addChild(ofto);
}
return ofto;
}
@Override
protected void walk(DatabaseObject databaseObject) throws Exception {
// retrieve recursion parameters
final TreeParent parentTreeObject = this.parentTreeObject;
final ProjectLoadingJob projectLoadingJob = this.projectLoadingJob;
// retrieve sibling parameters
ObjectsFolderTreeObject currentTreeFolder = this.currentTreeFolder;
String dboName = (databaseObject instanceof Step) ? ((Step) databaseObject).getStepNodeName() : databaseObject.getName();
monitor.subTask("Loading databaseObject '" + dboName + "'...");
DatabaseObjectTreeObject databaseObjectTreeObject = null;
// first call case, the tree object already exists and its content is just refreshed
if (parentTreeObject.getObject() == databaseObject) {
databaseObjectTreeObject = (DatabaseObjectTreeObject) parentTreeObject;
} else // recursive call case, the tree object doesn't exist and must be added to the parent tree object
{
int folderType = Integer.MIN_VALUE;
if (databaseObject instanceof Connector) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_CONNECTORS;
databaseObjectTreeObject = new ConnectorTreeObject(viewer, (Connector) databaseObject, false);
} else if (databaseObject instanceof Sequence) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SEQUENCES;
databaseObjectTreeObject = new SequenceTreeObject(viewer, (Sequence) databaseObject, false);
} else if (databaseObject instanceof MobileApplication) {
databaseObjectTreeObject = new MobileApplicationTreeObject(viewer, (MobileApplication) databaseObject, false);
} else if (databaseObject instanceof MobilePlatform) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_PLATFORMS;
databaseObjectTreeObject = new MobilePlatformTreeObject(viewer, (MobilePlatform) databaseObject, false);
} else /**
***********************************************************************************************
*/
if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.MobileComponent) {
if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.ApplicationComponent) {
databaseObjectTreeObject = new MobileApplicationComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.RouteComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_ROUTES;
databaseObjectTreeObject = new MobileRouteComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.RouteEventComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
databaseObjectTreeObject = new MobileRouteEventComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.RouteActionComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_ACTIONS;
databaseObjectTreeObject = new MobileRouteActionComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.PageComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_PAGES;
databaseObjectTreeObject = new MobilePageComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIActionStack) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SHARED_ACTIONS;
databaseObjectTreeObject = new MobileUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UISharedComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SHARED_COMPONENTS;
databaseObjectTreeObject = new MobileUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIDynamicMenu) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_MENUS;
databaseObjectTreeObject = new MobileUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIComponent) {
if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIAttribute) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_ATTRIBUTES;
if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIControlAttr) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_CONTROLS;
}
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIStyle) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_STYLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIControlVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UICompVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIStackVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIFormValidator) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VALIDATORS;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIAppEvent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIPageEvent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.mobile.components.UIEventSubscriber) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
}
databaseObjectTreeObject = new MobileUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
}
} else /**
***********************************************************************************************
*/
if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.MobileComponent) {
if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.ApplicationComponent) {
databaseObjectTreeObject = new NgxApplicationComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.PageComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_PAGES;
databaseObjectTreeObject = new NgxPageComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIActionStack) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SHARED_ACTIONS;
databaseObjectTreeObject = new NgxUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UISharedComponent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SHARED_COMPONENTS;
databaseObjectTreeObject = new NgxUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIDynamicMenu) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_MENUS;
databaseObjectTreeObject = new NgxUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIComponent) {
if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIAttribute) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_ATTRIBUTES;
if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIControlAttr) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_CONTROLS;
}
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIDynamicAttr) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_ATTRIBUTES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIStyle) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_STYLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIControlVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UICompVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIStackVariable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIAppEvent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIPageEvent) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.ngx.components.UIEventSubscriber) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EVENTS;
}
databaseObjectTreeObject = new NgxUIComponentTreeObject(viewer, GenericUtils.cast(databaseObject), false);
}
} else if (databaseObject instanceof UrlMapper) {
databaseObjectTreeObject = new UrlMapperTreeObject(viewer, (UrlMapper) databaseObject, false);
} else if (databaseObject instanceof UrlAuthentication) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_AUTHENTICATIONS;
databaseObjectTreeObject = new UrlAuthenticationTreeObject(viewer, (UrlAuthentication) databaseObject, false);
} else if (databaseObject instanceof UrlMapping) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_MAPPINGS;
databaseObjectTreeObject = new UrlMappingTreeObject(viewer, (UrlMapping) databaseObject, false);
} else if (databaseObject instanceof UrlMappingOperation) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_OPERATIONS;
databaseObjectTreeObject = new UrlMappingOperationTreeObject(viewer, (UrlMappingOperation) databaseObject, false);
} else if (databaseObject instanceof UrlMappingParameter) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_PARAMETERS;
databaseObjectTreeObject = new UrlMappingParameterTreeObject(viewer, (UrlMappingParameter) databaseObject, false);
} else if (databaseObject instanceof UrlMappingResponse) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_RESPONSES;
databaseObjectTreeObject = new UrlMappingResponseTreeObject(viewer, (UrlMappingResponse) databaseObject, false);
} else if (databaseObject instanceof Reference) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_REFERENCES;
databaseObjectTreeObject = new ReferenceTreeObject(viewer, (Reference) databaseObject, false);
} else if (databaseObject instanceof Pool) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_POOLS;
databaseObjectTreeObject = new DatabaseObjectTreeObject(viewer, databaseObject, false);
} else if (databaseObject instanceof Transaction) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_TRANSACTIONS;
databaseObjectTreeObject = new TransactionTreeObject(viewer, (Transaction) databaseObject, false);
} else if (databaseObject instanceof ScreenClass) {
if (databaseObject.getParent() instanceof IScreenClassContainer<?>) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SCREEN_CLASSES;
databaseObjectTreeObject = new ScreenClassTreeObject(viewer, (ScreenClass) databaseObject, false);
} else {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_INHERITED_SCREEN_CLASSES;
databaseObjectTreeObject = new ScreenClassTreeObject(viewer, (ScreenClass) databaseObject, false);
}
} else if (databaseObject instanceof Sheet) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_SHEETS;
databaseObjectTreeObject = new SheetTreeObject(viewer, (Sheet) databaseObject, parentTreeObject.getObject() != databaseObject.getParent());
} else if (databaseObject instanceof TestCase) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_TESTCASES;
databaseObjectTreeObject = new TestCaseTreeObject(viewer, (TestCase) databaseObject, false);
} else if (databaseObject instanceof Variable) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_VARIABLES;
databaseObjectTreeObject = new VariableTreeObject2(viewer, (Variable) databaseObject, false);
} else if (databaseObject instanceof Step) {
if (databaseObject.getParent() instanceof Sequence) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_STEPS;
}
databaseObjectTreeObject = new StepTreeObject(viewer, (Step) databaseObject, false);
} else if (databaseObject instanceof Statement) {
if (databaseObject.getParent() instanceof Transaction) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_FUNCTIONS;
}
databaseObjectTreeObject = new StatementTreeObject(viewer, (Statement) databaseObject, false);
} else if (databaseObject instanceof Criteria) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_CRITERIAS;
databaseObjectTreeObject = new CriteriaTreeObject(viewer, (Criteria) databaseObject, parentTreeObject.getObject() != databaseObject.getParent());
} else if (databaseObject instanceof ExtractionRule) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_EXTRACTION_RULES;
databaseObjectTreeObject = new ExtractionRuleTreeObject(viewer, (ExtractionRule) databaseObject, parentTreeObject.getObject() != databaseObject.getParent());
} else if (databaseObject instanceof BlockFactory) {
databaseObjectTreeObject = new DatabaseObjectTreeObject(viewer, databaseObject, parentTreeObject.getObject() != databaseObject.getParent());
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.core.Document) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_DOCUMENTS;
com.twinsoft.convertigo.beans.core.Document document = (com.twinsoft.convertigo.beans.core.Document) databaseObject;
String documentRenderer = document.getRenderer();
if (documentRenderer.equals("DesignDocumentTreeObject"))
databaseObjectTreeObject = new DesignDocumentTreeObject(viewer, document, false);
else
databaseObjectTreeObject = new DocumentTreeObject(viewer, document, false);
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.core.Listener) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_LISTENERS;
com.twinsoft.convertigo.beans.core.Listener listener = (com.twinsoft.convertigo.beans.core.Listener) databaseObject;
String listenerRenderer = listener.getRenderer();
if (listenerRenderer.equals("FullSyncListenerTreeObject")) {
databaseObjectTreeObject = new FullSyncListenerTreeObject(viewer, listener, false);
} else {
databaseObjectTreeObject = new ListenerTreeObject(viewer, listener, false);
}
} else if (databaseObject instanceof com.twinsoft.convertigo.beans.core.Index) {
folderType = ObjectsFolderTreeObject.FOLDER_TYPE_INDEXES;
databaseObjectTreeObject = new DatabaseObjectTreeObject(viewer, databaseObject, false);
} else {
// unknow DBO case !!!
databaseObjectTreeObject = new DatabaseObjectTreeObject(viewer, databaseObject, false);
}
// no virtual folder
if (folderType == Integer.MIN_VALUE) {
parentTreeObject.addChild(databaseObjectTreeObject);
} else // virtual folder creation or reuse
{
/* fixed #5416 */
// if (currentTreeFolder == null || currentTreeFolder.folderType != folderType) {
// currentTreeFolder = new ObjectsFolderTreeObject(viewer, folderType);
// parentTreeObject.addChild(currentTreeFolder);
// }
currentTreeFolder = getFolder(parentTreeObject, folderType);
currentTreeFolder.addChild(databaseObjectTreeObject);
}
// case databaseObject has been changed through dbo::preconfigure, mark projectTreeObject as modified
if ((databaseObject.bNew) || (databaseObject.hasChanged && !databaseObject.bNew)) {
databaseObjectTreeObject.hasBeenModified(true);
}
// new value of recursion parameters
this.parentTreeObject = databaseObjectTreeObject;
}
// special databaseObject cases
if (databaseObject instanceof Project) {
Project project = (Project) databaseObject;
// Creates directories and files
createDirsAndFiles(project.getName());
// Creates or Refresh xsd and wsdl folders
IFolder xsdFolder, wsdlFolder = null;
IFolder xsdInternalFolder = null;
try {
wsdlFolder = ((ProjectTreeObject) parentTreeObject).getFolder("wsdl");
if (!wsdlFolder.exists())
wsdlFolder.create(true, true, null);
else
wsdlFolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
xsdFolder = ((ProjectTreeObject) parentTreeObject).getFolder("xsd");
if (!xsdFolder.exists())
xsdFolder.create(true, true, null);
else {
xsdInternalFolder = xsdFolder.getFolder("internal");
if (!xsdInternalFolder.exists())
xsdInternalFolder.create(true, true, null);
xsdFolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
}
} catch (Exception e) {
e.printStackTrace();
}
// Connectors
IFolder xsdConnectorInternalFolder = null;
Collection<Connector> connectors = project.getConnectorsList();
if (connectors.size() != 0) {
// Set default connector if none
if (project.getDefaultConnector() == null) {
// Report from 4.5: fix #401
ConvertigoPlugin.logWarning(null, "Project \"" + project.getName() + "\" has no default connector. Try to set a default one.");
Connector defaultConnector = connectors.iterator().next();
try {
project.setDefaultConnector(defaultConnector);
defaultConnector.hasChanged = true;
} catch (Exception e) {
ConvertigoPlugin.logWarning(e, "Unable to set a default connector for project \"" + project.getName() + "\"");
}
}
// Refresh Traces folder
IFolder ifolder = ((ProjectTreeObject) parentTreeObject).getFolder("Traces");
if (ifolder.exists()) {
try {
ifolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
}
}
// Creates or Refresh internal xsd connector folders
for (Connector connector : connectors) {
try {
xsdConnectorInternalFolder = xsdInternalFolder.getFolder(connector.getName());
if (!xsdConnectorInternalFolder.exists())
xsdConnectorInternalFolder.create(true, true, null);
else
xsdConnectorInternalFolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if (databaseObject instanceof Connector) {
Connector connector = (Connector) databaseObject;
// Open connector editor
if (projectLoadingJob != null && connector.isDefault) {
projectLoadingJob.setDefaultConnectorTreeObject((ConnectorTreeObject) databaseObjectTreeObject);
}
// Traces
if (connector instanceof JavelinConnector) {
String projectName = databaseObject.getProject().getName();
if (projectLoadingJob == null) {
if (MigrationManager.isProjectMigrated(projectName)) {
UnloadedProjectTreeObject unloadedProjectTreeObject = new UnloadedProjectTreeObject(databaseObjectTreeObject.viewer, projectName);
this.projectLoadingJob = new ProjectLoadingJob(databaseObjectTreeObject.viewer, unloadedProjectTreeObject);
this.projectLoadingJob.loadTrace(databaseObjectTreeObject, new File(Engine.projectDir(projectName) + "/Traces/" + connector.getName()));
}
}
if (projectLoadingJob != null) {
projectLoadingJob.loadTrace(databaseObjectTreeObject, new File(Engine.projectDir(projectName) + "/Traces/" + connector.getName()));
}
}
} else if (databaseObject instanceof Transaction) {
Transaction transaction = (Transaction) databaseObject;
// Functions
List<HandlersDeclarationTreeObject> treeObjects = new LinkedList<HandlersDeclarationTreeObject>();
String line, lineReaded;
int lineNumber = 0;
BufferedReader br = new BufferedReader(new StringReader(transaction.handlers));
line = br.readLine();
while (line != null) {
lineReaded = line.trim();
lineNumber++;
if (lineReaded.startsWith("function ")) {
try {
String functionName = lineReaded.substring(9, lineReaded.indexOf(')') + 1);
HandlersDeclarationTreeObject handlersDeclarationTreeObject = null;
if (functionName.endsWith(JavelinTransaction.EVENT_ENTRY_HANDLER + "()")) {
handlersDeclarationTreeObject = new HandlersDeclarationTreeObject(viewer, functionName, HandlersDeclarationTreeObject.TYPE_FUNCTION_SCREEN_CLASS_ENTRY, lineNumber);
} else if (functionName.endsWith(JavelinTransaction.EVENT_EXIT_HANDLER + "()")) {
handlersDeclarationTreeObject = new HandlersDeclarationTreeObject(viewer, functionName, HandlersDeclarationTreeObject.TYPE_FUNCTION_SCREEN_CLASS_EXIT, lineNumber);
} else {
handlersDeclarationTreeObject = new HandlersDeclarationTreeObject(viewer, functionName, HandlersDeclarationTreeObject.TYPE_OTHER, lineNumber);
}
if (handlersDeclarationTreeObject != null) {
treeObjects.add(handlersDeclarationTreeObject);
}
} catch (StringIndexOutOfBoundsException e) {
throw new EngineException("Exception in reading line of a transaction", e);
}
}
line = br.readLine();
}
if (treeObjects.size() != 0) {
ObjectsFolderTreeObject objectsFolderTreeObject = new ObjectsFolderTreeObject(viewer, ObjectsFolderTreeObject.FOLDER_TYPE_FUNCTIONS);
databaseObjectTreeObject.addChild(objectsFolderTreeObject);
for (HandlersDeclarationTreeObject handlersDeclarationTreeObject : treeObjects) {
objectsFolderTreeObject.addChild(handlersDeclarationTreeObject);
}
}
} else if (databaseObject instanceof Sheet) {
addTemplates((Sheet) databaseObject, databaseObjectTreeObject);
} else if (databaseObject instanceof ITablesProperty) {
ITablesProperty iTablesProperty = (ITablesProperty) databaseObject;
String[] tablePropertyNames = iTablesProperty.getTablePropertyNames();
for (int i = 0; i < tablePropertyNames.length; i++) {
String tablePropertyName = tablePropertyNames[i];
String tableRenderer = iTablesProperty.getTableRenderer(tablePropertyName);
XMLVector<XMLVector<Object>> xmlv = iTablesProperty.getTableData(tablePropertyName);
if (tableRenderer.equals("XMLTableDescriptionTreeObject")) {
XMLTableDescriptionTreeObject propertyXMLTableTreeObject = new XMLTableDescriptionTreeObject(viewer, tablePropertyName, xmlv, databaseObjectTreeObject);
databaseObjectTreeObject.addChild(propertyXMLTableTreeObject);
} else if (tableRenderer.equals("XMLRecordDescriptionTreeObject")) {
XMLRecordDescriptionTreeObject propertyXMLRecordTreeObject = new XMLRecordDescriptionTreeObject(viewer, tablePropertyName, xmlv, databaseObjectTreeObject);
databaseObjectTreeObject.addChild(propertyXMLRecordTreeObject);
}
}
}
monitor.worked(1);
// children cannot be added in the current virtual folder
this.currentTreeFolder = null;
super.walk(databaseObject);
// restore recursion parameters
this.parentTreeObject = parentTreeObject;
this.projectLoadingJob = projectLoadingJob;
// restore sibling parameters
this.currentTreeFolder = currentTreeFolder;
}
}.init(parentDatabaseObject, parentTreeObject, projectLoadingJob);
} catch (EngineException e) {
throw e;
} catch (Exception e) {
throw new EngineException("Exception in copyDatabaseObject", e);
}
}
use of com.twinsoft.convertigo.beans.core.UrlAuthentication 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.UrlAuthentication 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