Skip to content

Commit

Permalink
CodeQL fixes (#43)
Browse files Browse the repository at this point in the history
* Add fixes for CodeQL scanning
* Check NumberFormatException
  • Loading branch information
ppouchin authored Dec 8, 2022
1 parent f3860bf commit 40d01e4
Show file tree
Hide file tree
Showing 7 changed files with 157 additions and 44 deletions.
54 changes: 48 additions & 6 deletions src/main/java/fr/igred/omero/annotations/TableWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,46 @@ public TableWrapper(Client client, ResultsTable results, Long imageId, List<? ex
}


/**
* Safely converts a String to an Integer, returning null if it fails.
*
* @param s The string.
*
* @return The integer value represented by s, null if not applicable.
*/
private static Integer safeParseInt(String s) {
Integer i = null;
if (s != null) {
try {
i = Integer.parseInt(s);
} catch (NumberFormatException ignored) {
// DO NOTHING
}
}
return i;
}


/**
* Safely converts a String to a Long, returning null if it fails.
*
* @param s The string.
*
* @return The integer value represented by s, null if not applicable.
*/
private static Long safeParseLong(String s) {
Long l = null;
if (s != null) {
try {
l = Long.parseLong(s);
} catch (NumberFormatException ignored) {
// DO NOTHING
}
}
return l;
}


/**
* Checks if a column from a {@link ResultsTable} is numeric or not.
*
Expand Down Expand Up @@ -318,11 +358,12 @@ private static ROIData[] createROIColumn(ResultsTable results,
Map<Integer, ROIData> index2roi = new HashMap<>(ijRois.size());
Map<String, ROIData> roiName2roi = new HashMap<>(ijRois.size());
for (Roi ijRoi : ijRois) {
String index = ijRoi.getProperty(roiProperty);
String id = ijRoi.getProperty(roiIdProperty);
Integer index = safeParseInt(ijRoi.getProperty(roiProperty));
Long id = safeParseLong(ijRoi.getProperty(roiIdProperty));
if (id != null) {
roiName2roi.put(ijRoi.getName(), id2roi.get(Long.parseLong(id)));
if (index != null) index2roi.putIfAbsent(Integer.parseInt(index), id2roi.get(Long.parseLong(id)));
ROIData roi = id2roi.get(id);
roiName2roi.put(ijRoi.getName(), roi);
if (index != null) index2roi.putIfAbsent(index, roi);
}
}

Expand Down Expand Up @@ -702,12 +743,13 @@ public TableData createTable() {
*/
public void saveAs(String path, char delimiter) throws FileNotFoundException, UnsupportedEncodingException {
StringBuilder sb = new StringBuilder(10 * columnCount * rowCount);
File f = new File(path);

File file = new File(path);

String sol = "\"";
String sep = String.format("\"%c\"", delimiter);
String eol = String.format("\"%n");
try (PrintWriter stream = new PrintWriter(f, StandardCharsets.UTF_8.name())) {
try (PrintWriter stream = new PrintWriter(file, StandardCharsets.UTF_8.name())) {
sb.append(sol);
for (int j = 0; j < columnCount; j++) {
sb.append(columns[j].getName());
Expand Down
13 changes: 10 additions & 3 deletions src/main/java/fr/igred/omero/roi/ROIWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,16 @@ public static List<ROIWrapper> fromImageJ(List<? extends ij.gui.Roi> ijRois, Str
for (int i = 0; i < ijRois.size(); i++) {
String value = ijRois.get(i).getProperty(property);
if (value != null && INT_PATTERN.matcher(value).matches()) {
long id = Long.parseLong(value);
rois4D.computeIfAbsent(id, val -> new ROIWrapper());
shape2roi.put(i, rois4D.get(id));
Long id = null;
try {
id = Long.parseLong(value);
} catch (NumberFormatException ignored) {
// DO NOTHING
}
if (id != null) {
rois4D.computeIfAbsent(id, val -> new ROIWrapper());
shape2roi.put(i, rois4D.get(id));
}
} else {
shape2roi.put(i, new ROIWrapper());
}
Expand Down
15 changes: 11 additions & 4 deletions src/test/java/fr/igred/omero/BasicTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.util.Random;
import java.util.logging.Logger;


Expand Down Expand Up @@ -60,10 +61,11 @@ public abstract class BasicTest {

protected static final double DOUBLE_PRECISION = 10.0e-15;

protected static final Random SECURE_RANDOM = new SecureRandom();


protected static File createFile(String filename) throws IOException {
@SuppressWarnings("AccessOfSystemProperties")
String tmpdir = System.getProperty("java.io.tmpdir") + File.separator;
String tmpdir = Files.createTempDirectory(null).toString();

File file = new File(tmpdir + File.separator + filename);
if (!file.createNewFile()) {
Expand All @@ -78,7 +80,7 @@ protected static File createRandomFile(String filename) throws IOException {

File file = createFile(filename);
byte[] array = new byte[size];
new SecureRandom().nextBytes(array);
SECURE_RANDOM.nextBytes(array);
String generatedString = new String(array, StandardCharsets.UTF_8);
try (PrintStream out = new PrintStream(Files.newOutputStream(file.toPath()), false, "UTF-8")) {
out.print(generatedString);
Expand All @@ -88,7 +90,12 @@ protected static File createRandomFile(String filename) throws IOException {


protected static void removeFile(File file) throws IOException {
if (!file.delete()) {
File parent = file.getParentFile();
if (file.delete()) {
if (!parent.delete()) {
logger.warning("\"" + parent.getCanonicalPath() + "\" could not be deleted.");
}
} else {
logger.severe("\"" + file.getCanonicalPath() + "\" could not be deleted.");
}
}
Expand Down
59 changes: 59 additions & 0 deletions src/test/java/fr/igred/omero/annotations/TableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -881,6 +881,65 @@ void testAddRowsFromIJResultsError() throws Exception {
}


@Test
void testNumberFormatException() throws Exception {
ImageWrapper image = client.getImage(IMAGE1.id);

ROIWrapper roi = new ROIWrapper();

roi.setImage(image);

for (int i = 0; i < 4; i++) {
RectangleWrapper rectangle = new RectangleWrapper();
rectangle.setCoordinates(i * 2, i * 2, 10, 10);
rectangle.setZ(i);
rectangle.setT(0);
rectangle.setC(0);

roi.addShape(rectangle);
}

image.saveROI(client, roi);

List<ROIWrapper> rois = image.getROIs(client);
List<Roi> ijRois = ROIWrapper.toImageJ(rois, null);
ijRois.get(0).setProperty(ROIWrapper.IJ_PROPERTY, "tutu");
ijRois.get(1).setProperty(ROIWrapper.IJ_PROPERTY, "tutu");
ijRois.get(2).setProperty(ROIWrapper.IJ_PROPERTY, "tutu");
ijRois.get(3).setProperty(ROIWrapper.ijIDProperty(ROIWrapper.IJ_PROPERTY), "tata");

ResultsTable results = new ResultsTable();
results.incrementCounter();
results.setLabel(image.getName(), 0);
results.setValue("Image", 0, image.getName());
results.setValue(ROIWrapper.IJ_PROPERTY, 0, 1);
results.setValue("Volume", 0, volume1);
results.setValue("Volume Unit", 0, "µm^3");

TableWrapper table = new TableWrapper(client, results, IMAGE1.id, ijRois);

Object[][] data = table.getData();
assertEquals(1, table.getRowCount());
assertEquals(image.getId(), ((DataObject) data[0][0]).getId());
assertEquals(image.getName(), data[1][0]);
assertEquals(image.getName(), data[2][0]);
assertEquals(1.0, data[3][0]);
assertEquals(volume1, (Double) data[4][0], Double.MIN_VALUE);
assertEquals("µm^3", data[5][0]);

image.addTable(client, table);

assertNotNull(table.getFileId());

client.delete(table);

for (ROIWrapper r : rois) {
client.delete(r);
}
assertEquals(0, image.getROIs(client).size());
}


@Test
void testAddRowsFromIJResultsInverted() throws Exception {
ImageWrapper image = client.getImage(IMAGE1.id);
Expand Down
6 changes: 3 additions & 3 deletions src/test/java/fr/igred/omero/repository/DatasetTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ void testCreateDatasetAndDeleteIt2() throws Exception {

DatasetWrapper dataset = new DatasetWrapper("To delete", description);

Long id = project.addDataset(client, dataset).getId();
long id = project.addDataset(client, dataset).getId();

DatasetWrapper checkDataset = client.getDataset(id);
client.delete(checkDataset);
Expand Down Expand Up @@ -320,10 +320,10 @@ void testAddFileDataset() throws Exception {
DatasetWrapper dataset = client.getDataset(DATASET1.id);

File file = createRandomFile("test_dataset.txt");
Long id = dataset.addFile(client, file);
long id = dataset.addFile(client, file);
removeFile(file);
client.deleteFile(id);
assertNotEquals(0L, id.longValue());
assertNotEquals(0L, id);
}


Expand Down
44 changes: 21 additions & 23 deletions src/test/java/fr/igred/omero/repository/ImageTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Files;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Expand All @@ -44,7 +43,6 @@
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
Expand Down Expand Up @@ -273,15 +271,14 @@ void testToImagePlusBound() throws Exception {
int[] zBounds = {0, 2};
int[] tBounds = {0, 2};

Random random = new SecureRandom();
xBounds[0] = random.nextInt(lowXY);
yBounds[0] = random.nextInt(lowXY);
cBounds[0] = random.nextInt(3);
tBounds[0] = random.nextInt(5);
xBounds[1] = random.nextInt(highXY - xBounds[0]) + xBounds[0] + 5;
yBounds[1] = random.nextInt(highXY - yBounds[0]) + yBounds[0] + 5;
cBounds[1] = random.nextInt(3 - cBounds[0]) + cBounds[0] + 2;
tBounds[1] = random.nextInt(5 - tBounds[0]) + tBounds[0] + 2;
xBounds[0] = SECURE_RANDOM.nextInt(lowXY);
yBounds[0] = SECURE_RANDOM.nextInt(lowXY);
cBounds[0] = SECURE_RANDOM.nextInt(3);
tBounds[0] = SECURE_RANDOM.nextInt(5);
xBounds[1] = SECURE_RANDOM.nextInt(highXY - xBounds[0]) + xBounds[0] + 5;
yBounds[1] = SECURE_RANDOM.nextInt(highXY - yBounds[0]) + yBounds[0] + 5;
cBounds[1] = SECURE_RANDOM.nextInt(3 - cBounds[0]) + cBounds[0] + 2;
tBounds[1] = SECURE_RANDOM.nextInt(5 - tBounds[0]) + tBounds[0] + 2;

String fake = "8bit-unsigned&pixelType=uint8&sizeZ=3&sizeC=5&sizeT=7&sizeX=512&sizeY=512.fake";
File fakeFile = createFile(fake);
Expand Down Expand Up @@ -481,18 +478,19 @@ void testAddFileImage() throws Exception {
long id = image.addFile(client, file);

List<FileAnnotationWrapper> files = image.getFileAnnotations(client);
for (FileAnnotationWrapper f : files) {
if (f.getId() == id) {
assertEquals(file.getName(), f.getFileName());
assertEquals("txt", f.getFileFormat());
assertEquals("text/plain", f.getOriginalMimetype());
assertEquals("text/plain", f.getServerFileMimetype());
assertEquals("Plain Text Document", f.getFileKind());
assertEquals(file.getParent() + File.separator, f.getContentAsString());
assertEquals(file.getParent() + File.separator, f.getFilePath());
assertFalse(f.isMovieFile());

File uploadedFile = f.getFile(client, "." + File.separator + "uploaded.txt");
for (FileAnnotationWrapper fileAnn : files) {
if (fileAnn.getId() == id) {
assertEquals(file.getName(), fileAnn.getFileName());
assertEquals("txt", fileAnn.getFileFormat());
assertEquals("text/plain", fileAnn.getOriginalMimetype());
assertEquals("text/plain", fileAnn.getServerFileMimetype());
assertEquals("Plain Text Document", fileAnn.getFileKind());
assertEquals(file.getParent() + File.separator, fileAnn.getContentAsString());
assertEquals(file.getParent() + File.separator, fileAnn.getFilePath());
assertFalse(fileAnn.isMovieFile());

String tmpdir = Files.createTempDirectory(null).toString();
File uploadedFile = fileAnn.getFile(client, tmpdir + File.separator + "uploaded.txt");

List<String> expectedLines = Files.readAllLines(file.toPath());
List<String> lines = Files.readAllLines(uploadedFile.toPath());
Expand Down
10 changes: 5 additions & 5 deletions src/test/java/fr/igred/omero/repository/ProjectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -296,9 +296,9 @@ void testCopyAnnotations() throws Exception {

File file = createRandomFile("test_project.txt");

Long fileId = project1.addFile(client, file);
long fileId = project1.addFile(client, file);
removeFile(file);
assertNotEquals(0L, fileId.longValue());
assertNotEquals(0L, fileId);

TagAnnotationWrapper tag = new TagAnnotationWrapper(client, "CopyTestTag", "Copy annotations");
project1.addTag(client, tag);
Expand Down Expand Up @@ -341,9 +341,9 @@ void testCopyFileAnnotation() throws Exception {

File file = createRandomFile("test_project.txt");

Long fileId = project1.addFile(client, file);
long fileId = project1.addFile(client, file);
removeFile(file);
assertNotEquals(0L, fileId.longValue());
assertNotEquals(0L, fileId);

List<FileAnnotationWrapper> files = project1.getFileAnnotations(client);
assertEquals(1, files.size());
Expand All @@ -356,7 +356,7 @@ void testCopyFileAnnotation() throws Exception {
client.deleteFile(fileId);
client.delete(project2);

assertNotEquals(0L, fileId.longValue());
assertNotEquals(0L, fileId);
}


Expand Down

0 comments on commit 40d01e4

Please sign in to comment.