second part of fixing Sonar issues (#2295)

* fix sonar issues

* fix csharp model issue

* refactor code
This commit is contained in:
Ramzi Maalej 2019-03-20 03:12:00 -04:00 committed by William Cheng
parent 546a230c73
commit 3100afce26
15 changed files with 46 additions and 38 deletions

View File

@ -86,10 +86,9 @@ public class ConfigHelp implements Runnable {
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
out.getParentFile().mkdirs(); out.getParentFile().mkdirs();
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8)); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8))) {
writer.write(sb.toString());
writer.write(sb.toString()); }
writer.close();
} else { } else {
System.out.print(sb.toString()); System.out.print(sb.toString());
} }

View File

@ -192,7 +192,7 @@ public class Generator {
return outputFolder; return outputFolder;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return null; throw new RuntimeException("Cannot access tmp folder");
} }
} }
} }

View File

@ -62,17 +62,20 @@ public abstract class AbstractGenerator {
throw new RuntimeException("can't load template " + name); throw new RuntimeException("can't load template " + name);
} }
@SuppressWarnings("squid:S2095")
// ignored rule as used in the CLI and it's required to return a reader
public Reader getTemplateReader(String name) { public Reader getTemplateReader(String name) {
InputStream is = null;
try { try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name));
if (is == null) { if (is == null) {
is = new FileInputStream(new File(name)); // May throw but never return a null value is = new FileInputStream(new File(name)); // May throw but never return a null value
} }
return new InputStreamReader(is, "UTF-8"); return new InputStreamReader(is, "UTF-8");
} catch (Exception e) { } catch (FileNotFoundException | UnsupportedEncodingException e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
throw new RuntimeException("can't load template " + name);
} }
throw new RuntimeException("can't load template " + name);
} }
private String buildLibraryFilePath(String dir, String library, String file) { private String buildLibraryFilePath(String dir, String library, String file) {

View File

@ -1270,12 +1270,15 @@ public class DefaultCodegen implements CodegenConfig {
} }
/** /**
* Return property value depending on property type * Return property value depending on property type.
* @param schema property type * @param schema property type
* @return property value * @return property value
*/ */
@SuppressWarnings("squid:S3923")
private String getPropertyDefaultValue(Schema schema) { private String getPropertyDefaultValue(Schema schema) {
//NOSONAR /**
* Although all branches return null, this is left intentionally as examples for new contributors
*/
if (ModelUtils.isBooleanSchema(schema)) { if (ModelUtils.isBooleanSchema(schema)) {
return "null"; return "null";
} else if (ModelUtils.isDateSchema(schema)) { } else if (ModelUtils.isDateSchema(schema)) {
@ -4793,6 +4796,9 @@ public class DefaultCodegen implements CodegenConfig {
} }
private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) { private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) {
if(parameter == null || property == null) {
return;
}
parameter.isNullable = property.isNullable; parameter.isNullable = property.isNullable;
} }

View File

@ -424,14 +424,14 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
private Map<String, List<String>> getAuthScopes(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) { private Map<String, List<String>> getAuthScopes(List<SecurityRequirement> securities, Map<String, SecurityScheme> securitySchemes) {
final Map<String, List<String>> scopes = new HashMap<>(); final Map<String, List<String>> scopes = new HashMap<>();
for (SecurityRequirement requirement : securities) { Optional.ofNullable(securitySchemes).ifPresent(_securitySchemes -> {
for (String key : requirement.keySet()) { for (SecurityRequirement requirement : securities) {
SecurityScheme securityScheme = securitySchemes.get(key); for (String key : requirement.keySet()) {
if (securityScheme != null) { Optional.ofNullable(securitySchemes.get(key))
scopes.put(key, requirement.get(key)); .ifPresent(securityScheme -> scopes.put(key, requirement.get(key)));
} }
} }
} });
return scopes; return scopes;
} }
@ -618,7 +618,7 @@ abstract public class AbstractAdaCodegen extends DefaultCodegen implements Codeg
* Collect the scopes to generate a unique identifier for each of them. * Collect the scopes to generate a unique identifier for each of them.
* *
* @param authMethods the auth methods with their scopes. * @param authMethods the auth methods with their scopes.
* @param scopes the optional auth methods and scopes required by an operation * @param scopes the optional auth methods and scopes required by an operation
* @return the authMethods to be used by the operation with its required scopes. * @return the authMethods to be used by the operation with its required scopes.
*/ */
private List<CodegenSecurity> postProcessAuthMethod(List<CodegenSecurity> authMethods, Map<String, List<String>> scopes) { private List<CodegenSecurity> postProcessAuthMethod(List<CodegenSecurity> authMethods, Map<String, List<String>> scopes) {

View File

@ -75,10 +75,10 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
public String sanitizeName(String name) { public String sanitizeName(String name) {
name = super.sanitizeName(name); name = super.sanitizeName(name);
if (name.contains("__")) { // Preventing namespacing if (name.contains("__")) { // Preventing namespacing
name.replaceAll("__", "_"); name = name.replaceAll("__", "_");
} }
if (name.matches("^\\d.*")) { // Prevent named credentials with leading number if (name.matches("^\\d.*")) { // Prevent named credentials with leading number
name.replaceAll("^\\d.*", ""); name = name.replaceAll("^\\d.*", "");
} }
return name; return name;
} }
@ -293,7 +293,7 @@ public abstract class AbstractApexCodegen extends DefaultCodegen implements Code
} }
} else if (Boolean.TRUE.equals(p.isString)) { } else if (Boolean.TRUE.equals(p.isString)) {
p.example = "'" + p.example + "'"; p.example = "'" + p.example + "'";
} else if ("".equals(p.example) || p.example == null && p.dataType != "Object") { } else if ("".equals(p.example) || p.example == null && "Object".equals(p.dataType)) {
// Get an example object from the generated model // Get an example object from the generated model
if (!isReservedWord(p.dataType.toLowerCase(Locale.ROOT))) { if (!isReservedWord(p.dataType.toLowerCase(Locale.ROOT))) {
p.example = p.dataType + ".getExample()"; p.example = p.dataType + ".getExample()";

View File

@ -540,7 +540,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
} }
for (final CodegenProperty property : codegenModel.readWriteVars) { for (final CodegenProperty property : codegenModel.readWriteVars) {
if (property.defaultValue == null && property.baseName.equals(parentCodegenModel.discriminator)) { if (property.defaultValue == null && property.baseName.equals(parentCodegenModel.discriminator.getPropertyName())) {
property.defaultValue = "\"" + name + "\""; property.defaultValue = "\"" + name + "\"";
} }
} }

View File

@ -243,7 +243,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen {
} }
for (final CodegenProperty property : codegenModel.readWriteVars) { for (final CodegenProperty property : codegenModel.readWriteVars) {
if (property.defaultValue == null && property.baseName.equals(parentCodegenModel.discriminator)) { if (property.defaultValue == null && property.baseName.equals(parentCodegenModel.discriminator.getPropertyName())) {
property.defaultValue = "\"" + name + "\""; property.defaultValue = "\"" + name + "\"";
} }
} }

View File

@ -584,7 +584,7 @@ public class ElmClientCodegen extends DefaultCodegen implements CodegenConfig {
} }
String mapResult = ""; String mapResult = "";
if (maybeMapResult != null) { if (maybeMapResult != null) {
if (mapFn == "") { if ("".equals(mapFn)) {
mapResult = maybeMapResult; mapResult = maybeMapResult;
} else { } else {
mapResult = maybeMapResult + (param.required ? " <|" : " <<"); mapResult = maybeMapResult + (param.required ? " <|" : " <<");

View File

@ -848,17 +848,17 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
if (ModelUtils.isArraySchema(model)) { if (ModelUtils.isArraySchema(model)) {
ArraySchema am = (ArraySchema) model; ArraySchema am = (ArraySchema) model;
if (am.getItems() != null) { if (codegenModel != null && am.getItems() != null) {
codegenModel.getVendorExtensions().put("x-isArray", true); codegenModel.getVendorExtensions().put("x-isArray", true);
codegenModel.getVendorExtensions().put("x-itemType", getSchemaType(am.getItems())); codegenModel.getVendorExtensions().put("x-itemType", getSchemaType(am.getItems()));
} }
} else if (ModelUtils.isMapSchema(model)) { } else if (ModelUtils.isMapSchema(model)) {
if (ModelUtils.getAdditionalProperties(model) != null) { if (codegenModel != null && ModelUtils.getAdditionalProperties(model) != null) {
codegenModel.getVendorExtensions().put("x-isMap", true); codegenModel.getVendorExtensions().put("x-isMap", true);
codegenModel.getVendorExtensions().put("x-itemType", getSchemaType(ModelUtils.getAdditionalProperties(model))); codegenModel.getVendorExtensions().put("x-itemType", getSchemaType(ModelUtils.getAdditionalProperties(model)));
} else { } else {
String type = model.getType(); String type = model.getType();
if (isPrimitiveType(type)) { if (codegenModel != null && isPrimitiveType(type)) {
codegenModel.vendorExtensions.put("x-isPrimitive", true); codegenModel.vendorExtensions.put("x-isPrimitive", true);
} }
} }
@ -1054,11 +1054,13 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo
} }
} }
for (CodegenProperty var : cm.vars) { for (CodegenProperty var : cm.vars) {
if (var == lastRequired) { Optional.ofNullable(lastRequired).ifPresent(_lastRequired -> {
var.vendorExtensions.put("x-codegen-hasMoreRequired", false); if (var == _lastRequired) {
} else if (var.required) { var.vendorExtensions.put("x-codegen-hasMoreRequired", false);
var.vendorExtensions.put("x-codegen-hasMoreRequired", true); } else if (var.required) {
} var.vendorExtensions.put("x-codegen-hasMoreRequired", true);
}
});
} }
} }
return objs; return objs;

View File

@ -32,7 +32,7 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.dashize; import static org.openapitools.codegen.utils.StringUtils.dashize;
public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCodegen { public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT); private final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
public static final String NPM_NAME = "npmName"; public static final String NPM_NAME = "npmName";
public static final String NPM_VERSION = "npmVersion"; public static final String NPM_VERSION = "npmVersion";

View File

@ -327,7 +327,7 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme
for (String token: pathname.substring(1).split("/")) { for (String token: pathname.substring(1).split("/")) {
if (token.startsWith("{")) { if (token.startsWith("{")) {
String snake_case_token = "{" + this.toParamName(token.substring(1, token.length()-1)) + "}"; String snake_case_token = "{" + this.toParamName(token.substring(1, token.length()-1)) + "}";
if(token != snake_case_token) { if(!token.equals(snake_case_token)) {
token = snake_case_token; token = snake_case_token;
} }
} }

View File

@ -36,7 +36,6 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { public class RubyOnRailsServerCodegen extends AbstractRubyCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(RubyOnRailsServerCodegen.class);
private static final SimpleDateFormat MIGRATE_FILE_NAME_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ROOT);
protected String gemName; protected String gemName;
protected String moduleName; protected String moduleName;

View File

@ -1012,10 +1012,10 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig {
if (bound < 0) { if (bound < 0) {
throw new RuntimeException("Unsigned bound is negative: " + bound); throw new RuntimeException("Unsigned bound is negative: " + bound);
} }
return 65 - Long.numberOfLeadingZeros(bound >> 1); return 65L - Long.numberOfLeadingZeros(bound >> 1);
} }
return 65 - Long.numberOfLeadingZeros( return 65L - Long.numberOfLeadingZeros(
// signed bounds go from (-n) to (n - 1), i.e. i8 goes from -128 to 127 // signed bounds go from (-n) to (n - 1), i.e. i8 goes from -128 to 127
bound < 0 ? Math.abs(bound) - 1 : bound); bound < 0 ? Math.abs(bound) - 1 : bound);
} }

View File

@ -102,7 +102,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
importMapping.put("DateTime", "org.joda.time.DateTime"); importMapping.put("DateTime", "org.joda.time.DateTime");
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<>();
typeMapping.put("array", "Seq"); typeMapping.put("array", "Seq");
typeMapping.put("set", "Set"); typeMapping.put("set", "Set");
typeMapping.put("boolean", "Boolean"); typeMapping.put("boolean", "Boolean");
@ -114,7 +114,6 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code
typeMapping.put("byte", "Byte"); typeMapping.put("byte", "Byte");
typeMapping.put("short", "Short"); typeMapping.put("short", "Short");
typeMapping.put("char", "Char"); typeMapping.put("char", "Char");
typeMapping.put("long", "Long");
typeMapping.put("double", "Double"); typeMapping.put("double", "Double");
typeMapping.put("object", "Any"); typeMapping.put("object", "Any");
typeMapping.put("file", "File"); typeMapping.put("file", "File");