SurendraKumar Jaiswal
SurendraKumar Jaiswal

Reputation: 192

Sonar issue for printStream constructor as "Remove this use of constructor" for PrintStream(outStream);

I am generating CSR using java code, I have taken the code from online website journaldev.com

public byte[] generateCSR(final String sigAlg, final PublicKey publicKey, final PrivateKey 
privateKey, final String organisationUrl) {

final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(outStream);

final X500Name x500Name = new X500Name("CN=" + organisationUrl);

final Signature signature = Signature.getInstance(sigAlg);

signature.initSign(privateKey);

final PKCS10 pkcs10 = new PKCS10(publicKey);

pkcs10.encodeAndSign(x500Name, signature);
pkcs10.print(printStream);

return outStream.toByteArray();

As you can see that above I have used printStream constructor, which takes ByteArrayOutputStream as a parameter. Because of that sonar is saying not to use this constructor as that constructor will use default charset of the system, Anyone is aware that How can I resolve this?
I have tried as an alternative code :

final Writer writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8);
final OutputStream out = new WriterOutputStream(writer,StandardCharsets.UTF_8);
final PrintStream printStream = new PrintStream(out, Boolean.FALSE, "UTF-8");

This code run, but it return an empty result. can you please help me out with this?

Upvotes: 0

Views: 860

Answers (1)

Stephen C
Stephen C

Reputation: 718758

Assuming that you want to encode as UTF-8, replace

final PrintStream printStream = new PrintStream(outStream);

with this:

final PrintStream printStream = new PrintStream(outStream, true, "UTF-8");

You will also need to catch UnsupportedEncodingException. This exception should never happen (because "UTF-8" is always supported) but you still need to catch it (or declare it) since it is a checked exception.


If you don't want the print stream to autoflush (i.e. the true), you could add

printStream.flush();

or

printStream.close();

before the return. I suspect that the reason you didn't get any output with your clunky attempt at correcting the problem is that the data that pks10.print wrote was not being flushed to the ByteArrayOutputStream.

Upvotes: 3

Related Questions