StandardCharsets used where possible; try-with-resources used; cleanup

This commit is contained in:
Tagir Valeev
2018-03-14 16:03:32 +07:00
parent 18550560ed
commit fb60f19349
17 changed files with 62 additions and 90 deletions
@@ -21,6 +21,7 @@ import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
/**
@@ -76,7 +77,7 @@ class ProcessProxyImpl implements ProcessProxy {
private void writeLine(String s) {
execute(() -> {
ByteBuffer out = ByteBuffer.wrap((s + '\n').getBytes("US-ASCII"));
ByteBuffer out = ByteBuffer.wrap((s + '\n').getBytes(StandardCharsets.US_ASCII));
synchronized (myLock) {
myConnection.write(out);
}
@@ -25,6 +25,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.api.GlobalOptions;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @author Eugene Zhuravlev
@@ -48,7 +49,7 @@ public class LogSetup {
String text = FileUtil.loadFile(configFile);
final String logFile = logDir != null? new File(logDir, LOG_FILE_NAME).getAbsolutePath() : LOG_FILE_NAME;
text = StringUtil.replace(text, LOG_FILE_MACRO, StringUtil.replace(logFile, "\\", "\\\\"));
PropertyConfigurator.configure(new ByteArrayInputStream(text.getBytes("UTF-8")));
PropertyConfigurator.configure(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
}
catch (IOException e) {
//noinspection UseOfSystemOutOrSystemErr
@@ -63,20 +64,11 @@ public class LogSetup {
private static void ensureLogConfigExists(final File logConfig) throws IOException {
if (!logConfig.exists()) {
FileUtil.createIfDoesntExist(logConfig);
@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
final InputStream in = LogSetup.class.getResourceAsStream("/" + DEFAULT_LOGGER_CONFIG);
if (in != null) {
try {
final FileOutputStream out = new FileOutputStream(logConfig);
try {
try(InputStream in = LogSetup.class.getResourceAsStream("/" + DEFAULT_LOGGER_CONFIG)) {
if (in != null) {
try (FileOutputStream out = new FileOutputStream(logConfig)) {
FileUtil.copy(in, out);
}
finally {
out.close();
}
}
finally {
in.close();
}
}
}
@@ -16,13 +16,13 @@
package org.jetbrains.jps.incremental.artifacts;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.PathUtil;
import org.jetbrains.jps.model.artifact.JpsArtifact;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@@ -170,22 +170,16 @@ public class ArtifactBuilderOverwriteTest extends ArtifactBuilderTestCase {
}
private String createArchive(String relativeArchivePath, String fileNameInArchive, String text) {
try {
File file = new File(getOrCreateProjectDir(), relativeArchivePath);
ZipOutputStream output = new ZipOutputStream(new FileOutputStream(file));
try {
output.putNextEntry(new ZipEntry(fileNameInArchive));
output.write(text.getBytes(CharsetToolkit.UTF8));
output.closeEntry();
}
finally {
output.close();
}
return FileUtil.toSystemIndependentName(file.getAbsolutePath());
File file = new File(getOrCreateProjectDir(), relativeArchivePath);
try (ZipOutputStream output = new ZipOutputStream(new FileOutputStream(file))) {
output.putNextEntry(new ZipEntry(fileNameInArchive));
output.write(text.getBytes(StandardCharsets.UTF_8));
output.closeEntry();
}
catch (IOException e) {
throw new RuntimeException(e);
}
return FileUtil.toSystemIndependentName(file.getAbsolutePath());
}
public void testFileOrder() {
@@ -25,13 +25,13 @@ import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.PathExecLazyValue;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -53,7 +53,7 @@ public class ExecUtil {
throw new IOException("Template '" + templateName + "' not found by " + loader);
}
String template = FileUtil.loadTextAndClose(new InputStreamReader(stream, CharsetToolkit.UTF8));
String template = FileUtil.loadTextAndClose(new InputStreamReader(stream, StandardCharsets.UTF_8));
if (variables == null || variables.size() == 0) {
return template;
}
@@ -73,7 +73,7 @@ public class ExecUtil {
public static File createTempExecutableScript(@NotNull String prefix, @NotNull String suffix, @NotNull String content) throws IOException, ExecutionException {
File tempDir = new File(PathManager.getTempPath());
File tempFile = FileUtil.createTempFile(tempDir, prefix, suffix, true, true);
FileUtil.writeToFile(tempFile, content.getBytes(CharsetToolkit.UTF8));
FileUtil.writeToFile(tempFile, content.getBytes(StandardCharsets.UTF_8));
if (!tempFile.setExecutable(true, true)) {
throw new ExecutionException("Failed to make temp file executable: " + tempFile);
}
@@ -16,7 +16,6 @@
package com.intellij.jps.impl;
import com.intellij.openapi.extensions.*;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -26,6 +25,7 @@ import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
@@ -120,8 +120,7 @@ public class JpsIdePluginManagerImpl extends JpsPluginManager {
private static List<String> loadClassNames(URL url) throws IOException {
List<String> result = new ArrayList<>();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), CharsetToolkit.UTF8));
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = in.readLine()) != null) {
int i = line.indexOf('#');
@@ -132,9 +131,6 @@ public class JpsIdePluginManagerImpl extends JpsPluginManager {
}
}
}
finally {
in.close();
}
return result;
}
}
@@ -76,6 +76,7 @@ import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Random;
import java.util.concurrent.ExecutionException;
@@ -783,7 +784,7 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase {
WriteCommandAction.runWriteCommandAction(null, () -> {
try {
virtualFile.setBinaryContent("\n txt txt txt".getBytes("UTF-8"));
virtualFile.setBinaryContent("\n txt txt txt".getBytes(StandardCharsets.UTF_8));
virtualFile.rename(this, "X.txt");
}
catch (IOException e) {
@@ -22,6 +22,7 @@ import org.jdom.Element;
import org.jetbrains.annotations.NotNull;
import java.io.*;
import java.nio.charset.StandardCharsets;
public class EclipseJDOMUtil {
private EclipseJDOMUtil() {
@@ -40,13 +41,9 @@ public class EclipseJDOMUtil {
}
public static void output(@NotNull Element element, @NotNull File file, @NotNull Project project) throws IOException {
Writer writer = new OutputStreamWriter(new FileOutputStream(file), CharsetToolkit.UTF8);
try {
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
output(element, writer, project);
}
finally {
writer.close();
}
}
public static void output(@NotNull Element element, @NotNull Writer writer, @NotNull Project project) throws IOException {
@@ -22,6 +22,7 @@ import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Pattern;
@@ -110,8 +111,7 @@ public class SSHConfig {
// no config file = empty config file
return rc;
}
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), "ISO-8859-1"));
try {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), StandardCharsets.ISO_8859_1))) {
Host host = null;
String line;
while ((line = in.readLine()) != null) {
@@ -172,9 +172,6 @@ public class SSHConfig {
}
}
}
finally {
in.close();
}
return rc;
}
@@ -43,6 +43,7 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -380,7 +381,7 @@ public class GitRebaser {
/**
* The constructor from fields that is expected to be
* accessed only from {@link git4idea.rebase.GitRebaseEditorService}.
* accessed only from {@link GitRebaseEditorService}.
*
* @param rebaseEditorService
* @param root the git repository root
@@ -413,8 +414,7 @@ public class GitRebaser {
String commit = s.spaceToken();
pickLines.put(commit, "pick " + commit + " " + s.line());
}
PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8));
try {
try (PrintWriter w = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8))) {
for (String commit : myCommits) {
String key = pickLines.headMap(commit + "\u0000").lastKey();
if (key == null || !commit.startsWith(key)) {
@@ -423,9 +423,6 @@ public class GitRebaser {
w.print(pickLines.get(key) + "\n");
}
}
finally {
w.close();
}
return 0;
}
catch (Exception ex) {
@@ -9,6 +9,7 @@ import org.jetbrains.java.decompiler.main.extern.IResultSaver;
import org.jetbrains.java.decompiler.util.InterpreterUtil;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
@@ -238,7 +239,7 @@ public class ConsoleDecompiler implements IBytecodeProvider, IResultSaver {
ZipOutputStream out = mapArchiveStreams.get(file);
out.putNextEntry(new ZipEntry(entryName));
if (content != null) {
out.write(content.getBytes("UTF-8"));
out.write(content.getBytes(StandardCharsets.UTF_8));
}
}
catch (IOException ex) {
@@ -8,6 +8,7 @@ import org.jetbrains.java.decompiler.util.InterpreterUtil;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@@ -106,7 +107,7 @@ public class DecompilerTestFixture {
private static String getContent(File expected) {
try {
return new String(InterpreterUtil.getBytes(expected), "UTF-8").replace("\r\n", "\n");
return new String(InterpreterUtil.getBytes(expected), StandardCharsets.UTF_8).replace("\r\n", "\n");
}
catch (IOException e) {
throw new RuntimeException(e);
@@ -3,7 +3,7 @@ package com.jetbrains.python.debugger.pydev;
import com.jetbrains.python.debugger.PyDebuggerException;
import org.jetbrains.annotations.NotNull;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class ProtocolFrame {
@@ -12,7 +12,7 @@ public class ProtocolFrame {
private final int mySequence;
private @NotNull final String myPayload;
public ProtocolFrame(final int command, final int sequence, @NotNull final String payload) throws PyDebuggerException {
public ProtocolFrame(final int command, final int sequence, @NotNull final String payload) {
myCommand = command;
mySequence = sequence;
myPayload = payload;
@@ -20,13 +20,13 @@ public class ProtocolFrame {
public ProtocolFrame(final String frame) throws PyDebuggerException {
final String[] parts = frame.split("\t", 3);
if (parts == null || parts.length < 2) {
if (parts.length < 2) {
throw new PyDebuggerException("Bad frame: " + frame);
}
myCommand = Integer.parseInt(parts[0]);
mySequence = Integer.parseInt(parts[1]);
myPayload = (parts.length == 3 && !"".equals(parts[2]) ? ProtocolParser.decode(parts[2]) : "").trim();
myPayload = (parts.length == 3 && !parts[2].isEmpty() ? ProtocolParser.decode(parts[2]) : "").trim();
}
public int getCommand() {
@@ -43,28 +43,25 @@ public class ProtocolFrame {
}
@NotNull
public byte[] pack() throws UnsupportedEncodingException {
final StringBuilder sb = new StringBuilder();
sb.append(Integer.toString(myCommand));
sb.append('\t');
sb.append(Integer.toString(mySequence));
sb.append('\t');
sb.append(myPayload);
sb.append('\n');
return sb.toString().getBytes("UTF-8");
public byte[] pack() {
String s = String.valueOf(myCommand) +
'\t' +
mySequence +
'\t' +
myPayload +
'\n';
return s.getBytes(StandardCharsets.UTF_8);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append('[');
sb.append(Integer.toString(myCommand));
sb.append(':');
sb.append(Integer.toString(mySequence));
sb.append(':');
sb.append(myPayload);
sb.append(']');
return sb.toString();
return "[" +
myCommand +
':' +
mySequence +
':' +
myPayload +
']';
}
}
@@ -16,6 +16,7 @@
package com.intellij.updater;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
@@ -50,7 +51,7 @@ public class CreateAction extends PatchAction {
private static void writeLinkInfo(File file, OutputStream out) throws IOException {
String target = Utils.readLink(file);
if (target.isEmpty()) throw new IOException("Invalid link: " + file);
byte[] bytes = target.getBytes("UTF-8");
byte[] bytes = target.getBytes(StandardCharsets.UTF_8);
out.write(bytes.length);
out.write(bytes);
}
@@ -127,7 +128,7 @@ public class CreateAction extends PatchAction {
int length = in.read();
if (length <= 0) throw new IOException("Stream format error");
byte[] bytes = Utils.readBytes(in, length);
return new String(bytes, "UTF-8");
return new String(bytes, StandardCharsets.UTF_8);
}
protected void doBackup(File toFile, File backupFile) {
@@ -16,6 +16,7 @@
package com.intellij.updater;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
@@ -48,7 +49,7 @@ public class Digester {
if (attrs.isSymbolicLink()) {
Path target = Files.readSymbolicLink(path);
if (target.isAbsolute()) throw new IOException("Absolute link: " + file + " -> " + target);
return digestStream(new ByteArrayInputStream(target.toString().getBytes("UTF-8"))) | LINK_MASK;
return digestStream(new ByteArrayInputStream(target.toString().getBytes(StandardCharsets.UTF_8))) | LINK_MASK;
}
if (attrs.isDirectory()) return DIRECTORY;
+2 -1
View File
@@ -31,6 +31,7 @@ import com.intellij.updater.Utils;
import com.intellij.updater.Utils.OpenByteArrayOutputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPOutputStream;
/**
@@ -470,7 +471,7 @@ public class JBDiff {
diffOut.close();
DataOutputStream headerStream = new DataOutputStream(diffFileOut);
headerStream.write("jbdiff40".getBytes("US-ASCII"));
headerStream.write("jbdiff40".getBytes(StandardCharsets.US_ASCII));
headerStream.writeLong(ctrlBlockLen); // ctrlBlockLen (compressed)
headerStream.writeLong(diffBlockLen); // diffBlockLen (compressed)
headerStream.writeLong(newsize);
@@ -23,6 +23,7 @@ import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
@@ -220,7 +221,7 @@ public abstract class PatchApplyingRevertingTest extends PatchTestCase {
@Test
public void testApplyingWithAbsentOptionalFile() throws Exception {
FileUtil.writeToFile(new File(myNewerDir, "bin/idea.bat"), "new content".getBytes("UTF-8"));
FileUtil.writeToFile(new File(myNewerDir, "bin/idea.bat"), "new content".getBytes(StandardCharsets.UTF_8));
myPatchSpec.setOptionalFiles(Collections.singletonList("bin/idea.bat"));
createPatch();
@@ -30,8 +30,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class HtmlFileType extends XmlLikeFileType {
@NonNls public static final String DOT_DEFAULT_EXTENSION = ".html";
@@ -78,13 +78,7 @@ public class HtmlFileType extends XmlLikeFileType {
: XmlCharsetDetector.extractXmlEncodingFromProlog(content);
if (charset != null) return charset;
@NonNls String strContent;
try {
strContent = new String(content, "ISO-8859-1");
}
catch (UnsupportedEncodingException e) {
return null;
}
@NonNls String strContent = new String(content, StandardCharsets.ISO_8859_1);
Charset c = HtmlUtil.detectCharsetFromMetaTag(strContent);
return c == null ? null : c.name();
}