Consistently use character encoding constants

Use the java.nio.charset.StandardCharsets.{ISO_8859_1,UTF_8} constants'
name() methods instead of hard-coding the strings.

Where possible, use method variants that take a Charset rather than
a String. This removes the need to catch UnsupportedEncodingException
in some cases.

Change-Id: I4ac1ba0a753de715e1f38ce631842f527b9e127c
This commit is contained in:
David Pursehouse 2015-10-08 15:46:47 +09:00
parent 852022af90
commit 19c63fa311
49 changed files with 170 additions and 148 deletions

View File

@ -14,7 +14,8 @@
package com.google.gerrit.acceptance;
import com.google.common.base.Charsets;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Preconditions;
import com.google.common.net.HttpHeaders;
import com.google.gerrit.extensions.restapi.RawInput;
@ -30,7 +31,6 @@ import org.apache.http.message.BasicHeader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class RestSession extends HttpSession {
@ -79,7 +79,7 @@ public class RestSession extends HttpSession {
put.addHeader(new BasicHeader("Content-Type", "application/json"));
put.body(new StringEntity(
OutputFormat.JSON_COMPACT.newGson().toJson(content),
Charsets.UTF_8.name()));
UTF_8.name()));
}
return execute(put);
}
@ -105,7 +105,7 @@ public class RestSession extends HttpSession {
post.addHeader(new BasicHeader("Content-Type", "application/json"));
post.body(new StringEntity(
OutputFormat.JSON_COMPACT.newGson().toJson(content),
Charsets.UTF_8.name()));
UTF_8.name()));
}
return execute(post);
}
@ -116,7 +116,7 @@ public class RestSession extends HttpSession {
public static RawInput newRawInput(String content) {
return newRawInput(content.getBytes(StandardCharsets.UTF_8));
return newRawInput(content.getBytes(UTF_8));
}
public static RawInput newRawInput(final byte[] bytes) {

View File

@ -14,6 +14,8 @@
package com.google.gerrit.extensions.restapi;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
@ -23,7 +25,6 @@ import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
/**
@ -187,7 +188,7 @@ public abstract class BinaryResult implements Closeable {
try {
Charset cs = enc != null
? Charset.forName(enc)
: StandardCharsets.UTF_8;
: UTF_8;
return cs.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
@ -226,9 +227,9 @@ public abstract class BinaryResult implements Closeable {
private final String str;
StringResult(String str) {
super(str.getBytes(StandardCharsets.UTF_8));
super(str.getBytes(UTF_8));
setContentType("text/plain");
setCharacterEncoding("UTF-8");
setCharacterEncoding(UTF_8.name());
this.str = str;
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.extensions.restapi;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
@ -40,7 +42,7 @@ public final class Url {
public static String encode(String component) {
if (component != null) {
try {
return URLEncoder.encode(component, "UTF-8");
return URLEncoder.encode(component, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM must support UTF-8", e);
}
@ -52,7 +54,7 @@ public final class Url {
public static String decode(String str) {
if (str != null) {
try {
return URLDecoder.decode(str, "UTF-8");
return URLDecoder.decode(str, UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM must support UTF-8", e);
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.httpd;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.cache.Cache;
import com.google.common.collect.Lists;
import com.google.gerrit.common.data.Capable;
@ -160,7 +162,7 @@ public class GitOverHttpServlet extends GitServlet {
ServiceNotEnabledException {
try {
// TODO: remove this code when Guice fixes its issue 745
projectName = URLDecoder.decode(projectName, "UTF-8");
projectName = URLDecoder.decode(projectName, UTF_8.name());
} catch (UnsupportedEncodingException e) {
// leave it encoded
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.httpd;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.io.ByteStreams;
import org.w3c.dom.Document;
@ -27,7 +29,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
@ -50,7 +51,7 @@ import javax.xml.xpath.XPathFactory;
/** Utility functions to deal with HTML using W3C DOM operations. */
public class HtmlDomUtil {
/** Standard character encoding we prefer (UTF-8). */
public static final Charset ENC = StandardCharsets.UTF_8;
public static final Charset ENC = UTF_8;
/** DOCTYPE for a standards mode HTML document. */
public static final String HTML_STRICT =

View File

@ -14,6 +14,7 @@
package com.google.gerrit.httpd;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import com.google.common.base.MoreObjects;
@ -188,7 +189,7 @@ class ProjectBasicAuthFilter implements Filter {
}
private String encoding(HttpServletRequest req) {
return MoreObjects.firstNonNull(req.getCharacterEncoding(), "UTF-8");
return MoreObjects.firstNonNull(req.getCharacterEncoding(), UTF_8.name());
}
static class Response extends HttpServletResponseWrapper {

View File

@ -14,6 +14,7 @@
package com.google.gerrit.httpd;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
@ -36,7 +37,6 @@ import com.google.inject.Singleton;
import org.eclipse.jgit.lib.Config;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
@ -189,25 +189,17 @@ class ProjectDigestFilter implements Filter {
}
private static String H(String data) {
try {
MessageDigest md = newMD5();
md.update(data.getBytes("UTF-8"));
return LHEX(md.digest());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not available", e);
}
MessageDigest md = newMD5();
md.update(data.getBytes(UTF_8));
return LHEX(md.digest());
}
private static String KD(String secret, String data) {
try {
MessageDigest md = newMD5();
md.update(secret.getBytes("UTF-8"));
md.update((byte) ':');
md.update(data.getBytes("UTF-8"));
return LHEX(md.digest());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 encoding not available", e);
}
MessageDigest md = newMD5();
md.update(secret.getBytes(UTF_8));
md.update((byte) ':');
md.update(data.getBytes(UTF_8));
return LHEX(md.digest());
}
private static MessageDigest newMD5() {

View File

@ -15,6 +15,7 @@
package com.google.gerrit.httpd.auth.container;
import static com.google.gerrit.reviewdb.client.AccountExternalId.SCHEME_EXTERNAL;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.PageLinks;
import com.google.gerrit.extensions.registration.DynamicItem;
@ -102,7 +103,7 @@ class HttpLoginServlet extends HttpServlet {
final byte[] bin = HtmlDomUtil.toUTF8(doc);
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.setContentType("text/html");
rsp.setCharacterEncoding("UTF-8");
rsp.setCharacterEncoding(UTF_8.name());
rsp.setContentLength(bin.length);
try (ServletOutputStream out = rsp.getOutputStream()) {
out.write(bin);

View File

@ -92,7 +92,7 @@ class LdapLoginServlet extends HttpServlet {
byte[] bin = HtmlDomUtil.toUTF8(doc);
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
res.setContentType("text/html");
res.setCharacterEncoding("UTF-8");
res.setCharacterEncoding(UTF_8.name());
res.setContentLength(bin.length);
try (ServletOutputStream out = res.getOutputStream()) {
out.write(bin);

View File

@ -15,6 +15,7 @@
package com.google.gerrit.httpd.gitweb;
import static com.google.gerrit.common.FileUtil.lastModified;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.httpd.HtmlDomUtil;
import com.google.gerrit.server.config.GitwebCgiConfig;
@ -25,6 +26,7 @@ import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
@ -51,7 +53,7 @@ abstract class GitwebCssServlet extends HttpServlet {
}
}
private static final String ENC = "UTF-8";
private static final Charset ENC = UTF_8;
private final long modified;
private final byte[] raw_css;
@ -65,7 +67,7 @@ abstract class GitwebCssServlet extends HttpServlet {
final String raw = HtmlDomUtil.readFile(dir, name);
if (raw != null) {
modified = lastModified(src);
raw_css = raw.getBytes(ENC);
raw_css = raw.getBytes(UTF_8);
gz_css = HtmlDomUtil.compress(raw_css);
} else {
modified = -1L;
@ -89,7 +91,7 @@ abstract class GitwebCssServlet extends HttpServlet {
final HttpServletResponse rsp) throws IOException {
if (raw_css != null) {
rsp.setContentType("text/css");
rsp.setCharacterEncoding(ENC);
rsp.setCharacterEncoding(ENC.name());
final byte[] toSend;
if (RPCServletUtils.acceptsGzipEncoding(req)) {
rsp.setHeader("Content-Encoding", "gzip");

View File

@ -29,6 +29,7 @@
package com.google.gerrit.httpd.gitweb;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.PageLinks;
@ -636,7 +637,7 @@ class GitwebServlet extends HttpServlet {
@Override
public void run() {
try (BufferedReader br =
new BufferedReader(new InputStreamReader(in, "ISO-8859-1"))) {
new BufferedReader(new InputStreamReader(in, ISO_8859_1.name()))) {
String line;
while ((line = br.readLine()) != null) {
log.error("CGI: " + line);

View File

@ -17,6 +17,7 @@ package com.google.gerrit.httpd.plugins;
import static com.google.gerrit.common.FileUtil.lastModified;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CHARACTER_ENCODING;
import static com.google.gerrit.server.plugins.PluginEntry.ATTR_CONTENT_TYPE;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.CharMatcher;
import com.google.common.base.Optional;
@ -468,13 +469,13 @@ class HttpPluginServlet extends HttpServlet
m.appendTail(sb);
byte[] html = new MarkdownFormatter()
.markdownToDocHtml(sb.toString(), "UTF-8");
.markdownToDocHtml(sb.toString(), UTF_8.name());
resourceCache.put(cacheKey, new SmallResource(html)
.setContentType("text/html")
.setCharacterEncoding("UTF-8")
.setCharacterEncoding(UTF_8.name())
.setLastModified(lastModifiedTime));
res.setContentType("text/html");
res.setCharacterEncoding("UTF-8");
res.setCharacterEncoding(UTF_8.name());
res.setContentLength(html.length);
res.setDateHeader("Last-Modified", lastModifiedTime);
res.getOutputStream().write(html);
@ -526,7 +527,7 @@ class HttpPluginServlet extends HttpServlet
charEnc = Strings.emptyToNull(atts.get(ATTR_CHARACTER_ENCODING));
}
if (charEnc == null) {
charEnc = "UTF-8";
charEnc = UTF_8.name();
}
return new MarkdownFormatter().extractTitleFromMarkdown(
readWholeEntry(scanner, entry),
@ -553,7 +554,7 @@ class HttpPluginServlet extends HttpServlet
}
String txtmd = RawParseUtils.decode(
Charset.forName(encoding != null ? encoding : "UTF-8"),
Charset.forName(encoding != null ? encoding : UTF_8.name()),
rawmd);
long time = entry.getTime();
if (0 < time) {

View File

@ -15,6 +15,7 @@
package com.google.gerrit.httpd.raw;
import static com.google.gerrit.common.FileUtil.lastModified;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
@ -201,7 +202,7 @@ public class HostPageServlet extends HttpServlet {
plugins(w);
messages(w);
final byte[] hpd = w.toString().getBytes("UTF-8");
final byte[] hpd = w.toString().getBytes(UTF_8);
final byte[] raw = Bytes.concat(page.part1, hpd, page.part2);
final byte[] tosend;
if (RPCServletUtils.acceptsGzipEncoding(req)) {
@ -353,8 +354,8 @@ public class HostPageServlet extends HttpServlet {
if (p < 0) {
throw new IOException("No tag in transformed host page HTML");
}
part1 = raw.substring(0, p).getBytes("UTF-8");
part2 = raw.substring(raw.indexOf('>', p) + 1).getBytes("UTF-8");
part1 = raw.substring(0, p).getBytes(UTF_8);
part2 = raw.substring(raw.indexOf('>', p) + 1).getBytes(UTF_8);
}
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.httpd.raw;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.server.ssh.SshInfo;
import com.google.gwtexpui.server.CacheHeaders;
import com.google.inject.Inject;
@ -88,7 +90,7 @@ public class SshInfoServlet extends HttpServlet {
}
CacheHeaders.setNotCacheable(rsp);
rsp.setCharacterEncoding("UTF-8");
rsp.setCharacterEncoding(UTF_8.name());
rsp.setContentType("text/plain");
try (PrintWriter w = rsp.getWriter()) {
w.write(out);

View File

@ -17,6 +17,7 @@ package com.google.gerrit.httpd.raw;
import static com.google.gerrit.httpd.HtmlDomUtil.compress;
import static com.google.gerrit.httpd.HtmlDomUtil.newDocument;
import static com.google.gerrit.httpd.HtmlDomUtil.toUTF8;
import static java.nio.charset.StandardCharsets.UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND;
import static org.eclipse.jgit.util.HttpSupport.HDR_CACHE_CONTROL;
import static org.eclipse.jgit.util.HttpSupport.HDR_EXPIRES;
@ -143,7 +144,7 @@ public class ToolServlet extends HttpServlet {
rsp.setHeader(HDR_PRAGMA, "no-cache");
rsp.setHeader(HDR_CACHE_CONTROL, "no-cache, must-revalidate");
rsp.setContentType("text/html");
rsp.setCharacterEncoding("UTF-8");
rsp.setCharacterEncoding(UTF_8.name());
rsp.setContentLength(tosend.length);
try (OutputStream out = rsp.getOutputStream()) {
out.write(tosend);

View File

@ -819,7 +819,7 @@ public class RestApiServlet extends HttpServlet {
}
res.setHeader("X-FYI-Content-Encoding", "base64");
res.setHeader("X-FYI-Content-Type", src.getContentType());
return b64.setContentType("text/plain").setCharacterEncoding("ISO-8859-1");
return b64.setContentType("text/plain").setCharacterEncoding(ISO_8859_1.name());
}
private static BinaryResult stackGzip(HttpServletResponse res,

View File

@ -14,6 +14,8 @@
package com.google.gerrit.httpd.auth.openid;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.MoreObjects;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
@ -320,7 +322,7 @@ class LoginForm extends HttpServlet {
byte[] bin = HtmlDomUtil.toUTF8(doc);
res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
res.setContentType("text/html");
res.setCharacterEncoding("UTF-8");
res.setCharacterEncoding(UTF_8.name());
res.setContentLength(bin.length);
try (ServletOutputStream out = res.getOutputStream()) {
out.write(bin);

View File

@ -14,12 +14,15 @@
package com.google.gerrit.httpd.auth.openid;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.server.config.CanonicalWebUrl;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
@ -29,7 +32,7 @@ import javax.servlet.http.HttpServletResponse;
@Singleton
class XrdsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String ENC = "UTF-8";
private static final Charset ENC = UTF_8;
static final String LOCATION = "OpenID.XRDS";
private final Provider<String> url;
@ -43,7 +46,7 @@ class XrdsServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws IOException {
final StringBuilder r = new StringBuilder();
r.append("<?xml version=\"1.0\" encoding=\"").append(ENC).append("\"?>");
r.append("<?xml version=\"1.0\" encoding=\"").append(ENC.name()).append("\"?>");
r.append("<xrds:XRDS");
r.append(" xmlns:xrds=\"xri://$xrds\"");
r.append(" xmlns:openid=\"http://openid.net/xmlns/1.0\"");
@ -61,7 +64,7 @@ class XrdsServlet extends HttpServlet {
final byte[] raw = r.toString().getBytes(ENC);
rsp.setContentLength(raw.length);
rsp.setContentType("application/xrds+xml");
rsp.setCharacterEncoding(ENC);
rsp.setCharacterEncoding(ENC.name());
try (ServletOutputStream out = rsp.getOutputStream()) {
out.write(raw);

View File

@ -14,6 +14,8 @@
package org.apache.commons.net.smtp;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.util.ssl.BlindSSLSocketFactory;
import org.apache.commons.codec.binary.Base64;
@ -35,8 +37,6 @@ import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLSocketFactory;
public class AuthSMTPClient extends SMTPClient {
private static final String UTF_8 = "UTF-8";
private String authTypes;
public AuthSMTPClient(final String charset) {
@ -65,11 +65,9 @@ public class AuthSMTPClient extends SMTPClient {
_input_ = _socket_.getInputStream();
_output_ = _socket_.getOutputStream();
_reader =
new BufferedReader(new InputStreamReader(_input_,
UTF_8));
new BufferedReader(new InputStreamReader(_input_, UTF_8));
_writer =
new BufferedWriter(new OutputStreamWriter(_output_,
UTF_8));
new BufferedWriter(new OutputStreamWriter(_output_, UTF_8));
return true;
}
@ -190,7 +188,7 @@ public class AuthSMTPClient extends SMTPClient {
return SMTPReply.isPositiveCompletion(sendCommand("AUTH", cmd));
}
private static String encodeBase64(final byte[] data) throws UnsupportedEncodingException {
private static String encodeBase64(final byte[] data) {
return new String(Base64.encodeBase64(data), UTF_8);
}
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.pgm;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.pgm.util.AbstractProgram;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.schema.java.JavaSchemaModel;
@ -45,13 +47,13 @@ public class ProtoGen extends AbstractProgram {
JavaSchemaModel jsm = new JavaSchemaModel(ReviewDb.class);
try (OutputStream o = lock.getOutputStream();
PrintWriter out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(o, "UTF-8")))) {
new BufferedWriter(new OutputStreamWriter(o, UTF_8)))) {
String header;
try (InputStream in = getClass().getResourceAsStream("ProtoGenHeader.txt")) {
ByteBuffer buf = IO.readWholeStream(in, 1024);
int ptr = buf.arrayOffset() + buf.position();
int len = buf.remaining();
header = new String(buf.array(), ptr, len, "UTF-8");
header = new String(buf.array(), ptr, len, UTF_8);
}
String version = com.google.gerrit.common.Version.getVersion();

View File

@ -14,6 +14,8 @@
package com.google.gerrit.pgm.init;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
@ -120,7 +122,7 @@ class Libraries {
if (in == null) {
throw new FileNotFoundException("Cannot load resource " + p);
}
try (Reader r = new InputStreamReader(in, "UTF-8")) {
try (Reader r = new InputStreamReader(in, UTF_8)) {
final StringBuilder buf = new StringBuilder();
final char[] tmp = new char[512];
int n;

View File

@ -16,6 +16,7 @@ package com.google.gerrit.pgm.init;
import static com.google.gerrit.pgm.init.api.InitUtil.die;
import static com.google.gerrit.pgm.init.api.InitUtil.savePublic;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.pgm.init.api.ConsoleUI;
import com.google.gerrit.pgm.init.api.InitFlags;
@ -172,8 +173,8 @@ class UpgradeFrom2_0_x implements InitStep {
return false;
}
String n = URLDecoder.decode(pair.substring(0, eq), "UTF-8");
String v = URLDecoder.decode(pair.substring(eq + 1), "UTF-8");
String n = URLDecoder.decode(pair.substring(0, eq), UTF_8.name());
String v = URLDecoder.decode(pair.substring(eq + 1), UTF_8.name());
if ("user".equals(n) || "username".equals(n)) {
username = v;

View File

@ -14,6 +14,8 @@
package com.google.gerrit.common;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -39,7 +41,7 @@ public class Version {
if (in == null) {
return "(dev)";
}
try (BufferedReader r = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
try (BufferedReader r = new BufferedReader(new InputStreamReader(in, UTF_8))) {
String vs = r.readLine();
if (vs != null && vs.startsWith("v")) {
vs = vs.substring(1);

View File

@ -14,6 +14,7 @@
package com.google.gerrit.server.documentation;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.pegdown.Extensions.ALL;
import static org.pegdown.Extensions.HARDWRAPS;
import static org.pegdown.Extensions.SUPPRESS_ALL_HTML;
@ -159,7 +160,7 @@ public class MarkdownFormatter {
try (InputStream in = url.openStream();
TemporaryBuffer.Heap tmp = new TemporaryBuffer.Heap(128 * 1024)) {
tmp.copy(in);
return new String(tmp.toByteArray(), "UTF-8");
return new String(tmp.toByteArray(), UTF_8);
}
}
}

View File

@ -15,6 +15,7 @@
package com.google.gerrit.server.git;
import static com.google.gerrit.reviewdb.client.RefNames.REFS_REJECT_COMMITS;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.errors.PermissionDeniedException;
import com.google.gerrit.reviewdb.client.Project;
@ -41,7 +42,6 @@ import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
@ -137,12 +137,12 @@ public class BanCommit {
}
private ObjectId createNoteContent(String reason, ObjectInserter inserter)
throws UnsupportedEncodingException, IOException {
throws IOException {
String noteContent = reason != null ? reason : "";
if (noteContent.length() > 0 && !noteContent.endsWith("\n")) {
noteContent = noteContent + "\n";
}
return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes("UTF-8"));
return inserter.insert(Constants.OBJ_BLOB, noteContent.getBytes(UTF_8));
}
private PersonIdent createPersonIdent() {

View File

@ -29,6 +29,8 @@
package com.google.gerrit.server.ioutil;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.reviewdb.client.CodedEnum;
import org.eclipse.jgit.util.IO;
@ -139,7 +141,7 @@ public class BasicSerialization {
if (bin.length == 0) {
return null;
}
return new String(bin, 0, bin.length, "UTF-8");
return new String(bin, 0, bin.length, UTF_8);
}
/** Write a UTF-8 string, prefixed by its byte length in a varint. */
@ -148,7 +150,7 @@ public class BasicSerialization {
if (s == null) {
writeVarInt32(output, 0);
} else {
writeBytes(output, s.getBytes("UTF-8"));
writeBytes(output, s.getBytes(UTF_8));
}
}

View File

@ -14,8 +14,6 @@
package com.google.gerrit.server.mail;
import java.io.UnsupportedEncodingException;
public class Address {
public static Address parse(final String in) {
final int lt = in.indexOf('<');
@ -69,14 +67,10 @@ public class Address {
@Override
public String toString() {
try {
return toHeaderString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Cannot encode address", e);
}
return toHeaderString();
}
public String toHeaderString() throws UnsupportedEncodingException {
public String toHeaderString() {
if (name != null) {
return quotedPhrase(name) + " <" + email + ">";
} else if (isSimple()) {
@ -98,8 +92,7 @@ public class Address {
return true;
}
private static String quotedPhrase(final String name)
throws UnsupportedEncodingException {
private static String quotedPhrase(final String name) {
if (EmailHeader.needsQuotedPrintable(name)) {
return EmailHeader.quotedPrintable(name);
}

View File

@ -14,10 +14,11 @@
package com.google.gerrit.server.mail;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.MoreObjects;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@ -104,8 +105,7 @@ public abstract class EmailHeader {
}
}
static java.lang.String quotedPrintable(java.lang.String value)
throws UnsupportedEncodingException {
static java.lang.String quotedPrintable(java.lang.String value) {
final StringBuilder r = new StringBuilder();
r.append("=?UTF-8?Q?");
@ -115,7 +115,7 @@ public abstract class EmailHeader {
r.append('_');
} else if (needsQuotedPrintableWithinPhrase(cp)) {
byte[] buf = new java.lang.String(Character.toChars(cp)).getBytes("UTF-8");
byte[] buf = new java.lang.String(Character.toChars(cp)).getBytes(UTF_8);
for (byte b: buf) {
r.append('=');
r.append(Integer.toHexString((b >>> 4) & 0x0f).toUpperCase());

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.mail;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.collect.Sets;
import com.google.gerrit.common.errors.EmailException;
import com.google.gerrit.reviewdb.client.Account;
@ -443,7 +445,7 @@ public abstract class OutgoingEmail {
if (runtime.getLoaderNameForResource(name) == null) {
name = "com/google/gerrit/server/mail/" + name;
}
Template template = runtime.getTemplate(name, "UTF-8");
Template template = runtime.getTemplate(name, UTF_8.name());
StringWriter w = new StringWriter();
template.merge(velocityContext, w);
return w.toString();

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.mail;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gwtjsonrpc.server.SignedToken;
@ -25,7 +27,6 @@ import com.google.inject.Singleton;
import org.eclipse.jgit.util.Base64;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -50,10 +51,10 @@ public class SignedTokenEmailTokenVerifier implements EmailTokenVerifier {
public String encode(Account.Id accountId, String emailAddress) {
try {
String payload = String.format("%s:%s", accountId, emailAddress);
byte[] utf8 = payload.getBytes("UTF-8");
byte[] utf8 = payload.getBytes(UTF_8);
String base64 = Base64.encodeBytes(utf8);
return emailRegistrationToken.newToken(base64);
} catch (XsrfException | UnsupportedEncodingException e) {
} catch (XsrfException e) {
throw new IllegalArgumentException(e);
}
}
@ -70,13 +71,7 @@ public class SignedTokenEmailTokenVerifier implements EmailTokenVerifier {
throw new InvalidTokenException();
}
String payload;
try {
payload = new String(Base64.decode(token.getData()), "UTF-8");
} catch (UnsupportedEncodingException err) {
throw new InvalidTokenException(err);
}
String payload = new String(Base64.decode(token.getData()), UTF_8);
Matcher matcher = Pattern.compile("^([0-9]+):(.+@.+)$").matcher(payload);
if (!matcher.matches()) {
throw new InvalidTokenException();

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.mail;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.primitives.Ints;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.Version;
@ -241,7 +243,7 @@ public class SmtpEmailSender implements EmailSender {
}
private SMTPClient open() throws EmailException {
final AuthSMTPClient client = new AuthSMTPClient("UTF-8");
final AuthSMTPClient client = new AuthSMTPClient(UTF_8.name());
if (smtpEncryption == Encryption.SSL) {
client.enableSSL(sslVerify);

View File

@ -15,6 +15,7 @@
package com.google.gerrit.server.patch;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import com.google.common.base.Function;
@ -297,7 +298,7 @@ public class PatchListLoader implements Callable<PatchList> {
aCommit != null ? Text.forCommit(reader, aCommit) : Text.EMPTY;
Text bText = Text.forCommit(reader, bCommit);
byte[] rawHdr = hdr.toString().getBytes("UTF-8");
byte[] rawHdr = hdr.toString().getBytes(UTF_8);
byte[] aContent = aText.getContent();
byte[] bContent = bText.getContent();
long sizeDelta = bContent.length - aContent.length;
@ -431,7 +432,7 @@ public class PatchListLoader implements Callable<PatchList> {
MergeResult<? extends Sequence> p = entry.getValue();
try (TemporaryBuffer buf =
new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
fmt.formatMerge(buf, p, "BASE", oursName, theirsName, "UTF-8");
fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name());
buf.close();
try (InputStream in = buf.openInputStream()) {

View File

@ -14,6 +14,9 @@
package com.google.gerrit.server.patch;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.errors.LargeObjectException;
import org.eclipse.jgit.errors.MissingObjectException;
@ -37,7 +40,6 @@ import java.text.SimpleDateFormat;
public class Text extends RawText {
private static final Logger log = LoggerFactory.getLogger(Text.class);
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
private static final int bigFileThreshold = PackConfig.DEFAULT_BIG_FILE_THRESHOLD;
public static final byte[] NO_BYTES = {};
@ -81,7 +83,7 @@ public class Text extends RawText {
appendPersonIdent(b, "Commit", c.getCommitterIdent());
b.append("\n");
b.append(c.getFullMessage());
return new Text(b.toString().getBytes("UTF-8"));
return new Text(b.toString().getBytes(UTF_8));
}
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.project;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Predicate;
import com.google.common.base.Strings;
import com.google.common.collect.FluentIterable;
@ -59,7 +61,6 @@ import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
@ -235,7 +236,7 @@ public class ListProjects implements RestReadView<TopLevelResource> {
display(buf);
return BinaryResult.create(buf.toByteArray())
.setContentType("text/plain")
.setCharacterEncoding("UTF-8");
.setCharacterEncoding(UTF_8.name());
}
return apply();
}
@ -249,12 +250,8 @@ public class ListProjects implements RestReadView<TopLevelResource> {
throws BadRequestException {
PrintWriter stdout = null;
if (displayOutputStream != null) {
try {
stdout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(displayOutputStream, "UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM lacks UTF-8 encoding", e);
}
stdout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(displayOutputStream, UTF_8)));
}
int foundIndex = 0;

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.query.change;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.data.LabelTypes;
import com.google.gerrit.reviewdb.client.PatchSet;
@ -164,7 +166,7 @@ public class OutputStreamQuery {
public void query(String queryString) throws IOException {
out = new PrintWriter( //
new BufferedWriter( //
new OutputStreamWriter(outputStream, "UTF-8")));
new OutputStreamWriter(outputStream, UTF_8)));
try {
if (queryProcessor.isDisabled()) {
ErrorMessage m = new ErrorMessage();

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.schema;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.CharMatcher;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gwtorm.jdbc.JdbcSchema;
@ -73,7 +75,7 @@ class ScriptRunner {
}
private List<String> parse(final InputStream in) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, UTF_8))) {
String delimiter = ";";
List<String> commands = new ArrayList<>();
StringBuilder buffer = new StringBuilder();

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.tools;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.Version;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@ -72,7 +74,7 @@ public class ToolsCatalog {
SortedMap<String, Entry> toc = new TreeMap<>();
final BufferedReader br =
new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
read("TOC")), "UTF-8"));
read("TOC")), UTF_8));
String line;
while ((line = br.readLine()) != null) {
if (line.length() > 0 && !line.startsWith("#")) {

View File

@ -14,6 +14,8 @@
package com.google.gerrit.server.util;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Strings;
import com.google.gerrit.common.Die;
import com.google.gerrit.server.config.GerritServerConfig;
@ -60,7 +62,7 @@ public class SystemLog {
final DailyRollingFileAppender dst = new DailyRollingFileAppender();
dst.setName(name);
dst.setLayout(layout);
dst.setEncoding("UTF-8");
dst.setEncoding(UTF_8.name());
dst.setFile(resolve(logdir).resolve(name).toString());
dst.setImmediateFlush(true);
dst.setAppend(true);

View File

@ -16,6 +16,7 @@ package com.google.gerrit.rules;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assert_;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.TimeUtil;
import com.google.inject.Guice;
@ -106,7 +107,7 @@ public abstract class PrologTestCase {
SymbolTerm pathTerm = SymbolTerm.create(prologResource);
JavaObjectTerm inTerm =
new JavaObjectTerm(new PushbackReader(new BufferedReader(
new InputStreamReader(in, "UTF-8")), Prolog.PUSHBACK_SIZE));
new InputStreamReader(in, UTF_8)), Prolog.PUSHBACK_SIZE));
if (!env.execute(Prolog.BUILTIN, "consult_stream", pathTerm, inTerm)) {
throw new CompileException("Cannot consult " + prologResource);
}

View File

@ -20,8 +20,6 @@ import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.UnsupportedEncodingException;
public class AddressTest {
@Rule
public ExpectedException exception = ExpectedException.none();
@ -155,10 +153,6 @@ public class AddressTest {
}
private static String format(final String name, final String email) {
try {
return new Address(name, email).toHeaderString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Cannot encode address", e);
}
return new Address(name, email).toHeaderString();
}
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.sshd;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.util.concurrent.Atomics;
import com.google.gerrit.common.Nullable;
import com.google.gerrit.common.TimeUtil;
@ -51,13 +53,13 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
public abstract class BaseCommand implements Command {
private static final Logger log = LoggerFactory.getLogger(BaseCommand.class);
public static final String ENC = "UTF-8";
public static final Charset ENC = UTF_8;
private static final int PRIVATE_STATUS = 1 << 30;
static final int STATUS_CANCEL = PRIVATE_STATUS | 1;
@ -309,14 +311,7 @@ public abstract class BaseCommand implements Command {
/** Wrap the supplied output stream in a UTF-8 encoded PrintWriter. */
protected static PrintWriter toPrintWriter(final OutputStream o) {
try {
return new PrintWriter(new BufferedWriter(new OutputStreamWriter(o, ENC)));
} catch (UnsupportedEncodingException e) {
// Our default encoding is required by the specifications for the
// runtime APIs, this should never, ever happen.
//
throw new RuntimeException("JVM lacks " + ENC + " encoding", e);
}
return new PrintWriter(new BufferedWriter(new OutputStreamWriter(o, ENC)));
}
private int handleError(final Throwable e) {

View File

@ -14,6 +14,7 @@
package com.google.gerrit.sshd;
import static java.nio.charset.StandardCharsets.ISO_8859_1;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Preconditions;
@ -193,7 +194,7 @@ class DatabasePubKeyAuth implements PublickeyAuthenticator {
}
try {
byte[] bin = Base64.decodeBase64(line.getBytes("ISO-8859-1"));
byte[] bin = Base64.decodeBase64(line.getBytes(ISO_8859_1));
keys.add(new Buffer(bin).getRawPublicKey());
} catch (RuntimeException | SshException e) {
logBadKey(path, line, e);

View File

@ -14,6 +14,8 @@
package com.google.gerrit.sshd;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.util.concurrent.Atomics;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.server.CurrentUser;
@ -102,7 +104,7 @@ public final class SuExec extends BaseCommand {
if (!msg.endsWith("\n")) {
msg += "\n";
}
err.write(msg.getBytes("UTF-8"));
err.write(msg.getBytes(UTF_8));
err.flush();
onExit(1);
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.sshd.commands;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.gerrit.common.data.GlobalCapability;
@ -33,7 +35,6 @@ import org.kohsuke.args4j.Option;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
@ -82,14 +83,14 @@ final class CreateAccountCommand extends SshCommand {
}
}
private String readSshKey() throws UnsupportedEncodingException, IOException {
private String readSshKey() throws IOException {
if (sshKey == null) {
return null;
}
if ("-".equals(sshKey)) {
sshKey = "";
BufferedReader br =
new BufferedReader(new InputStreamReader(in, "UTF-8"));
new BufferedReader(new InputStreamReader(in, UTF_8));
String line;
while ((line = br.readLine()) != null) {
sshKey += line + "\n";

View File

@ -14,6 +14,8 @@
package com.google.gerrit.sshd.commands;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.Version;
import com.google.gerrit.reviewdb.server.ReviewDb;
@ -32,7 +34,6 @@ import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
@ -65,11 +66,10 @@ public class QueryShell {
@Inject
QueryShell(final SchemaFactory<ReviewDb> dbFactory,
@Assisted final InputStream in, @Assisted final OutputStream out)
throws UnsupportedEncodingException {
@Assisted final InputStream in, @Assisted final OutputStream out) {
this.dbFactory = dbFactory;
this.in = new BufferedReader(new InputStreamReader(in, "UTF-8"));
this.out = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
this.in = new BufferedReader(new InputStreamReader(in, UTF_8));
this.out = new PrintWriter(new OutputStreamWriter(out, UTF_8));
}
public void setOutputFormat(OutputFormat fmt) {

View File

@ -22,6 +22,8 @@
*/
package com.google.gerrit.sshd.commands;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.server.tools.ToolsCatalog;
import com.google.gerrit.server.tools.ToolsCatalog.Entry;
import com.google.gerrit.sshd.BaseCommand;
@ -188,7 +190,7 @@ final class ScpCommand extends BaseCommand {
}
}
out.write("E\n".getBytes("UTF-8"));
out.write("E\n".getBytes(UTF_8));
out.flush();
readAck();
}
@ -210,7 +212,7 @@ final class ScpCommand extends BaseCommand {
buf.append(" ");
buf.append(dir.getName());
buf.append("\n");
out.write(buf.toString().getBytes("UTF-8"));
out.write(buf.toString().getBytes(UTF_8));
out.flush();
}

View File

@ -14,6 +14,8 @@
package com.google.gerrit.sshd.commands;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.base.Strings;
import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.common.errors.EmailException;
@ -226,7 +228,7 @@ final class SetAccountCommand extends SshCommand {
in.raw = new RawInput() {
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(sshKey.getBytes("UTF-8"));
return new ByteArrayInputStream(sshKey.getBytes(UTF_8));
}
@Override
@ -312,7 +314,7 @@ final class SetAccountCommand extends SshCommand {
if (idx >= 0) {
StringBuilder sshKey = new StringBuilder();
BufferedReader br =
new BufferedReader(new InputStreamReader(in, "UTF-8"));
new BufferedReader(new InputStreamReader(in, UTF_8));
String line;
while ((line = br.readLine()) != null) {
sshKey.append(line)

View File

@ -15,6 +15,7 @@
package com.google.gerrit.sshd.commands;
import static com.google.gerrit.sshd.CommandMetaData.Mode.MASTER;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.common.EventListener;
import com.google.gerrit.common.EventSource;
@ -125,7 +126,7 @@ final class StreamEvents extends BaseCommand {
if (!msg.endsWith("\n")) {
msg += "\n";
}
err.write(msg.getBytes("UTF-8"));
err.write(msg.getBytes(UTF_8));
err.flush();
onExit(1);
return;

View File

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.gerrit.server.documentation.Constants;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
@ -108,7 +110,7 @@ public class DocIndexer {
String title;
try (BufferedReader titleReader = new BufferedReader(
new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
new InputStreamReader(new FileInputStream(file), UTF_8))) {
title = titleReader.readLine();
if (title != null && title.startsWith("[[")) {
// Generally the first line of the txt is the title. In a few cases the