fix resources management (#2229)

* fix resources management

* remove obselete if statement

* throw exception when body is null

* prevent potentional nullpointerexception

* use valueOf instead of constructor

* remove duplicated code

* avoid unclosed resources

* remove redundant key

* fix broken tests

* fix sonar issues

* fix tests

* add Veamly as a company using openAPI generator

* revert back if statement to explicitly express the intention behind it
This commit is contained in:
Ramzi Maalej 2019-03-04 06:27:54 -08:00 committed by William Cheng
parent 0c54286909
commit cc1fe6eebf
17 changed files with 92 additions and 77 deletions

View File

@ -524,6 +524,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Telstra](https://dev.telstra.com) - [Telstra](https://dev.telstra.com)
- [TUI InfoTec GmbH](http://www.tui-infotec.com/) - [TUI InfoTec GmbH](http://www.tui-infotec.com/)
- [unblu inc.](https://www.unblu.com/) - [unblu inc.](https://www.unblu.com/)
- [Veamly](https://www.veamly.com/)
- [Xero](https://www.xero.com/) - [Xero](https://www.xero.com/)
- [Zalando](https://www.zalando.com) - [Zalando](https://www.zalando.com)

View File

@ -51,18 +51,18 @@ public class ZipUtil {
public void compressFiles(List<File> listFiles, String destZipFile) public void compressFiles(List<File> listFiles, String destZipFile)
throws IOException { throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile))) {
for (File file : listFiles) { for (File file : listFiles) {
if (file.isDirectory()) { if (file.isDirectory()) {
addFolderToZip(file, file.getName(), zos); addFolderToZip(file, file.getName(), zos);
} else { } else {
addFileToZip(file, zos); addFileToZip(file, zos);
}
} }
}
zos.flush(); zos.flush();
zos.close(); }
} }
/** /**
@ -84,15 +84,12 @@ public class ZipUtil {
zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytesIn = new byte[BUFFER_SIZE];
long bytesRead = 0; int read;
byte[] bytesIn = new byte[BUFFER_SIZE]; while ((read = bis.read(bytesIn)) != -1) {
int read = 0; zos.write(bytesIn, 0, read);
}
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
bytesRead += read;
} }
zos.closeEntry(); zos.closeEntry();
@ -112,13 +109,12 @@ public class ZipUtil {
IOException { IOException {
zos.putNextEntry(new ZipEntry(file.getName())); zos.putNextEntry(new ZipEntry(file.getName()));
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
byte[] bytesIn = new byte[BUFFER_SIZE];
byte[] bytesIn = new byte[BUFFER_SIZE]; int read;
int read = 0; while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
while ((read = bis.read(bytesIn)) != -1) { }
zos.write(bytesIn, 0, read);
} }
zos.closeEntry(); zos.closeEntry();

View File

@ -40,11 +40,11 @@ public abstract class AbstractGenerator {
File parent = new File(output.getParent()); File parent = new File(output.getParent());
parent.mkdirs(); parent.mkdirs();
} }
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(output), "UTF-8"));
out.write(contents); try (Writer out = new BufferedWriter(new OutputStreamWriter(
out.close(); new FileOutputStream(output), "UTF-8"))) {
out.write(contents);
}
return output; return output;
} }

View File

@ -1251,23 +1251,7 @@ public class DefaultCodegen implements CodegenConfig {
return schema.getExample().toString(); return schema.getExample().toString();
} }
if (ModelUtils.isBooleanSchema(schema)) { return getPropertyDefaultValue(schema);
return "null";
} else if (ModelUtils.isDateSchema(schema)) {
return "null";
} else if (ModelUtils.isDateTimeSchema(schema)) {
return "null";
} else if (ModelUtils.isNumberSchema(schema)) {
return "null";
} else if (ModelUtils.isIntegerSchema(schema)) {
return "null";
} else if (ModelUtils.isStringSchema(schema)) {
return "null";
} else if (ModelUtils.isObjectSchema(schema)) {
return "null";
} else {
return "null";
}
} }
/** /**
@ -1282,6 +1266,16 @@ public class DefaultCodegen implements CodegenConfig {
return schema.getDefault().toString(); return schema.getDefault().toString();
} }
return getPropertyDefaultValue(schema);
}
/**
* Return property value depending on property type
* @param schema property type
* @return property value
*/
private String getPropertyDefaultValue(Schema schema) {
//NOSONAR
if (ModelUtils.isBooleanSchema(schema)) { if (ModelUtils.isBooleanSchema(schema)) {
return "null"; return "null";
} else if (ModelUtils.isDateSchema(schema)) { } else if (ModelUtils.isDateSchema(schema)) {
@ -4506,6 +4500,7 @@ public class DefaultCodegen implements CodegenConfig {
public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) { public CodegenParameter fromRequestBody(RequestBody body, Set<String> imports, String bodyParameterName) {
if (body == null) { if (body == null) {
LOGGER.error("body in fromRequestBody cannot be null!"); LOGGER.error("body in fromRequestBody cannot be null!");
throw new RuntimeException("body in fromRequestBody cannot be null!");
} }
CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER);
codegenParameter.baseName = "UNKNOWN_BASE_NAME"; codegenParameter.baseName = "UNKNOWN_BASE_NAME";

View File

@ -1,5 +1,6 @@
package org.openapitools.codegen; package org.openapitools.codegen;
import java.util.Optional;
import java.util.Set; import java.util.Set;
public class SpecValidationException extends RuntimeException { public class SpecValidationException extends RuntimeException {
@ -105,28 +106,28 @@ public class SpecValidationException extends RuntimeException {
@Override @Override
public String getMessage() { public String getMessage() {
int errorCount = 0; int errorCount = 0;
if (errors != null) { if (errors != null) errorCount = errors.size();
errorCount = errors.size();
}
int warningCount = 0; int warningCount = 0;
if (warnings != null) { if (warnings != null) warningCount = warnings.size();
warningCount = warnings.size();
}
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(System.lineSeparator()) sb.append(System.lineSeparator())
.append("Errors: ") .append("Errors: ")
.append(System.lineSeparator()); .append(System.lineSeparator());
errors.forEach(msg ->
sb.append("\t-").append(msg).append(System.lineSeparator())
);
if (!warnings.isEmpty()) { Optional.ofNullable(errors).ifPresent(_errors -> {
for (String msg : errors) {
sb.append("\t-").append(msg).append(System.lineSeparator());
}
});
Optional.ofNullable(warnings).filter(warnings -> !warnings.isEmpty()).ifPresent(_errors -> {
sb.append("Warnings: ").append(System.lineSeparator()); sb.append("Warnings: ").append(System.lineSeparator());
warnings.forEach(msg -> for (String msg : errors) {
sb.append("\t-").append(msg).append(System.lineSeparator()) sb.append("\t-").append(msg).append(System.lineSeparator());
); }
} });
return super.getMessage() + " | " + return super.getMessage() + " | " +
"Error count: " + errorCount + ", Warning count: " + warningCount + sb.toString(); "Error count: " + errorCount + ", Warning count: " + warningCount + sb.toString();
} }

View File

@ -254,12 +254,12 @@ public class ExampleGenerator {
} else if (ModelUtils.isDateTimeSchema(property)) { } else if (ModelUtils.isDateTimeSchema(property)) {
return "2000-01-23T04:56:07.000+00:00"; return "2000-01-23T04:56:07.000+00:00";
} else if (ModelUtils.isNumberSchema(property)) { } else if (ModelUtils.isNumberSchema(property)) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue(); Double min = getPropertyValue(property.getMinimum());
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue(); Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isFloatSchema(property)) { // float if (ModelUtils.isFloatSchema(property)) { // float
return (float) randomNumber(min, max); return (float) randomNumber(min, max);
} else if (ModelUtils.isDoubleSchema(property)) { // decimal/double } else if (ModelUtils.isDoubleSchema(property)) { // decimal/double
return new BigDecimal(randomNumber(min, max)); return BigDecimal.valueOf(randomNumber(min, max));
} else { // no format defined } else { // no format defined
return randomNumber(min, max); return randomNumber(min, max);
} }
@ -267,8 +267,8 @@ public class ExampleGenerator {
return ""; // TODO return ""; // TODO
} else if (ModelUtils.isIntegerSchema(property)) { } else if (ModelUtils.isIntegerSchema(property)) {
Double min = property.getMinimum() == null ? null : property.getMinimum().doubleValue(); Double min = getPropertyValue(property.getMinimum());
Double max = property.getMaximum() == null ? null : property.getMaximum().doubleValue(); Double max = getPropertyValue(property.getMaximum());
if (ModelUtils.isLongSchema(property)) { if (ModelUtils.isLongSchema(property)) {
return (long) randomNumber(min, max); return (long) randomNumber(min, max);
} }
@ -319,6 +319,10 @@ public class ExampleGenerator {
return ""; return "";
} }
private Double getPropertyValue(BigDecimal propertyValue) {
return propertyValue == null ? null : propertyValue.doubleValue();
}
private double randomNumber(Double min, Double max) { private double randomNumber(Double min, Double max) {
if (min != null && max != null) { if (min != null && max != null) {
double range = max - min; double range = max - min;

View File

@ -28,6 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@ -38,6 +39,8 @@ import static org.openapitools.codegen.utils.StringUtils.underscore;
public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
protected final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value"; private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static final String UNDEFINED_VALUE = "undefined"; private static final String UNDEFINED_VALUE = "undefined";

View File

@ -78,7 +78,7 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod
importMapping.put("DateTime", "org.joda.time.DateTime"); importMapping.put("DateTime", "org.joda.time.DateTime");
importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer"); importMapping.put("ListBuffer", "scala.collection.mutable.ListBuffer");
typeMapping = new HashMap<String, String>(); typeMapping = new HashMap<>();
typeMapping.put("Integer", "Int"); typeMapping.put("Integer", "Int");
typeMapping.put("enum", "NSString"); typeMapping.put("enum", "NSString");
typeMapping.put("array", "Seq"); typeMapping.put("array", "Seq");
@ -91,7 +91,6 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod
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");

View File

@ -34,8 +34,6 @@ import static org.openapitools.codegen.utils.StringUtils.*;
public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptAngularClientCodegen.class);
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$"; private static String CLASS_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9]*$";
private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$"; private static String FILE_NAME_SUFFIX_PATTERN = "^[a-zA-Z0-9.-]*$";

View File

@ -30,7 +30,6 @@ import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodegen {
private static 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

@ -31,7 +31,6 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen {
private static 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

@ -31,8 +31,6 @@ import java.util.*;
import static org.openapitools.codegen.utils.StringUtils.camelize; import static org.openapitools.codegen.utils.StringUtils.camelize;
public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCodegen {
private static final SimpleDateFormat SNAPSHOT_SUFFIX_FORMAT = new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT);
private static final String X_DISCRIMINATOR_TYPE = "x-discriminator-value";
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

@ -33,7 +33,6 @@ import java.util.Locale;
public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptJqueryClientCodegen.class);
private static 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

@ -32,7 +32,6 @@ import static org.openapitools.codegen.utils.StringUtils.camelize;
public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class); private static final Logger LOGGER = LoggerFactory.getLogger(TypeScriptNodeClientCodegen.class);
private static 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

@ -32,7 +32,6 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen { public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen {
private static 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

@ -38,7 +38,7 @@ import java.util.stream.Collectors;
public class DefaultCodegenTest { public class DefaultCodegenTest {
@Test @Test
public void testHasBodyParameter() throws Exception { public void testHasBodyParameter() {
final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet"); final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");
Operation pingOperation = new Operation() Operation pingOperation = new Operation()
.responses( .responses(
@ -61,6 +61,13 @@ public class DefaultCodegenTest {
Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true); Assert.assertEquals(codegen.hasBodyParameter(openAPI, createOperation), true);
} }
@Test(expectedExceptions = RuntimeException.class)
public void testParameterEmptyDescription() {
DefaultCodegen codegen = new DefaultCodegen();
codegen.fromRequestBody(null, new HashSet<>(), null);
}
@Test @Test
public void testGetConsumesInfoAndGetProducesInfo() throws Exception { public void testGetConsumesInfoAndGetProducesInfo() throws Exception {
final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet"); final Schema refSchema = new Schema<>().$ref("#/components/schemas/Pet");

View File

@ -0,0 +1,18 @@
package org.openapitools.codegen;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SpecValidationExceptionTest {
@Test
public void shouldGetDefaultMessage() {
SpecValidationException specValidationException = new SpecValidationException();
String expectedResult = new StringBuffer("null | Error count: 0, Warning count: 0")
.append(System.lineSeparator()).append("Errors: ")
.append(System.lineSeparator()).toString();
Assert.assertEquals(specValidationException.getMessage(), expectedResult);
}
}