Use explicit character set in tests (#6150)

This commit is contained in:
Basil Crow 2022-01-07 06:29:39 -08:00 committed by GitHub
parent dd0db180bf
commit 520e114ea1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
46 changed files with 225 additions and 159 deletions

View File

@ -31,6 +31,7 @@ import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.Charset;
import org.junit.jupiter.api.Test;
public class PlainCLIProtocolTest {
@ -67,7 +68,7 @@ public class PlainCLIProtocolTest {
void send() throws IOException {
sendArg("command");
sendStart();
streamStdin().write("hello".getBytes());
streamStdin().write("hello".getBytes(Charset.defaultCharset()));
}
void newop() throws IOException {
@ -123,7 +124,7 @@ public class PlainCLIProtocolTest {
protected void handleClose() {}
void send() throws IOException {
streamStdout().write("goodbye".getBytes());
streamStdout().write("goodbye".getBytes(Charset.defaultCharset()));
sendExit(2);
}
@ -156,9 +157,9 @@ public class PlainCLIProtocolTest {
while (server.stdin.size() == 0) {
Thread.sleep(100);
}
assertEquals("hello", server.stdin.toString());
assertEquals("hello", server.stdin.toString(Charset.defaultCharset().name()));
assertEquals("command", server.arg);
assertEquals("goodbye", client.stdout.toString());
assertEquals("goodbye", client.stdout.toString(Charset.defaultCharset().name()));
assertEquals(2, client.code);
}

View File

@ -58,6 +58,7 @@ import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@ -657,9 +658,9 @@ public class FilePathTest {
when(con.getInputStream()).thenThrow(new ConnectException());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String message = "going ahead";
assertFalse(d.installIfNecessaryFrom(url, new StreamTaskListener(baos), message));
assertFalse(d.installIfNecessaryFrom(url, new StreamTaskListener(baos, Charset.defaultCharset()), message));
verify(con).setIfModifiedSince(123000);
String log = baos.toString();
String log = baos.toString(Charset.defaultCharset().name());
assertFalse(log, log.contains(message));
assertTrue(log, log.contains("504 Gateway Timeout"));
}
@ -701,7 +702,7 @@ public class FilePathTest {
final ZipOutputStream zip = new ZipOutputStream(buf);
zip.putNextEntry(new ZipEntry("abc"));
zip.write("abc".getBytes());
zip.write("abc".getBytes(StandardCharsets.US_ASCII));
zip.close();
return new ByteArrayInputStream(buf.toByteArray());

View File

@ -90,12 +90,12 @@ public class LauncherTest {
@Issue("JENKINS-15733")
@Test public void decorateByEnv() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TaskListener l = new StreamBuildListener(baos);
TaskListener l = new StreamBuildListener(baos, Charset.defaultCharset());
Launcher base = new Launcher.LocalLauncher(l);
EnvVars env = new EnvVars("key1", "val1");
Launcher decorated = base.decorateByEnv(env);
int res = decorated.launch().envs("key2=val2").cmds(Functions.isWindows() ? new String[] {"cmd", "/q", "/c", "echo %key1% %key2%"} : new String[] {"sh", "-c", "echo $key1 $key2"}).stdout(l).join();
String log = baos.toString();
String log = baos.toString(Charset.defaultCharset().name());
assertEquals(log, 0, res);
assertTrue(log, log.contains("val1 val2"));
}
@ -103,7 +103,7 @@ public class LauncherTest {
@Issue("JENKINS-18368")
@Test public void decoratedByEnvMaintainsIsUnix() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
TaskListener listener = new StreamBuildListener(output);
TaskListener listener = new StreamBuildListener(output, Charset.defaultCharset());
Launcher remoteLauncher = new Launcher.RemoteLauncher(listener, FilePath.localChannel, false);
Launcher decorated = remoteLauncher.decorateByEnv(new EnvVars());
assertFalse(decorated.isUnix());
@ -115,7 +115,7 @@ public class LauncherTest {
@Issue("JENKINS-18368")
@Test public void decoratedByPrefixMaintainsIsUnix() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
TaskListener listener = new StreamBuildListener(output);
TaskListener listener = new StreamBuildListener(output, Charset.defaultCharset());
Launcher remoteLauncher = new Launcher.RemoteLauncher(listener, FilePath.localChannel, false);
Launcher decorated = remoteLauncher.decorateByPrefix("test");
assertFalse(decorated.isUnix());

View File

@ -63,7 +63,7 @@ public class PluginManagerTest {
tmp.resolve("output.txt")
);
assertEquals("{other=2.0, stuff=1.2}", new LocalPluginManager(output.getParent().toFile())
.parseRequestedPlugins(new ByteArrayInputStream("<root><stuff plugin='stuff@1.0'><more plugin='other@2.0'><things plugin='stuff@1.2'/></more></stuff></root>".getBytes())).toString());
.parseRequestedPlugins(new ByteArrayInputStream("<root><stuff plugin='stuff@1.0'><more plugin='other@2.0'><things plugin='stuff@1.2'/></more></stuff></root>".getBytes(StandardCharsets.UTF_8))).toString());
}
@Issue("SECURITY-167")
@ -82,7 +82,7 @@ public class PluginManagerTest {
PluginManager pluginManager = new LocalPluginManager(Util.createTempDir());
final IOException ex = assertThrows(IOException.class,
() -> pluginManager.parseRequestedPlugins(new ByteArrayInputStream(evilXML.getBytes())),
() -> pluginManager.parseRequestedPlugins(new ByteArrayInputStream(evilXML.getBytes(StandardCharsets.UTF_8))),
"XML contains an external entity, but no exception was thrown.");
assertThat(ex.getCause(), instanceOf(SAXException.class));
assertThat(ex.getCause().getMessage(), containsString("DOCTYPE is disallowed"));
@ -156,7 +156,7 @@ public class PluginManagerTest {
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(f.toPath()))) {
ZipEntry e = new ZipEntry(manifestPath);
out.putNextEntry(e);
byte[] data = SAMPLE_MANIFEST_FILE.getBytes();
byte[] data = SAMPLE_MANIFEST_FILE.getBytes(StandardCharsets.UTF_8);
out.write(data, 0, data.length);
out.closeEntry();
}

View File

@ -44,6 +44,7 @@ import hudson.util.StreamTaskListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
@ -231,7 +232,7 @@ public class UtilTest {
assumeFalse(Functions.isWindows());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamTaskListener l = new StreamTaskListener(baos);
StreamTaskListener l = new StreamTaskListener(baos, Charset.defaultCharset());
File d = tmp.getRoot();
try {
new FilePath(new File(d, "a")).touch(0);
@ -245,7 +246,7 @@ public class UtilTest {
buf.append((char) ('0' + (i % 10)));
Util.createSymlink(d, buf.toString(), "x", l);
String log = baos.toString();
String log = baos.toString(Charset.defaultCharset().name());
if (log.length() > 0)
System.err.println("log output: " + log);
@ -279,7 +280,7 @@ public class UtilTest {
assumeFalse(Functions.isWindows());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StreamTaskListener l = new StreamTaskListener(baos);
StreamTaskListener l = new StreamTaskListener(baos, Charset.defaultCharset());
File d = tmp.getRoot();
try {
new FilePath(new File(d, "original")).touch(0);

View File

@ -14,11 +14,13 @@ import hudson.model.View;
import hudson.model.ViewTest.CompositeView;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import jenkins.model.Jenkins;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
@ -154,8 +156,11 @@ public class ListJobsCommandTest {
@Override
protected boolean matchesSafely(ByteArrayOutputStream item) {
return item.toString().isEmpty();
try {
return item.toString(command.getClientCharset().name()).isEmpty();
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
@Override
@ -173,9 +178,12 @@ public class ListJobsCommandTest {
@Override
protected boolean matchesSafely(ByteArrayOutputStream item) {
final HashSet<String> jobs = new HashSet<>(
Arrays.asList(item.toString().split(System.getProperty("line.separator")))
);
Set<String> jobs;
try {
jobs = new HashSet<>(Arrays.asList(item.toString(command.getClientCharset().name()).split(System.getProperty("line.separator"))));
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
return new HashSet<>(Arrays.asList(expected)).equals(jobs);
}

View File

@ -32,6 +32,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;
import java.nio.charset.Charset;
import org.apache.commons.io.output.NullOutputStream;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.Issue;
@ -142,8 +143,8 @@ public class ComputerLauncherTest {
private static void assertChecked(String text, String spec) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ComputerLauncher.checkJavaVersion(new PrintStream(os), "bin/java", new BufferedReader(new StringReader(text)));
String logged = os.toString();
ComputerLauncher.checkJavaVersion(new PrintStream(os, false, Charset.defaultCharset().name()), "bin/java", new BufferedReader(new StringReader(text)));
String logged = os.toString(Charset.defaultCharset().name());
assertTrue(logged.contains(Messages.ComputerLauncher_JavaVersionResult("bin/java", spec)), logged);
}
}

View File

@ -61,7 +61,7 @@ public class SecretRewriterTest {
private String encryptOld(String str) throws Exception {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, HistoricalSecrets.getLegacyKey());
return new String(Base64.getEncoder().encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes(StandardCharsets.UTF_8))));
return Base64.getEncoder().encodeToString(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes(StandardCharsets.UTF_8)));
}
private String encryptNew(String str) {

View File

@ -130,7 +130,7 @@ public class SecretTest {
for (String str : new String[] {"Hello world", "", "\u0000unprintable"}) {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, legacy);
String old = new String(Base64.getEncoder().encode(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes(StandardCharsets.UTF_8))));
String old = Base64.getEncoder().encodeToString(cipher.doFinal((str + HistoricalSecrets.MAGIC).getBytes(StandardCharsets.UTF_8)));
Secret s = Secret.fromString(old);
assertEquals("secret by the old key should decrypt", str, s.getPlainText());
assertNotEquals("but when encrypting, ConfidentialKey should be in use", old, s.getEncryptedValue());

View File

@ -8,7 +8,9 @@ import hudson.FilePath;
import hudson.Functions;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
@ -24,7 +26,7 @@ public class RewindableRotatingFileOutputStreamTest {
public void rotation() throws IOException, InterruptedException {
File base = tmp.newFile("test.log");
RewindableRotatingFileOutputStream os = new RewindableRotatingFileOutputStream(base, 3);
PrintWriter w = new PrintWriter(os, true);
PrintWriter w = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8), true);
for (int i = 0; i <= 4; i++) {
w.println("Content" + i);
os.rewind();

View File

@ -21,7 +21,6 @@ import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
@ -29,6 +28,8 @@ import java.lang.reflect.Modifier;
import java.net.HttpURLConnection;
import java.net.IDN;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
@ -336,7 +337,7 @@ public class DomainValidatorTest extends TestCase {
// if the txt file contains entries not found in the html file, try again in a day or two
download(htmlFile, "https://www.iana.org/domains/root/db", timestamp);
BufferedReader br = new BufferedReader(new FileReader(txtFile));
BufferedReader br = Files.newBufferedReader(txtFile.toPath(), StandardCharsets.UTF_8);
String line;
final String header;
line = br.readLine(); // header
@ -437,7 +438,7 @@ public class DomainValidatorTest extends TestCase {
// <td>Ålands landskapsregering</td>
final Pattern comment = Pattern.compile("\\s+<td>([^<]+)</td>");
final BufferedReader br = new BufferedReader(new FileReader(f));
final BufferedReader br = Files.newBufferedReader(f.toPath(), StandardCharsets.UTF_8);
String line;
while ((line = br.readLine()) != null) {
Matcher m = domain.matcher(line);
@ -541,7 +542,7 @@ public class DomainValidatorTest extends TestCase {
BufferedReader in = null;
try {
download(rootCheck, tldurl, 0L);
in = new BufferedReader(new FileReader(rootCheck));
in = Files.newBufferedReader(rootCheck.toPath(), StandardCharsets.UTF_8);
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("This domain is not present in the root zone at this time.")) {

View File

@ -2,6 +2,7 @@ package jenkins.security;
import static org.junit.Assert.assertArrayEquals;
import java.nio.charset.StandardCharsets;
import org.junit.Rule;
import org.junit.Test;
@ -15,13 +16,13 @@ public class CryptoConfidentialKeyTest {
@Test
public void decryptGetsPlainTextBack() throws Exception {
for (String str : new String[] {"Hello world", "", "\u0000"}) {
assertArrayEquals(str.getBytes(), key.decrypt().doFinal(key.encrypt().doFinal(str.getBytes())));
assertArrayEquals(str.getBytes(StandardCharsets.UTF_8), key.decrypt().doFinal(key.encrypt().doFinal(str.getBytes(StandardCharsets.UTF_8))));
}
}
@Test
public void multipleEncryptsAreIdempotent() throws Exception {
byte[] str = "Hello world".getBytes();
byte[] str = "Hello world".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(key.encrypt().doFinal(str), key.encrypt().doFinal(str));
}
@ -29,7 +30,7 @@ public class CryptoConfidentialKeyTest {
public void loadingExistingKey() throws Exception {
CryptoConfidentialKey key2 = new CryptoConfidentialKey("test"); // this will cause the key to be loaded from the disk
for (String str : new String[] {"Hello world", "", "\u0000"}) {
assertArrayEquals(str.getBytes(), key2.decrypt().doFinal(key.encrypt().doFinal(str.getBytes())));
assertArrayEquals(str.getBytes(StandardCharsets.UTF_8), key2.decrypt().doFinal(key.encrypt().doFinal(str.getBytes(StandardCharsets.UTF_8))));
}
}

View File

@ -10,7 +10,7 @@ import static org.junit.Assert.assertTrue;
import hudson.FilePath;
import hudson.Functions;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
@ -30,14 +30,14 @@ public class DefaultConfidentialStoreTest {
// basic roundtrip
String str = "Hello world!";
store.store(key, str.getBytes());
assertEquals(str, new String(store.load(key)));
store.store(key, str.getBytes(StandardCharsets.UTF_8));
assertEquals(str, new String(store.load(key), StandardCharsets.UTF_8));
// data storage should have some stuff
assertTrue(new File(tmp, "test").exists());
assertTrue(new File(tmp, "master.key").exists());
assertThat(FileUtils.readFileToString(new File(tmp, "test"), Charset.defaultCharset()), not(containsString("Hello"))); // the data shouldn't be a plain text, obviously
assertThat(FileUtils.readFileToString(new File(tmp, "test"), StandardCharsets.UTF_8), not(containsString("Hello"))); // the data shouldn't be a plain text, obviously
if (!Functions.isWindows()) {
assertEquals(0700, new FilePath(tmp).mode() & 0777); // should be read only

View File

@ -42,8 +42,9 @@ import static org.mockito.Mockito.mock;
import hudson.Functions;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
@ -454,7 +455,7 @@ public class PathRemoverTest {
private static void touchWithFileName(File... files) throws IOException {
for (File file : files) {
try (FileWriter writer = new FileWriter(file)) {
try (Writer writer = Files.newBufferedWriter(file.toPath(), Charset.defaultCharset())) {
writer.append(file.getName()).append(System.lineSeparator());
}
assertTrue(file.isFile());

View File

@ -56,6 +56,7 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
@ -286,15 +287,15 @@ public class LauncherTest {
}
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
TaskListener listener = new StreamTaskListener(baos2);
TaskListener listener = new StreamTaskListener(baos2, Charset.defaultCharset());
psCustomizer.run(ps, baos1, baos2, listener);
assertEquals(message, 0, ps.join());
if (outputIn2) {
assertThat(message, baos2.toString(), containsString("hello"));
assertThat(message, baos1.toString(), is(emptyString()));
assertThat(message, baos2.toString(Charset.defaultCharset().name()), containsString("hello"));
assertThat(message, baos1.toString(Charset.defaultCharset().name()), is(emptyString()));
} else {
assertThat(message, baos1.toString(), containsString("hello"));
assertThat(message, baos2.toString(), is(emptyString()));
assertThat(message, baos1.toString(Charset.defaultCharset().name()), containsString("hello"));
assertThat(message, baos2.toString(Charset.defaultCharset().name()), is(emptyString()));
}
}

View File

@ -51,6 +51,7 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@ -244,9 +245,9 @@ public class PluginManagerTest {
sites.add(site);
assertEquals(FormValidation.ok(), site.updateDirectly(false).get());
assertNotNull(site.getData());
assertEquals(Collections.emptyList(), r.jenkins.getPluginManager().prevalidateConfig(new ByteArrayInputStream("<whatever><runant plugin=\"ant@1.1\"/></whatever>".getBytes())));
assertEquals(Collections.emptyList(), r.jenkins.getPluginManager().prevalidateConfig(new ByteArrayInputStream("<whatever><runant plugin=\"ant@1.1\"/></whatever>".getBytes(StandardCharsets.UTF_8))));
assertNull(r.jenkins.getPluginManager().getPlugin("htmlpublisher"));
List<Future<UpdateCenterJob>> jobs = r.jenkins.getPluginManager().prevalidateConfig(new ByteArrayInputStream("<whatever><htmlpublisher plugin=\"htmlpublisher@0.7\"/></whatever>".getBytes()));
List<Future<UpdateCenterJob>> jobs = r.jenkins.getPluginManager().prevalidateConfig(new ByteArrayInputStream("<whatever><htmlpublisher plugin=\"htmlpublisher@0.7\"/></whatever>".getBytes(StandardCharsets.UTF_8)));
assertEquals(1, jobs.size());
UpdateCenterJob job = jobs.get(0).get(); // blocks for completion
assertEquals("InstallationJob", job.getType());

View File

@ -64,7 +64,7 @@ public class ProcTest {
for (int i = 0; i < 1000; i++) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
launcher.launch().cmds("echo", str).stdout(baos).join();
assertEquals(str, baos.toString().trim());
assertEquals(str, baos.toString(Charset.defaultCharset().name()).trim());
}
ch.close();
@ -115,21 +115,21 @@ public class ProcTest {
String[] ECHO_BACK_CMD = {"cat"}; // TODO: what is the echo back command for Windows? "cmd /C copy CON CON"?
ByteArrayOutputStream out = new ByteArrayOutputStream();
l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes())).stdout(out).join();
assertEquals("Hello", out.toString());
l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes(Charset.defaultCharset()))).stdout(out).join();
assertEquals("Hello", out.toString(Charset.defaultCharset().name()));
Proc p = l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes())).readStdout().start();
Proc p = l.launch().cmds(ECHO_BACK_CMD).stdin(new ByteArrayInputStream("Hello".getBytes(Charset.defaultCharset()))).readStdout().start();
p.join();
assertEquals("Hello", org.apache.commons.io.IOUtils.toString(p.getStdout()));
assertEquals("Hello", org.apache.commons.io.IOUtils.toString(p.getStdout(), Charset.defaultCharset()));
assertNull(p.getStderr());
assertNull(p.getStdin());
p = l.launch().cmds(ECHO_BACK_CMD).writeStdin().readStdout().start();
p.getStdin().write("Hello".getBytes());
p.getStdin().write("Hello".getBytes(Charset.defaultCharset()));
p.getStdin().close();
p.join();
assertEquals("Hello", org.apache.commons.io.IOUtils.toString(p.getStdout()));
assertEquals("Hello", org.apache.commons.io.IOUtils.toString(p.getStdout(), Charset.defaultCharset()));
assertNull(p.getStderr());
}
}

View File

@ -5,7 +5,8 @@ import static org.hamcrest.MatcherAssert.assertThat;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
@ -39,7 +40,7 @@ public class XMLFileTest {
File configFile = new File(j.jenkins.getRootDir(), "config.xml");
assertThat(configFile.exists(), is(true));
try (BufferedReader config = new BufferedReader(new FileReader(configFile))) {
try (BufferedReader config = Files.newBufferedReader(configFile.toPath(), StandardCharsets.UTF_8)) {
assertThat(config.readLine(), is("<?xml version='1.1' encoding='UTF-8'?>"));
}
}

View File

@ -60,6 +60,7 @@ import hudson.tasks.Shell;
import hudson.util.OneShotEvent;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import net.sf.json.JSONObject;
import org.junit.ClassRule;
@ -298,7 +299,7 @@ public class BuildCommandTest {
}
});
assertThat(new CLICommandInvoker(j, "build").
withStdin(new ByteArrayInputStream("uploaded content here".getBytes())).
withStdin(new ByteArrayInputStream("uploaded content here".getBytes(Charset.defaultCharset()))).
invokeWithArgs("-f", "-p", "file=", "myjob"),
CLICommandInvoker.Matcher.succeeded());
FreeStyleBuild b = p.getBuildByNumber(1);

View File

@ -17,11 +17,13 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -143,7 +145,7 @@ public class CLIActionTest {
"-webSocket", // TODO as above
"-s", j.getURL().toString()./* just checking */replaceFirst("/$", ""), "test-diagnostic").
stdout(baos).stderr(System.err).join());
assertEquals("encoding=ISO-8859-2 locale=cs_CZ", baos.toString().trim());
assertEquals("encoding=ISO-8859-2 locale=cs_CZ", baos.toString(Charset.forName("ISO-8859-2").name()).trim());
// TODO test that stdout/stderr are in expected encoding (not true of -remoting mode!)
// -ssh mode does not pass client locale or encoding
}
@ -157,21 +159,21 @@ public class CLIActionTest {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
PrintWriter pw = new PrintWriter(new TeeOutputStream(pos, System.err), true);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new TeeOutputStream(pos, System.err), Charset.defaultCharset()), true);
Proc proc = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds(
"java", "-jar", jar.getAbsolutePath(), "-s", j.getURL().toString(),
"-webSocket", // TODO as above
"groovysh").
stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).stdin(pis).start();
while (!baos.toString().contains("000")) { // cannot just search for, say, "groovy:000> " since there are ANSI escapes there (cf. StringEscapeUtils.escapeJava)
while (!baos.toString(Charset.defaultCharset().name()).contains("000")) { // cannot just search for, say, "groovy:000> " since there are ANSI escapes there (cf. StringEscapeUtils.escapeJava)
Thread.sleep(100);
}
pw.println("11 * 11");
while (!baos.toString().contains("121")) { // ditto not "===> 121"
while (!baos.toString(Charset.defaultCharset().name()).contains("121")) { // ditto not "===> 121"
Thread.sleep(100);
}
pw.println("11 * 11 * 11");
while (!baos.toString().contains("1331")) {
while (!baos.toString(Charset.defaultCharset().name()).contains("1331")) {
Thread.sleep(100);
}
pw.println(":q");
@ -245,7 +247,7 @@ public class CLIActionTest {
"large-upload").
stdin(new NullInputStream(size)).
stdout(baos).stderr(System.err).join());
assertEquals("received " + size + " bytes", baos.toString().trim());
assertEquals("received " + size + " bytes", baos.toString(Charset.defaultCharset().name()).trim());
}
@TestExtension("largeTransferWebSocket")

View File

@ -15,6 +15,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@ -117,7 +118,7 @@ public class CLIEnvVarTest {
"-auth", String.format("%s:%s", "admin", token),
"who-am-i")
);
assertThat(baos.toString(), containsString("Authenticated as: admin"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin"));
}
}
@ -134,7 +135,7 @@ public class CLIEnvVarTest {
"-s", r.getURL().toString(),
"who-am-i")
);
assertThat(baos.toString(), containsString("Authenticated as: anonymous"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: anonymous"));
}
}
@ -152,7 +153,7 @@ public class CLIEnvVarTest {
"-s", r.getURL().toString(),
"who-am-i")
);
assertThat(baos.toString(), containsString("Authenticated as: admin"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin"));
}
}
@ -203,7 +204,7 @@ public class CLIEnvVarTest {
"-auth", String.format("%s:%s", "admin", token),
"who-am-i")
);
assertThat(baos.toString(), containsString("Authenticated as: admin"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: admin"));
}
}

View File

@ -43,6 +43,7 @@ import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -107,7 +108,7 @@ public class CLITest {
args.addAll(Arrays.asList(modeArgs));
args.addAll(Arrays.asList("build", "-s", "-v", "p"));
Proc proc = new Launcher.LocalLauncher(StreamTaskListener.fromStderr()).launch().cmds(args).stdout(new TeeOutputStream(baos, System.out)).stderr(System.err).start();
while (!baos.toString().contains("Sleeping ")) {
while (!baos.toString(Charset.defaultCharset().name()).contains("Sleeping ")) {
if (!proc.isAlive()) {
throw new AssertionError("Process failed to start with " + proc.join());
}
@ -128,7 +129,7 @@ public class CLITest {
"java", "-jar", jar.getAbsolutePath(), "-s", url, "-http", "-user", "asdf", "who-am-i"
).stdout(baos).stderr(baos).join();
assertThat(baos.toString(), containsString("There's no Jenkins running at"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("There's no Jenkins running at"));
assertNotEquals(0, ret);
// TODO -webSocket currently produces a stack trace
}
@ -186,7 +187,7 @@ public class CLITest {
).stdout(baos).stderr(baos).join();
//assertThat(baos.toString(), containsString("There's no Jenkins running at"));
assertThat(baos.toString(), containsString("Authenticated as: anonymous"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("Authenticated as: anonymous"));
assertEquals(0, ret);
}
}
@ -208,7 +209,7 @@ public class CLITest {
.stderr(baos)
.stdin(CLITest.class.getResourceAsStream("huge-stdin.txt"))
.join();
assertThat(baos.toString(), not(containsString("java.io.IOException: Stream is closed")));
assertThat(baos.toString(Charset.defaultCharset().name()), not(containsString("java.io.IOException: Stream is closed")));
assertEquals(0, ret);
}
}

View File

@ -24,14 +24,13 @@
package hudson.cli;
import static org.junit.Assert.assertEquals;
import static hudson.cli.CLICommandInvoker.Matcher.hasNoErrorOutput;
import static hudson.cli.CLICommandInvoker.Matcher.succeeded;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import hudson.model.FreeStyleProject;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.Locale;
import org.apache.commons.io.input.NullInputStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
@ -40,27 +39,28 @@ import org.jvnet.hudson.test.MockFolder;
public class GetJobCommandTest {
private CLICommandInvoker command;
@Rule public JenkinsRule j = new JenkinsRule();
@Before
public void setUp() {
command = new CLICommandInvoker(j, new GetJobCommand());
}
@Issue("JENKINS-20236")
@Test public void withFolders() throws Exception {
MockFolder d = j.createFolder("d");
FreeStyleProject p = d.createProject(FreeStyleProject.class, "p");
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream outS = new PrintStream(out);
// TODO switch to CLICommandInvoker
int result = new GetJobCommand().main(Collections.singletonList("d/p"), Locale.ENGLISH, new NullInputStream(0), outS, outS);
outS.flush();
String output = out.toString();
assertEquals(output, 0, result);
assertEquals(p.getConfigFile().asString(), output);
out = new ByteArrayOutputStream();
outS = new PrintStream(out);
result = new GetJobCommand().main(Collections.singletonList("d"), Locale.ENGLISH, new NullInputStream(0), outS, outS);
outS.flush();
output = out.toString();
assertEquals(output, 0, result);
assertEquals(d.getConfigFile().asString(), output);
CLICommandInvoker.Result result = command.invokeWithArgs("d/p");
assertThat(result.stdout(), equalTo(p.getConfigFile().asString()));
assertThat(result, hasNoErrorOutput());
assertThat(result, succeeded());
result = command.invokeWithArgs("d");
assertThat(result.stdout(), equalTo(d.getConfigFile().asString()));
assertThat(result, hasNoErrorOutput());
assertThat(result, succeeded());
}
}

View File

@ -30,6 +30,7 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import jenkins.model.Jenkins;
import org.junit.Rule;
import org.junit.Test;
@ -44,7 +45,7 @@ public class GroovyshCommandTest {
@Test public void authentication() {
CLICommandInvoker.Result result = new CLICommandInvoker(r, new GroovyshCommand())
.authorizedTo(Jenkins.READ, Jenkins.ADMINISTER)
.withStdin(new ByteArrayInputStream("println(jenkins.model.Jenkins.instance.getClass().name)\n:quit\n".getBytes()))
.withStdin(new ByteArrayInputStream("println(jenkins.model.Jenkins.instance.getClass().name)\n:quit\n".getBytes(Charset.defaultCharset())))
.invoke();
assertThat(result, succeeded());
assertThat(result, hasNoErrorOutput());

View File

@ -38,8 +38,11 @@ import hudson.model.Node;
import hudson.model.User;
import hudson.tasks.Mailer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import jenkins.model.Jenkins;
import org.junit.Before;
import org.junit.Ignore;
@ -184,16 +187,19 @@ public class ReloadConfigurationCommandTest {
private void replace(String path, String search, String replace) {
File configFile = new File(j.jenkins.getRootDir(), path);
String oldConfig;
try {
String oldConfig = Util.loadFile(configFile);
oldConfig = Util.loadFile(configFile, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
String newConfig = oldConfig.replaceAll(search, replace);
String newConfig = oldConfig.replaceAll(search, replace);
FileWriter fw = new FileWriter(configFile);
fw.write(newConfig);
fw.close();
} catch (IOException ex) {
throw new AssertionError(ex);
try (Writer writer = Files.newBufferedWriter(configFile.toPath(), StandardCharsets.UTF_8)) {
writer.write(newConfig);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

View File

@ -57,14 +57,14 @@ public class AnnotatedLargeTextTest {
@Test
public void smokes() throws Exception {
ByteBuffer buf = new ByteBuffer();
PrintStream ps = new PrintStream(buf, true);
PrintStream ps = new PrintStream(buf, true, StandardCharsets.UTF_8.name());
ps.print("Some text.\n");
ps.print("Go back to " + TestNote.encodeTo("/root", "your home") + ".\n");
ps.print("More text.\n");
AnnotatedLargeText<Void> text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
text.writeLogTo(0, baos);
assertEquals("Some text.\nGo back to your home.\nMore text.\n", baos.toString());
assertEquals("Some text.\nGo back to your home.\nMore text.\n", baos.toString(StandardCharsets.UTF_8.name()));
StringWriter w = new StringWriter();
text.writeHtmlTo(0, w);
assertEquals("Some text.\nGo back to <a href='/root'>your home</a>.\nMore text.\n", w.toString());
@ -83,11 +83,11 @@ public class AnnotatedLargeTextTest {
+ "v3+utadQyH8B+aJxVM4AAAA="
+ ConsoleNote.POSTAMBLE_STR
+ "there\n")
.getBytes());
.getBytes(StandardCharsets.UTF_8));
AnnotatedLargeText<Void> text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
text.writeLogTo(0, baos);
assertEquals("hellothere\n", baos.toString());
assertEquals("hellothere\n", baos.toString(StandardCharsets.UTF_8.name()));
StringWriter w = new StringWriter();
text.writeHtmlTo(0, w);
assertEquals("hellothere\n", w.toString());
@ -121,11 +121,11 @@ public class AnnotatedLargeTextTest {
+ "ABmN28qcAAAA"
+ ConsoleNote.POSTAMBLE_STR
+ "your home.\n")
.getBytes());
.getBytes(StandardCharsets.UTF_8));
AnnotatedLargeText<Void> text = new AnnotatedLargeText<>(buf, StandardCharsets.UTF_8, true, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
text.writeLogTo(0, baos);
assertEquals("Go back to your home.\n", baos.toString());
assertEquals("Go back to your home.\n", baos.toString(StandardCharsets.UTF_8.name()));
StringWriter w = new StringWriter();
text.writeHtmlTo(0, w);
assertEquals("Go back to your home.\n", w.toString());

View File

@ -7,6 +7,7 @@ import hudson.model.Run;
import hudson.slaves.SlaveComputer;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
@ -42,7 +43,7 @@ public class ConsoleLogFilterTest {
return new LineTransformationOutputStream.Delegating(out) {
@Override
protected void eol(byte[] b, int len) throws IOException {
out.write(("[[" + c.getName() + "]] ").getBytes());
out.write(("[[" + c.getName() + "]] ").getBytes(Charset.defaultCharset()));
out.write(b, 0, len);
}
};

View File

@ -455,10 +455,10 @@ public class AbstractProjectTest {
private HttpURLConnection postConfigDotXml(FreeStyleProject p, String xml) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), "job/" + p.getName() + "/config.xml").openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/xml");
con.setRequestProperty("Content-Type", "application/xml; charset=utf-8");
con.setDoOutput(true);
try (OutputStream s = con.getOutputStream()) {
s.write(xml.getBytes());
s.write(xml.getBytes(StandardCharsets.UTF_8));
}
return con;
}

View File

@ -36,6 +36,7 @@ import hudson.util.StreamTaskListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
@ -96,29 +97,29 @@ public class CauseTest {
@Issue("JENKINS-48467")
@Test public void userIdCausePrintTest() {
@Test public void userIdCausePrintTest() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TaskListener listener = new StreamTaskListener(baos);
TaskListener listener = new StreamTaskListener(baos, Charset.defaultCharset());
//null userId - print unknown or anonymous
Cause causeA = new Cause.UserIdCause(null);
causeA.print(listener);
assertEquals("Started by user unknown or anonymous", baos.toString().trim());
assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset().name()).trim());
baos.reset();
//SYSTEM userid - getDisplayName() should be SYSTEM
Cause causeB = new Cause.UserIdCause();
causeB.print(listener);
assertThat(baos.toString(), containsString("SYSTEM"));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString("SYSTEM"));
baos.reset();
//unknown userid - print unknown or anonymous
Cause causeC = new Cause.UserIdCause("abc123");
causeC.print(listener);
assertEquals("Started by user unknown or anonymous", baos.toString().trim());
assertEquals("Started by user unknown or anonymous", baos.toString(Charset.defaultCharset().name()).trim());
baos.reset();
//More or less standard operation
@ -127,7 +128,7 @@ public class CauseTest {
Cause causeD = new Cause.UserIdCause(user.getId());
causeD.print(listener);
assertThat(baos.toString(), containsString(user.getDisplayName()));
assertThat(baos.toString(Charset.defaultCharset().name()), containsString(user.getDisplayName()));
baos.reset();
}

View File

@ -41,6 +41,8 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -71,7 +73,7 @@ public class FingerprintCleanupThreadTest {
configureLocalTestStorage(new TestFingerprint(true));
FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread();
cleanupThread.execute(testTaskListener);
String logOutput = testTaskListener.outputStream.toString();
String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name());
assertFalse("Should not have logged unimportant, excessive message.", logOutput.contains("possibly trimming"));
}
@ -82,7 +84,7 @@ public class FingerprintCleanupThreadTest {
configureLocalTestStorage(new TestFingerprint(false));
FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread();
cleanupThread.execute(testTaskListener);
String logOutput = testTaskListener.outputStream.toString();
String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name());
assertFalse("Should have deleted obsolete file.", fpFile.toFile().exists());
}
@ -99,7 +101,7 @@ public class FingerprintCleanupThreadTest {
configureLocalTestStorage(new TestFingerprint());
FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread();
cleanupThread.execute(testTaskListener);
String logOutput = testTaskListener.outputStream.toString();
String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name());
assertTrue("Should have done nothing.", logOutput.startsWith("Cleaned up 0 records"));
}
@ -114,7 +116,7 @@ public class FingerprintCleanupThreadTest {
configureLocalTestStorage(fp);
FingerprintCleanupThread cleanupThread = new FingerprintCleanupThread();
cleanupThread.execute(testTaskListener);
String logOutput = testTaskListener.outputStream.toString();
String logOutput = testTaskListener.outputStream.toString(Charset.defaultCharset().name());
assertThat(logOutput, containsString("blocked deletion of"));
}
@ -219,8 +221,16 @@ public class FingerprintCleanupThreadTest {
private static class TestTaskListener implements TaskListener {
private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private PrintStream logStream = new PrintStream(outputStream);
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private final PrintStream logStream;
{
try {
logStream = new PrintStream(outputStream, false, Charset.defaultCharset().name());
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
}
@NonNull
@Override

View File

@ -48,6 +48,7 @@ import hudson.tasks.Builder;
import hudson.tasks.Shell;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import jenkins.model.Jenkins;
@ -129,7 +130,7 @@ public class FreeStyleProjectTest {
@Issue("JENKINS-15817")
public void minimalConfigXml() throws Exception {
// Make sure it can be created without exceptions:
FreeStyleProject project = (FreeStyleProject) j.jenkins.createProjectFromXML("stuff", new ByteArrayInputStream("<project/>".getBytes()));
FreeStyleProject project = (FreeStyleProject) j.jenkins.createProjectFromXML("stuff", new ByteArrayInputStream("<project/>".getBytes(StandardCharsets.UTF_8)));
System.out.println(project.getConfigFile().asString());
// and round-tripped:
Shell shell = new Shell("echo hello");
@ -253,7 +254,7 @@ public class FreeStyleProjectTest {
public void cannotCreateJobWithTrailingDot_withoutOtherJob() throws Exception {
assertThat(j.jenkins.getItems(), hasSize(0));
try {
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes()));
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes(StandardCharsets.UTF_8)));
fail("Adding the job should have thrown an exception during checkGoodName");
}
catch (Failure e) {
@ -269,7 +270,7 @@ public class FreeStyleProjectTest {
j.createFreeStyleProject("jobA");
assertThat(j.jenkins.getItems(), hasSize(1));
try {
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes()));
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes(StandardCharsets.UTF_8)));
fail("Adding the job should have thrown an exception during checkGoodName");
}
catch (Failure e) {
@ -285,7 +286,7 @@ public class FreeStyleProjectTest {
System.setProperty(propName, "false");
try {
assertThat(j.jenkins.getItems(), hasSize(0));
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes()));
j.jenkins.createProjectFromXML("jobA.", new ByteArrayInputStream("<project/>".getBytes(StandardCharsets.UTF_8)));
}
finally {
if (initialValue == null) {

View File

@ -49,6 +49,7 @@ import hudson.triggers.Trigger;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@ -95,13 +96,13 @@ public class ItemGroupMixInTest {
File configFile = project.getConfigFile().getFile();
List<String> lines = FileUtils.readLines(configFile).subList(0, 5);
List<String> lines = FileUtils.readLines(configFile, StandardCharsets.UTF_8).subList(0, 5);
configFile.delete();
// Remove half of the config.xml file to make "invalid" or fail to load
FileUtils.writeByteArrayToFile(configFile, lines.toString().getBytes());
FileUtils.writeByteArrayToFile(configFile, lines.toString().getBytes(StandardCharsets.UTF_8));
for (int i = lines.size() / 2; i < lines.size(); i++) {
FileUtils.writeStringToFile(configFile, lines.get(i), true);
FileUtils.writeStringToFile(configFile, lines.get(i), StandardCharsets.UTF_8, true);
}
// Reload Jenkins.
@ -212,7 +213,7 @@ public class ItemGroupMixInTest {
" <buildWrappers/>\n" +
"</project>";
Item foo = r.jenkins.createProjectFromXML("foo", new ByteArrayInputStream(xml.getBytes()));
Item foo = r.jenkins.createProjectFromXML("foo", new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
// if no exception then JAXP is swallowing these - so there should be no entity in the description.
assertThat(Items.getConfigFile(foo).asString(), containsString("<description/>"));
}
@ -261,7 +262,7 @@ public class ItemGroupMixInTest {
"</project>";
Failure exception = assertThrows(Failure.class, () -> {
r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes()));
r.jenkins.createProjectFromXML(badName, new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
});
assertEquals(exception.getMessage(), Messages.Hudson_UnsafeChar("@"));
}

View File

@ -53,6 +53,7 @@ import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
@ -375,7 +376,7 @@ public class JobTest {
FreeStyleBuild b2 = p2.getBuilds().getLastBuild();
ByteArrayOutputStream out = new ByteArrayOutputStream();
b2.getLogText().writeRawLogTo(0, out);
final String oldB2Log = out.toString();
final String oldB2Log = out.toString(Charset.defaultCharset().name());
assertTrue(b2.getArtifactManager().root().child("hello.txt").exists());
f.renameTo("something-else");
@ -392,7 +393,7 @@ public class JobTest {
assertNotNull(b2);
out = new ByteArrayOutputStream();
b2.getLogText().writeRawLogTo(0, out);
final String newB2Log = out.toString();
final String newB2Log = out.toString(Charset.defaultCharset().name());
assertEquals(oldB2Log, newB2Log);
assertTrue(b2.getArtifactManager().root().child("hello.txt").exists());

View File

@ -39,6 +39,7 @@ import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -99,7 +100,7 @@ public class UpdateSiteTest {
baseRequest.setHandled(true);
response.setContentType("text/plain; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().write(responseBody.getBytes());
response.getOutputStream().write(responseBody.getBytes(StandardCharsets.UTF_8));
}
}
});

View File

@ -31,6 +31,7 @@ import static org.junit.Assert.assertNotNull;
import hudson.cli.CLICommandInvoker;
import hudson.model.Item;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@ -64,7 +65,7 @@ public class ItemListenerTest {
@Test
public void onCreatedViaCLI() {
CLICommandInvoker.Result result = new CLICommandInvoker(j, "create-job").
withStdin(new ByteArrayInputStream("<project><actions/><builders/><publishers/><buildWrappers/></project>".getBytes())).
withStdin(new ByteArrayInputStream("<project><actions/><builders/><publishers/><buildWrappers/></project>".getBytes(Charset.defaultCharset()))).
invokeWithArgs("testJob");
assertThat(result, CLICommandInvoker.Matcher.succeeded());
assertNotNull("job should be created: " + result, j.jenkins.getItem("testJob"));

View File

@ -14,6 +14,7 @@ import com.gargoylesoftware.htmlunit.CookieManager;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.xml.XmlPage;
import hudson.model.User;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
@ -336,7 +337,7 @@ public class TokenBasedRememberMeServices2Test {
HudsonPrivateSecurityRealm.Details details = user.getProperty(HudsonPrivateSecurityRealm.Details.class);
String signatureValue = tokenService.makeTokenSignature(expiryTime, details.getUsername(), details.getPassword());
String tokenValue = user.getId() + ":" + expiryTime + ":" + signatureValue;
String tokenValueBase64 = Base64.getEncoder().encodeToString(tokenValue.getBytes());
String tokenValueBase64 = Base64.getEncoder().encodeToString(tokenValue.getBytes(StandardCharsets.UTF_8));
return new Cookie(j.getURL().getHost(), tokenService.getCookieName(), tokenValueBase64);
}

View File

@ -34,6 +34,7 @@ import hudson.model.Items;
import java.io.ByteArrayInputStream;
import java.io.ObjectStreamException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Source;
@ -84,7 +85,9 @@ public class TriggerStartTest {
}
@Test public void createProjectFromXmlCallsStartTrue() throws Exception {
FreeStyleProject p = (FreeStyleProject) j.jenkins.createProjectFromXML("whatever", new ByteArrayInputStream(("<project>\n <builders/>\n <publishers/>\n <buildWrappers/>\n" + triggersSection() + "</project>").getBytes()));
FreeStyleProject p = (FreeStyleProject) j.jenkins.createProjectFromXML(
"whatever",
new ByteArrayInputStream(("<project>\n <builders/>\n <publishers/>\n <buildWrappers/>\n" + triggersSection() + "</project>").getBytes(StandardCharsets.UTF_8)));
MockTrigger t = p.getTrigger(MockTrigger.class);
assertNotNull(t);
assertEquals("[true]", t.calls.toString());

View File

@ -28,6 +28,7 @@ import antlr.ANTLRException;
import hudson.Extension;
import hudson.model.Item;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Rule;
@ -44,7 +45,7 @@ public class TriggerTest {
@Issue("JENKINS-36748")
@Test
public void testNoNPE() throws Exception {
jenkinsRule.getInstance().createProjectFromXML("whatever", new ByteArrayInputStream(("<project>\n <builders/>\n <publishers/>\n <buildWrappers/>\n" + triggersSection() + "</project>").getBytes()));
jenkinsRule.getInstance().createProjectFromXML("whatever", new ByteArrayInputStream(("<project>\n <builders/>\n <publishers/>\n <buildWrappers/>\n" + triggersSection() + "</project>").getBytes(StandardCharsets.UTF_8)));
final Calendar cal = new GregorianCalendar();
Trigger.checkTriggers(cal);
}

View File

@ -39,6 +39,7 @@ import hudson.model.Slave;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.logging.Level;
import jenkins.util.SystemProperties;
import org.apache.tools.ant.util.JavaEnvUtils;
@ -135,7 +136,7 @@ public class ArgumentListBuilder2Test {
.toWindowsCommand();
ByteArrayOutputStream out = new ByteArrayOutputStream();
final StreamTaskListener listener = new StreamTaskListener(out);
final StreamTaskListener listener = new StreamTaskListener(out, Charset.defaultCharset());
Proc p = new LocalLauncher(listener)
.launch()
.stderr(System.err)
@ -147,6 +148,6 @@ public class ArgumentListBuilder2Test {
listener.close();
assumeThat("Failed to run " + args, code, equalTo(0));
return out.toString();
return out.toString(Charset.defaultCharset().name());
}
}

View File

@ -47,6 +47,7 @@ import hudson.security.ACL;
import java.io.ByteArrayInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import jenkins.model.Jenkins;
@ -271,7 +272,7 @@ public class RobustReflectionConverterTest {
CLICommandInvoker.Result ret = new CLICommandInvoker(r, "update-job")
.asUser("test")
.withStdin(new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD).getBytes()))
.withStdin(new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, "badvalue", AcceptOnlySpecificKeyword.ACCEPT_KEYWORD).getBytes(Charset.defaultCharset())))
.withArgs(
p.getFullName()
)
@ -303,7 +304,7 @@ public class RobustReflectionConverterTest {
r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
CLICommandInvoker.Result ret = new CLICommandInvoker(r, "update-job")
.asUser("test")
.withStdin(new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue").getBytes()))
.withStdin(new ByteArrayInputStream(String.format(CONFIGURATION_TEMPLATE, AcceptOnlySpecificKeyword.ACCEPT_KEYWORD, "badvalue").getBytes(Charset.defaultCharset())))
.withArgs(
p.getFullName()
)

View File

@ -38,6 +38,7 @@ import hudson.slaves.SlaveComputer;
import hudson.tasks.BatchFile;
import hudson.tasks.Shell;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
@ -136,7 +137,7 @@ public class WebSocketAgentsTest {
@Override
public String call() {
return new String(payload);
return new String(payload, StandardCharsets.UTF_8);
}
}

View File

@ -41,6 +41,7 @@ import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
@ -89,7 +90,7 @@ public class SetupWizardTest {
final FilePath adminPassFile = wizard.getInitialAdminPasswordFile();
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
adminPassFile.copyTo(ostream);
final String password = ostream.toString();
final String password = ostream.toString(StandardCharsets.UTF_8.name());
}
@Test
@ -351,7 +352,7 @@ public class SetupWizardTest {
baseRequest.setHandled(true);
response.setContentType("text/plain; charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().write(responseBody.getBytes());
response.getOutputStream().write(responseBody.getBytes(StandardCharsets.UTF_8));
} else {
response.sendError(404);
}
@ -456,7 +457,7 @@ public class SetupWizardTest {
protected Set<TrustAnchor> loadTrustAnchors(CertificateFactory cf) throws IOException {
Set<TrustAnchor> trustAnchors = new HashSet<>();
try {
Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(cert.getBytes()));
Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(cert.getBytes(StandardCharsets.UTF_8)));
trustAnchors.add(new TrustAnchor((X509Certificate) certificate, null));
} catch (CertificateException ex) {
throw new IOException(ex);

View File

@ -9,8 +9,11 @@ import hudson.model.Node;
import hudson.model.User;
import hudson.tasks.Mailer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
@ -126,16 +129,19 @@ public class JenkinsReloadConfigurationTest {
private void replace(String path, String search, String replace) {
File configFile = new File(j.jenkins.getRootDir(), path);
String oldConfig;
try {
String oldConfig = Util.loadFile(configFile);
oldConfig = Util.loadFile(configFile, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
String newConfig = oldConfig.replaceAll(search, replace);
String newConfig = oldConfig.replaceAll(search, replace);
FileWriter fw = new FileWriter(configFile);
fw.write(newConfig);
fw.close();
} catch (IOException ex) {
throw new AssertionError(ex);
try (Writer writer = Files.newBufferedWriter(configFile.toPath(), StandardCharsets.UTF_8)) {
writer.write(newConfig);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

View File

@ -15,6 +15,7 @@ import hudson.cli.GetNodeCommand;
import hudson.cli.UpdateNodeCommand;
import hudson.model.Node;
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@ -36,10 +37,10 @@ public class NodeListenerTest {
public void crud() throws Exception {
Node agent = j.createSlave();
String xml = cli(new GetNodeCommand()).invokeWithArgs(agent.getNodeName()).stdout();
cli(new UpdateNodeCommand()).withStdin(new ByteArrayInputStream(xml.getBytes())).invokeWithArgs(agent.getNodeName());
cli(new UpdateNodeCommand()).withStdin(new ByteArrayInputStream(xml.getBytes(Charset.defaultCharset()))).invokeWithArgs(agent.getNodeName());
cli(new DeleteNodeCommand()).invokeWithArgs(agent.getNodeName());
cli(new CreateNodeCommand()).withStdin(new ByteArrayInputStream(xml.getBytes())).invokeWithArgs("replica");
cli(new CreateNodeCommand()).withStdin(new ByteArrayInputStream(xml.getBytes(Charset.defaultCharset()))).invokeWithArgs("replica");
j.jenkins.getComputer("replica").doDoDelete();
verify(mock, times(2)).onCreated(any(Node.class));

View File

@ -89,7 +89,7 @@ public class RekeySecretAdminMonitorTest {
private static void putSomeOldData(File dir) throws Exception {
File xml = new File(dir, "foo.xml");
FileUtils.writeStringToFile(xml, "<foo>" + encryptOld(TEST_KEY) + "</foo>");
FileUtils.writeStringToFile(xml, "<foo>" + encryptOld(TEST_KEY) + "</foo>", StandardCharsets.UTF_8);
}
private void verifyRewrite(File dir) throws Exception {
@ -177,7 +177,7 @@ public class RekeySecretAdminMonitorTest {
private static String encryptOld(String str) throws Exception {
Cipher cipher = Secret.getCipher("AES");
cipher.init(Cipher.ENCRYPT_MODE, Util.toAes128Key(TEST_KEY));
return new String(Base64.getEncoder().encode(cipher.doFinal((str + "::::MAGIC::::").getBytes(StandardCharsets.UTF_8))));
return Base64.getEncoder().encodeToString(cipher.doFinal((str + "::::MAGIC::::").getBytes(StandardCharsets.UTF_8)));
}
private String encryptNew(String str) {

View File

@ -58,6 +58,7 @@ import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Locale;
import org.junit.Assume;
@ -291,7 +292,7 @@ public class SimpleBuildWrapperTest {
@Override public OutputStream decorateLogger(AbstractBuild _ignore, OutputStream logger) throws IOException, InterruptedException {
return new LineTransformationOutputStream.Delegating(logger) {
@Override protected void eol(byte[] b, int len) throws IOException {
out.write(new String(b, 0, len).toUpperCase(Locale.ROOT).getBytes());
out.write(new String(b, 0, len, Charset.defaultCharset()).toUpperCase(Locale.ROOT).getBytes(Charset.defaultCharset()));
}
};
}