[github-278] Resolve all SpotBugs P1 issues in Main and Test. Thanks to Andreas Reichel. This closes #278

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1895016 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2021-11-14 10:18:40 +00:00
parent 20c0ac1637
commit 8365ee1611
34 changed files with 110 additions and 104 deletions

View File

@ -18,6 +18,13 @@
package org.apache.poi.examples.hssf.usermodel;
/* Placeholder - this is now handled in the Common SS example **/
import org.apache.poi.util.Removal;
/**
* Placeholder Class - this is now handled in the Common SS example
* @deprecated in 5.1.0 - use {@link org.apache.poi.examples.ss.AddDimensionedImage}
*/
@Removal(version="6.0.0")
@Deprecated
public class AddDimensionedImage extends org.apache.poi.examples.ss.AddDimensionedImage {
}

View File

@ -22,18 +22,19 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.apache.poi.ss.usermodel.Workbook;
public class MockExcelAntWorkbookHandler implements IExcelAntWorkbookHandler {
public static boolean executed;
public static Workbook workbook;
public boolean executed = false;
public Workbook workbook = null;
public final static MockExcelAntWorkbookHandler instance = new MockExcelAntWorkbookHandler();
@Override
public void setWorkbook(Workbook workbook) {
MockExcelAntWorkbookHandler.workbook = workbook;
instance.workbook = workbook;
}
@Override
public void execute() {
executed = true;
assertNotNull(workbook);
instance.executed = true;
assertNotNull(instance.workbook);
}
}

View File

@ -312,8 +312,8 @@ public class TestBuildFile {
assertLogContaining("Using input file: " + TestBuildFile.getDataDir() + "/spreadsheet/excelant.xls");
assertLogContaining("Succeeded when evaluating 'MortgageCalculator'!$B$4.");
assertNotNull(MockExcelAntWorkbookHandler.workbook, "The workbook should have been passed to the handler");
assertTrue(MockExcelAntWorkbookHandler.executed, "The handler should have been executed");
assertNotNull(MockExcelAntWorkbookHandler.instance.workbook, "The workbook should have been passed to the handler");
assertTrue(MockExcelAntWorkbookHandler.instance.executed, "The handler should have been executed");
}
@Test

View File

@ -24,7 +24,6 @@ import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Enumeration;
import javax.crypto.Cipher;
@ -44,6 +43,7 @@ import org.apache.poi.poifs.crypt.CipherAlgorithm;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.util.Beta;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
/**
@ -106,10 +106,9 @@ public final class AesZipFileZipEntrySource implements ZipEntrySource {
public static AesZipFileZipEntrySource createZipEntrySource(InputStream is) throws IOException {
// generate session key
SecureRandom sr = new SecureRandom();
byte[] ivBytes = new byte[16], keyBytes = new byte[16];
sr.nextBytes(ivBytes);
sr.nextBytes(keyBytes);
RandomSingleton.getInstance().nextBytes(ivBytes);
RandomSingleton.getInstance().nextBytes(keyBytes);
final File tmpFile = TempFile.createTempFile("protectedXlsx", ".zip");
copyToFile(is, tmpFile, keyBytes, ivBytes);
IOUtils.closeQuietly(is);

View File

@ -25,7 +25,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
@ -39,6 +38,7 @@ import org.apache.poi.poifs.crypt.ChainingMode;
import org.apache.poi.poifs.crypt.CipherAlgorithm;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.util.Beta;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
/**
@ -46,8 +46,8 @@ import org.apache.poi.util.TempFile;
*/
@Beta
public class EncryptedTempData {
private static Logger LOG = LogManager.getLogger(EncryptedTempData.class);
private static final Logger LOG = LogManager.getLogger(EncryptedTempData.class);
private static final CipherAlgorithm cipherAlgorithm = CipherAlgorithm.aes128;
private static final String PADDING = "PKCS5Padding";
private final SecretKeySpec skeySpec;
@ -56,11 +56,10 @@ public class EncryptedTempData {
private CountingOutputStream outputStream;
public EncryptedTempData() throws IOException {
SecureRandom sr = new SecureRandom();
ivBytes = new byte[16];
byte[] keyBytes = new byte[16];
sr.nextBytes(ivBytes);
sr.nextBytes(keyBytes);
RandomSingleton.getInstance().nextBytes(ivBytes);
RandomSingleton.getInstance().nextBytes(keyBytes);
skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId);
tempFile = TempFile.createTempFile("poi-temp-data", ".tmp");
}

View File

@ -24,7 +24,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
@ -35,6 +34,7 @@ import org.apache.poi.poifs.crypt.ChainingMode;
import org.apache.poi.poifs.crypt.CipherAlgorithm;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.util.Beta;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.xssf.streaming.SheetDataWriter;
@Beta
@ -49,11 +49,10 @@ public class SheetDataWriterWithDecorator extends SheetDataWriter {
void init() {
if(skeySpec == null) {
SecureRandom sr = new SecureRandom();
ivBytes = new byte[16];
byte[] keyBytes = new byte[16];
sr.nextBytes(ivBytes);
sr.nextBytes(keyBytes);
RandomSingleton.getInstance().nextBytes(ivBytes);
RandomSingleton.getInstance().nextBytes(keyBytes);
skeySpec = new SecretKeySpec(keyBytes, cipherAlgorithm.jceId);
}
}

View File

@ -46,7 +46,7 @@ public class XDDFGradientFillProperties implements XDDFFillProperties {
if (props.isSetRotWithShape()) {
return props.getRotWithShape();
} else {
return null;
return false;
}
}

View File

@ -59,7 +59,7 @@ public class XDDFLinearShadeProperties {
if (props.isSetScaled()) {
return props.getScaled();
} else {
return null;
return false;
}
}

View File

@ -58,7 +58,7 @@ public class XDDFPictureFillProperties implements XDDFFillProperties {
if (props.isSetRotWithShape()) {
return props.getRotWithShape();
} else {
return null;
return false;
}
}

View File

@ -191,7 +191,7 @@ public class XDDFLine3DChartData extends XDDFChartData {
if (series.isSetSmooth()) {
return series.getSmooth().getVal();
} else {
return null;
return false;
}
}

View File

@ -174,7 +174,7 @@ public class XDDFLineChartData extends XDDFChartData {
if (series.isSetSmooth()) {
return series.getSmooth().getVal();
} else {
return null;
return false;
}
}

View File

@ -144,7 +144,7 @@ public class XDDFScatterChartData extends XDDFChartData {
if (series.isSetSmooth()) {
return series.getSmooth().getVal();
} else {
return null;
return false;
}
}

View File

@ -82,7 +82,7 @@ public class XDDFSurface3DChartData extends XDDFChartData {
if (chart.isSetWireframe()) {
return chart.getWireframe().getVal();
} else {
return null;
return false;
}
}

View File

@ -82,7 +82,7 @@ public class XDDFSurfaceChartData extends XDDFChartData {
if (chart.isSetWireframe()) {
return chart.getWireframe().getVal();
} else {
return null;
return false;
}
}

View File

@ -60,7 +60,7 @@ public class XDDFBodyProperties {
if (props.isSetAnchorCtr()) {
return props.getAnchorCtr();
} else {
return null;
return false;
}
}
@ -216,7 +216,7 @@ public class XDDFBodyProperties {
if (props.isSetRtlCol()) {
return props.getRtlCol();
} else {
return null;
return false;
}
}

View File

@ -19,7 +19,6 @@
package org.apache.poi.xssf.usermodel.helpers;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Locale;
@ -28,7 +27,9 @@ import javax.xml.namespace.QName;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.crypt.temp.EncryptedTempData;
import org.apache.poi.util.Internal;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.StringUtil;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
@ -65,8 +66,7 @@ public final class XSSFPasswordHelper {
cur.insertAttributeWithValue(getAttrName(prefix, "password"),
String.format(Locale.ROOT, "%04X", hash).toUpperCase(Locale.ROOT));
} else {
SecureRandom random = new SecureRandom();
byte[] salt = random.generateSeed(16);
byte[] salt = RandomSingleton.getInstance().generateSeed(16);
// Iterations specifies the number of times the hashing function shall be iteratively run (using each
// iteration's result as the input for the next iteration).

View File

@ -22,7 +22,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Arrays;
import javax.xml.namespace.QName;
@ -33,6 +32,7 @@ import org.apache.poi.ooxml.util.POIXMLUnits;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.util.RandomSingleton;
import org.apache.xmlbeans.XmlOptions;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STAlgClass;
import org.openxmlformats.schemas.officeDocument.x2006.sharedTypes.STAlgType;
@ -46,7 +46,6 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.STDocProtect;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.SettingsDocument;
public class XWPFSettings extends POIXMLDocumentPart {
private CTSettings ctSettings;
/**
@ -258,8 +257,7 @@ public class XWPFSettings extends POIXMLDocumentPart {
}
SecureRandom random = new SecureRandom();
byte[] salt = random.generateSeed(16);
byte[] salt = RandomSingleton.getInstance().generateSeed(16);
// Iterations specifies the number of times the hashing function shall be iteratively run (using each
// iteration's result as the input for the next iteration).

View File

@ -40,7 +40,6 @@ import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
@ -57,6 +56,7 @@ import java.util.stream.Stream;
import org.apache.poi.poifs.crypt.CryptoFunctions;
import org.apache.poi.poifs.storage.RawDataUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.RandomSingleton;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.ocsp.OCSPObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
@ -119,7 +119,6 @@ public class DummyKeystore {
}
}
private static final SecureRandom RANDOM = new SecureRandom();
private static final String DUMMY_ALIAS = "Test";
private static final String DUMMY_PASS = "test";
@ -187,7 +186,7 @@ public class DummyKeystore {
public KeyCertPair addEntry(String keyAlias, String keyPass, int keySize, int expiryInMonths) throws GeneralSecurityException, IOException, OperatorCreationException {
if (!keystore.isKeyEntry(keyAlias)) {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), RANDOM);
keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), RandomSingleton.getInstance());
KeyPair pair = keyPairGenerator.generateKeyPair();
Date notBefore = new Date();
@ -262,7 +261,7 @@ public class DummyKeystore {
X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(
issuerName
, new BigInteger(128, new SecureRandom())
, new BigInteger(128, RandomSingleton.getInstance())
, notBefore
, notAfter
, new X500Name(subjectDn)

View File

@ -75,9 +75,9 @@ class TestIdentifierManager {
@Test
void testReserveNew() {
IdentifierManager manager = new IdentifierManager(10L,12L);
assertSame(10L,manager.reserveNew());
assertSame(11L,manager.reserveNew());
assertSame(12L,manager.reserveNew());
assertEquals(10L,manager.reserveNew());
assertEquals(11L,manager.reserveNew());
assertEquals(12L,manager.reserveNew());
assertThrows(IllegalStateException.class, manager::reserveNew);
}

View File

@ -31,11 +31,9 @@ import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import org.apache.poi.sl.draw.DrawTableShape;
import org.apache.poi.sl.usermodel.ShapeType;
@ -44,6 +42,7 @@ import org.apache.poi.sl.usermodel.StrokeStyle;
import org.apache.poi.sl.usermodel.TableCell.BorderEdge;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.sl.usermodel.VerticalAlignment;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
import org.apache.poi.xslf.XSLFTestDataSamples;
import org.apache.poi.xslf.util.PPTX2PNG;
@ -143,17 +142,17 @@ class TestXSLFTable {
String[] names = { "car", "rubber duckie", "phone", "gadget" };
String[] desc = { "new", "used", "untouched" };
Random r = new Random();
for (int row=1; row<=rows; row++) {
String[] line = new String[header.length];
line[0] = Integer.toString(row);
line[1] = Integer.toString(r.nextInt(1000));
line[2] = names[r.nextInt(names.length)];
line[3] = "The "+desc[r.nextInt(desc.length)]+" "+line[2]+" in "+(2017+row);
line[4] = "$"+r.nextInt(50000);
line[5] = r.nextInt(100)+"%";
line[6] = "$"+r.nextInt(50000);
line[1] = Integer.toString(RandomSingleton.getInstance().nextInt(1000));
line[2] = names[RandomSingleton.getInstance().nextInt(names.length)];
line[3] = "The "+desc[RandomSingleton.getInstance().nextInt(desc.length)]+" "+line[2]+" in "+(2017+row);
line[4] = "$"+RandomSingleton.getInstance().nextInt(50000);
line[5] = RandomSingleton.getInstance().nextInt(100)+"%";
line[6] = "$"+RandomSingleton.getInstance().nextInt(50000);
System.arraycopy(line, 0, data[row], 0, header.length);
}
@ -311,7 +310,7 @@ class TestXSLFTable {
tc0.setText("bla bla bla bla");
tab.setColumnWidth(0, 50);
// usually text height == 88, but font rendering is plattform dependent
// usually text height == 88, but font rendering is platform dependent
// so we use something more reliable
assertTrue(tc0.getTextHeight() > 50);
assertEquals(0, tc0.getLineWidth(), 0);

View File

@ -366,9 +366,19 @@ public final class TestSXSSFWorkbook extends BaseTestXWorkbook {
if (i == 0) {
populateWorkbook(wb);
} else {
System.gc();
System.gc();
System.gc();
/*
Code explicitly invokes garbage collection. Except for specific use in benchmarking,
this is very dubious.
In the past, situations where people have explicitly invoked the garbage collector in
routines such as close or finalize methods has led to huge performance black holes.
Garbage collection can be expensive. Any situation that forces hundreds or thousands
of garbage collections will bring the machine to a crawl.
*/
//System.gc();
//System.gc();
//System.gc();
}
wb.write(outSteam);

View File

@ -34,7 +34,6 @@ import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
@ -53,6 +52,7 @@ import org.apache.poi.sl.image.ImageHeaderEMF;
import org.apache.poi.sl.image.ImageHeaderPICT;
import org.apache.poi.sl.image.ImageHeaderWMF;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.Units;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@ -497,10 +497,9 @@ public final class TestPictures {
originalOffsets = ppt1.getPictureData().stream().mapToInt(HSLFPictureData::getOffset).toArray();
originalNumberOfRecords = ppt1.getPictureData().get(0).bStore.getChildCount();
Random random = new Random();
for (HSLFPictureData picture : ppt1.getPictureData()) {
// Bound is arbitrary and irrelevant to the test.
picture.bse.setOffset(random.nextInt(500_000));
picture.bse.setOffset(RandomSingleton.getInstance().nextInt(500_000));
}
try (HSLFSlideShow ppt2 = writeOutAndReadBack(ppt1)) {

View File

@ -31,6 +31,7 @@ import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.GenericRecordUtil;
public abstract class Encryptor implements GenericRecord {
protected static final String DEFAULT_POIFS_ENTRY = Decryptor.DEFAULT_POIFS_ENTRY;
private EncryptionInfo encryptionInfo;
private SecretKey secretKey;

View File

@ -37,8 +37,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.Mac;
@ -62,6 +60,7 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.XMLHelper;
import org.w3c.dom.Document;
@ -81,7 +80,6 @@ public class AgileEncryptor extends Encryptor {
@Override
public void confirmPassword(String password) {
// see [MS-OFFCRYPTO] - 2.3.3 EncryptionVerifier
Random r = new SecureRandom();
AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader();
int blockSize = header.getBlockSize();
int keySize = header.getKeySize()/8;
@ -93,11 +91,13 @@ public class AgileEncryptor extends Encryptor {
, newKeySalt = IOUtils.safelyAllocate(blockSize, maxLen)
, newKeySpec = IOUtils.safelyAllocate(keySize, maxLen)
, newIntegritySalt = IOUtils.safelyAllocate(hashSize, maxLen);
r.nextBytes(newVerifierSalt); // blocksize
r.nextBytes(newVerifier); // blocksize
r.nextBytes(newKeySalt); // blocksize
r.nextBytes(newKeySpec); // keysize
r.nextBytes(newIntegritySalt); // hashsize
// using a java.security.SecureRandom (and avoid allocating a new SecureRandom for each random number needed).
RandomSingleton.getInstance().nextBytes(newVerifierSalt); // blocksize
RandomSingleton.getInstance().nextBytes(newVerifier); // blocksize
RandomSingleton.getInstance().nextBytes(newKeySalt); // blocksize
RandomSingleton.getInstance().nextBytes(newKeySpec); // keysize
RandomSingleton.getInstance().nextBytes(newIntegritySalt); // hashsize
confirmPassword(password, newKeySpec, newKeySalt, newVerifierSalt, newVerifier, newIntegritySalt);
}

View File

@ -22,8 +22,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
@ -38,6 +36,7 @@ import org.apache.poi.poifs.crypt.HashAlgorithm;
import org.apache.poi.poifs.crypt.standard.EncryptionRecord;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.RandomSingleton;
public class BinaryRC4Encryptor extends Encryptor {
@ -52,11 +51,12 @@ public class BinaryRC4Encryptor extends Encryptor {
@Override
public void confirmPassword(String password) {
Random r = new SecureRandom();
byte[] salt = new byte[16];
byte[] verifier = new byte[16];
r.nextBytes(salt);
r.nextBytes(verifier);
// using a java.security.SecureRandom (and avoid allocating a new SecureRandom for each random number needed).
RandomSingleton.getInstance().nextBytes(salt);
RandomSingleton.getInstance().nextBytes(verifier);
confirmPassword(password, null, null, verifier, salt, null);
}

View File

@ -22,10 +22,8 @@ import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
@ -43,6 +41,7 @@ import org.apache.poi.poifs.filesystem.Entry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndian;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.StringUtil;
public class CryptoAPIEncryptor extends Encryptor {
@ -58,11 +57,11 @@ public class CryptoAPIEncryptor extends Encryptor {
@Override
public void confirmPassword(String password) {
Random r = new SecureRandom();
byte[] salt = new byte[16];
byte[] verifier = new byte[16];
r.nextBytes(salt);
r.nextBytes(verifier);
// using a java.security.SecureRandom (and avoid allocating a new SecureRandom for each random number needed).
RandomSingleton.getInstance().nextBytes(salt);
RandomSingleton.getInstance().nextBytes(verifier);
confirmPassword(password, null, null, verifier, salt, null);
}

View File

@ -28,9 +28,7 @@ import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
@ -51,6 +49,7 @@ import org.apache.poi.util.IOUtils;
import org.apache.poi.util.LittleEndianByteArrayOutputStream;
import org.apache.poi.util.LittleEndianConsts;
import org.apache.poi.util.LittleEndianOutputStream;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
public class StandardEncryptor extends Encryptor {
@ -65,10 +64,11 @@ public class StandardEncryptor extends Encryptor {
@Override
public void confirmPassword(String password) {
// see [MS-OFFCRYPTO] - 2.3.3 EncryptionVerifier
Random r = new SecureRandom();
byte[] salt = new byte[16], verifier = new byte[16];
r.nextBytes(salt);
r.nextBytes(verifier);
// using a java.security.SecureRandom (and avoid allocating a new SecureRandom for each random number needed).
RandomSingleton.getInstance().nextBytes(salt);
RandomSingleton.getInstance().nextBytes(verifier);
confirmPassword(password, null, null, salt, verifier, null);
}

View File

@ -244,7 +244,7 @@ public final class CellUtil {
// Copy CellStyle
if (policy.isCopyCellStyle()) {
if (destCell.getSheet().getWorkbook() == srcCell.getSheet().getWorkbook()) {
destCell.setCellStyle(srcCell == null ? null : srcCell.getCellStyle());
destCell.setCellStyle(srcCell.getCellStyle());
} else {
CellStyle srcStyle = srcCell.getCellStyle();
CellStyle destStyle = context == null ? null : context.getMappedStyle(srcStyle);

View File

@ -21,7 +21,6 @@ import static org.apache.poi.util.TempFile.JAVA_IO_TMPDIR;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
/**
* Default implementation of the {@link TempFileCreationStrategy} used by {@link TempFile}:
@ -41,9 +40,6 @@ public class DefaultTempFileCreationStrategy implements TempFileCreationStrategy
/** To keep files after JVM exit, set the <code>-Dpoi.keep.tmp.files</code> JVM property */
public static final String KEEP_FILES = "poi.keep.tmp.files";
/** random number generator to generate unique filenames */
private static final SecureRandom random = new SecureRandom();
/** The directory where the temporary files will be created (<code>null</code> to use the default directory). */
private File dir;
@ -126,7 +122,7 @@ public class DefaultTempFileCreationStrategy implements TempFileCreationStrategy
// Generate a unique new filename
// FIXME: Java 7+: use java.nio.Files#createTempDirectory
final long n = random.nextLong();
final long n = RandomSingleton.getInstance().nextLong();
File newDirectory = new File(dir, prefix + Long.toString(n));
createTempDirectory(newDirectory);

View File

@ -26,7 +26,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Random;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.hpsf.CustomProperties;
@ -36,6 +35,7 @@ import org.apache.poi.hpsf.PropertySetFactory;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.RandomSingleton;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -583,16 +583,19 @@ final class TestMetaDataIPI {
StringBuilder sb = new StringBuilder();
String[] umlaute = { "\u00e4", "\u00fc", "\u00f6", "\u00dc", "$", "\u00d6", "\u00dc",
"\u00c9", "\u00d6", "@", "\u00e7", "&" };
Random rand = new Random(0); // TODO - no Random - tests should be completely deterministic
for (int i = 0; i < 5; i++) {
sb.append(s);
sb.append(' ');
char j = (char) rand.nextInt(220);
// TODO - no Random - tests should be completely deterministic
char j = (char) RandomSingleton.getInstance().nextInt(220);
j += 33;
sb.append('>');
sb.append(Character.valueOf(j));
sb.append('=');
sb.append(umlaute[rand.nextInt(umlaute.length)]);
// TODO - no Random - tests should be completely deterministic
sb.append(umlaute[RandomSingleton.getInstance().nextInt(umlaute.length)]);
sb.append('<');
}
return sb;

View File

@ -32,7 +32,6 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.stream.Stream;
import org.apache.poi.hssf.HSSFTestDataSamples;
@ -48,6 +47,7 @@ import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Test;
@ -414,9 +414,8 @@ final class TestCellStyle {
@Test
void test56563() {
Stream.of("56563a.xls", "56563b.xls").parallel().forEach(fileName -> assertDoesNotThrow(() -> {
Random rand = new Random();
for(int i=0; i<10; i++) {
Thread.sleep(rand.nextInt(300));
Thread.sleep(RandomSingleton.getInstance().nextInt(300));
try (Workbook wb = openSample(fileName)) {
for (Row row : wb.getSheetAt(0)) {
for (Cell cell : row) {

View File

@ -33,9 +33,9 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;
import org.apache.poi.POIDataSamples;
import org.apache.poi.util.RandomSingleton;
import org.apache.poi.util.TempFile;
import org.junit.jupiter.api.Test;
@ -165,12 +165,10 @@ class TestFileMagic {
@Test
void testRandomPatterns() {
Random random = new Random();
// just try to trash the functionality with some byte-patterns
for(int i = 0; i < 1000;i++) {
final byte[] data = new byte[12];
random.nextBytes(data);
RandomSingleton.getInstance().nextBytes(data);
// we cannot check for UNKNOWN as we might hit valid byte-patterns here as well
try {

View File

@ -37,6 +37,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.zip.ZipFile;
@ -304,7 +305,7 @@ public final class ExcelFileFormatDocFunctionExtractor {
@Override
public void endElement(String namespaceURI, String localName, String name) {
String expectedName = _elemNameStack.peek();
if(expectedName != name) {
if(!Objects.equals(name, expectedName)) {
throw new RuntimeException("close tag mismatch");
}
if(matchesPath(0, HEADING_PATH_NAMES)) {

View File

@ -36,7 +36,6 @@ import java.io.PushbackInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.apache.poi.EmptyFileException;
@ -48,7 +47,7 @@ import org.junit.jupiter.api.parallel.Isolated;
@Isolated // this test changes global static BYTE_ARRAY_MAX_OVERRIDE
final class TestIOUtils {
private static File TMP;
private static final long LENGTH = 300 + new Random().nextInt(9000);
private static final long LENGTH = 300 + RandomSingleton.getInstance().nextInt(9000);
@BeforeAll
public static void setUp() throws IOException {