From 5ec27be683e2423b7a46aa38ed23e35f741b508e Mon Sep 17 00:00:00 2001 From: andrey alekseenko Date: Tue, 7 May 2024 21:13:49 +0600 Subject: [PATCH] cleanup:use standard methods instead of alternatives from third party library --- .../classloading/ApplicationClassloader.java | 27 ++------ framework/src/play/libs/Files.java | 12 ++-- framework/src/play/libs/IO.java | 57 ++++++---------- .../src/play/mvc/results/RenderBinary.java | 15 ++-- framework/src/play/server/FileService.java | 5 +- framework/src/play/server/PlayHandler.java | 6 +- framework/src/play/server/ServletWrapper.java | 14 ++-- .../play/server/StreamChunkAggregator.java | 3 +- framework/src/play/utils/Java.java | 17 ++--- .../src/play/utils/OrderSafeProperties.java | 68 +++++++------------ framework/src/play/vfs/VirtualFile.java | 36 +++------- 11 files changed, 79 insertions(+), 181 deletions(-) diff --git a/framework/src/play/classloading/ApplicationClassloader.java b/framework/src/play/classloading/ApplicationClassloader.java index da1ac216ca..36f6210b32 100644 --- a/framework/src/play/classloading/ApplicationClassloader.java +++ b/framework/src/play/classloading/ApplicationClassloader.java @@ -2,7 +2,6 @@ import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableMap; -import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.File; import java.io.IOException; @@ -22,14 +21,10 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; - import play.Logger; import play.Play; import play.cache.Cache; @@ -221,12 +216,10 @@ byte[] getClassDefinition(String name) { if (is == null) { return null; } - try { - return IOUtils.toByteArray(is); + try (is) { + return is.readAllBytes(); } catch (Exception e) { throw new UnexpectedException(e); - } finally { - closeQuietly(is); } } @@ -238,7 +231,6 @@ public InputStream getResourceAsStream(String name) { return res.inputstream(); } } - URL url = getResource(name); return super.getResourceAsStream(name); } @@ -293,19 +285,8 @@ public Enumeration getResources(String name) throws IOException { urls.add(next); } } - final Iterator it = urls.iterator(); - return new Enumeration() { - @Override - public boolean hasMoreElements() { - return it.hasNext(); - } - - @Override - public URL nextElement() { - return it.next(); - } - }; + return Collections.enumeration(urls); } /** @@ -452,7 +433,7 @@ public List> getAllClasses() { for (ApplicationClass clazz : Play.classes.all()) { byNormalizedName.put(clazz.name.toLowerCase(), clazz); if (clazz.name.contains("$")) { - byNormalizedName.put(StringUtils.replace(clazz.name.toLowerCase(), "$", "."), clazz); + byNormalizedName.put(clazz.name.toLowerCase().replace('$', '.'), clazz); } } diff --git a/framework/src/play/libs/Files.java b/framework/src/play/libs/Files.java index 76f76c9d8e..06fd24aa47 100644 --- a/framework/src/play/libs/Files.java +++ b/framework/src/play/libs/Files.java @@ -9,14 +9,12 @@ import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; - import play.Logger; import play.exceptions.UnexpectedException; @@ -74,7 +72,7 @@ public static void copy(File from, File to) { } try { - FileUtils.copyFile(from, to); + java.nio.file.Files.copy(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { throw new RuntimeException(e); } @@ -118,9 +116,9 @@ public static boolean deleteDirectory(File path) { public static boolean copyDir(File from, File to) { try { - FileUtils.copyDirectory(from, to); + IO.copyDirectory(from, to); return true; - } catch (IOException e) { + } catch (Exception e) { return false; } } @@ -221,7 +219,7 @@ static void zipDirectory(File root, File directory, ZipOutputStream zos) throws String path = item.getAbsolutePath().substring(root.getAbsolutePath().length() + 1); ZipEntry anEntry = new ZipEntry(path); zos.putNextEntry(anEntry); - IOUtils.copyLarge(fis, zos); + fis.transferTo(zos); } } } diff --git a/framework/src/play/libs/IO.java b/framework/src/play/libs/IO.java index 5b7edcd8c2..c07d22bc9f 100644 --- a/framework/src/play/libs/IO.java +++ b/framework/src/play/libs/IO.java @@ -4,22 +4,22 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.apache.commons.io.Charsets.toCharset; -import static org.apache.commons.io.IOUtils.closeQuietly; +import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.io.OutputStream; -import java.io.UncheckedIOException; +import java.nio.channels.Channels; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Properties; +import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.commons.io.IOUtils; - import play.exceptions.UnexpectedException; import play.utils.OrderSafeProperties; @@ -37,13 +37,11 @@ public class IO { */ public static Properties readUtf8Properties(InputStream is) { Properties properties = new OrderSafeProperties(); - try { + try (is) { properties.load(is); return properties; } catch (Exception e) { throw new RuntimeException(e); - } finally { - closeQuietly(is); } } @@ -69,7 +67,7 @@ public static String readContentAsString(InputStream is) { */ public static String readContentAsString(InputStream is, String encoding) { try { - return IOUtils.toString(is, encoding); + return new String(is.readAllBytes(), toCharset(encoding)); } catch (Exception e) { throw new RuntimeException(e); } @@ -108,11 +106,7 @@ public static String readContentAsString(File file, String encoding) { } public static List readLines(InputStream is) { - try { - return IOUtils.readLines(is, defaultCharset()); - } catch (UncheckedIOException ex) { - throw new UnexpectedException(ex); - } + return new BufferedReader(new InputStreamReader(is, defaultCharset())).lines().collect(Collectors.toList()); } public static List readLines(File file, String encoding) { @@ -155,7 +149,7 @@ public static byte[] readContent(File file) { */ public static byte[] readContent(InputStream is) { try { - return IOUtils.toByteArray(is); + return is.readAllBytes(); } catch (IOException e) { throw new UnexpectedException(e); } @@ -170,12 +164,12 @@ public static byte[] readContent(InputStream is) { * The stream to write */ public static void writeContent(CharSequence content, OutputStream os) { - try { - IOUtils.write(content, os, UTF_8); + try (os) { + if (content != null) { + Channels.newChannel(os).write(UTF_8.encode(content.toString())); + } } catch (IOException e) { throw new UnexpectedException(e); - } finally { - closeQuietly(os); } } @@ -190,12 +184,12 @@ public static void writeContent(CharSequence content, OutputStream os) { * Encoding to used */ public static void writeContent(CharSequence content, OutputStream os, String encoding) { - try { - IOUtils.write(content, os, encoding); + try (os) { + if (content != null) { + Channels.newChannel(os).write(toCharset(encoding).encode(content.toString())); + } } catch (IOException e) { throw new UnexpectedException(e); - } finally { - closeQuietly(os); } } @@ -258,12 +252,10 @@ public static void write(byte[] data, File file) { * The destination stream */ public static void copy(InputStream is, OutputStream os) { - try { + try (is) { is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); - } finally { - closeQuietly(is); } } @@ -276,13 +268,10 @@ public static void copy(InputStream is, OutputStream os) { * The destination stream */ public static void write(InputStream is, OutputStream os) { - try { + try (is; os) { is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); - } finally { - closeQuietly(is); - closeQuietly(os); } } @@ -295,14 +284,8 @@ public static void write(InputStream is, OutputStream os) { * The destination file */ public static void write(InputStream is, File f) { - try { - OutputStream os = new FileOutputStream(f); - try { - is.transferTo(os); - } finally { - closeQuietly(is); - closeQuietly(os); - } + try (is; var os = new FileOutputStream(f)) { + is.transferTo(os); } catch (IOException e) { throw new UnexpectedException(e); } diff --git a/framework/src/play/mvc/results/RenderBinary.java b/framework/src/play/mvc/results/RenderBinary.java index 91d78b0e97..20d4f3302c 100644 --- a/framework/src/play/mvc/results/RenderBinary.java +++ b/framework/src/play/mvc/results/RenderBinary.java @@ -1,18 +1,14 @@ package play.mvc.results; -import static org.apache.commons.io.IOUtils.closeQuietly; +import static java.nio.charset.StandardCharsets.US_ASCII; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetEncoder; -import java.nio.charset.StandardCharsets; import org.apache.commons.codec.net.URLCodec; -import org.apache.commons.io.IOUtils; import play.exceptions.UnexpectedException; import play.libs.MimeTypes; @@ -204,16 +200,13 @@ private String dispositionType() { } private static void copyInputStreamAndClose(InputStream is, OutputStream out) throws IOException { - try { - IOUtils.copyLarge(is, out); - } finally { - closeQuietly(is); + try (is) { + is.transferTo(out); } } private boolean canAsciiEncode(String string) { - CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder(); - return asciiEncoder.canEncode(string); + return US_ASCII.newEncoder().canEncode(string); } public boolean isInline() { diff --git a/framework/src/play/server/FileService.java b/framework/src/play/server/FileService.java index 9b94575527..276a5a2c0d 100644 --- a/framework/src/play/server/FileService.java +++ b/framework/src/play/server/FileService.java @@ -22,15 +22,13 @@ import java.util.Arrays; import java.util.Comparator; -import static org.apache.commons.io.IOUtils.closeQuietly; import static org.jboss.netty.buffer.ChannelBuffers.wrappedBuffer; import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; public class FileService { public static void serve(File localFile, HttpRequest nettyRequest, HttpResponse nettyResponse, ChannelHandlerContext ctx, Request request, Response response, Channel channel) throws FileNotFoundException { - RandomAccessFile raf = new RandomAccessFile(localFile, "r"); - try { + try (RandomAccessFile raf = new RandomAccessFile(localFile, "r")) { long fileLength = raf.length(); boolean isKeepAlive = HttpHeaders.isKeepAlive(nettyRequest) && nettyRequest.getProtocolVersion().equals(HttpVersion.HTTP_1_1); @@ -82,7 +80,6 @@ public static void serve(File localFile, HttpRequest nettyRequest, HttpResponse } } catch (Throwable exx) { exx.printStackTrace(); - closeQuietly(raf); try { if (ctx.getChannel().isOpen()) { ctx.getChannel().close(); diff --git a/framework/src/play/server/PlayHandler.java b/framework/src/play/server/PlayHandler.java index 5a1291e0b8..ecab8794bb 100644 --- a/framework/src/play/server/PlayHandler.java +++ b/framework/src/play/server/PlayHandler.java @@ -1,6 +1,5 @@ package play.server; -import org.apache.commons.io.IOUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.buffer.ChannelBuffers; @@ -568,10 +567,7 @@ public Request parseRequest(ChannelHandlerContext ctx, HttpRequest nettyRequest, } } else { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(new ChannelBufferInputStream(b), out); - byte[] n = out.toByteArray(); - body = new ByteArrayInputStream(n); + body = new ByteArrayInputStream(new ChannelBufferInputStream(b).readAllBytes()); } String host = nettyRequest.headers().get(HOST); diff --git a/framework/src/play/server/ServletWrapper.java b/framework/src/play/server/ServletWrapper.java index 708f390e23..3f0d6a7efd 100644 --- a/framework/src/play/server/ServletWrapper.java +++ b/framework/src/play/server/ServletWrapper.java @@ -1,6 +1,5 @@ package play.server; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import play.Invoker; import play.Invoker.InvocationContext; @@ -39,8 +38,6 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.apache.commons.io.IOUtils.closeQuietly; - /** * Servlet implementation. * Thanks to Lee Breisacher. @@ -474,7 +471,7 @@ public void copyResponse(Request request, Response response, HttpServletRequest // Content response.out.flush(); - if (response.direct != null && response.direct instanceof File) { + if (response.direct instanceof File) { File file = (File) response.direct; servletResponse.setHeader("Content-Length", String.valueOf(file.length())); if (!request.method.equals("HEAD")) { @@ -482,7 +479,7 @@ public void copyResponse(Request request, Response response, HttpServletRequest } else { copyStream(servletResponse, new ByteArrayInputStream(new byte[0])); } - } else if (response.direct != null && response.direct instanceof InputStream) { + } else if (response.direct instanceof InputStream) { copyStream(servletResponse, (InputStream) response.direct); } else { byte[] content = response.out.toByteArray(); @@ -498,12 +495,10 @@ public void copyResponse(Request request, Response response, HttpServletRequest private void copyStream(HttpServletResponse servletResponse, InputStream is) throws IOException { if (servletResponse != null && is != null) { - try { + try (is) { OutputStream os = servletResponse.getOutputStream(); - IOUtils.copyLarge(is, os); + is.transferTo(os); os.flush(); - } finally { - closeQuietly(is); } } } @@ -547,7 +542,6 @@ public void run() { super.run(); } catch (Exception e) { serve500(e, httpServletRequest, httpServletResponse); - return; } } diff --git a/framework/src/play/server/StreamChunkAggregator.java b/framework/src/play/server/StreamChunkAggregator.java index 98007dd04c..a814c2bc42 100644 --- a/framework/src/play/server/StreamChunkAggregator.java +++ b/framework/src/play/server/StreamChunkAggregator.java @@ -1,6 +1,5 @@ package play.server; -import org.apache.commons.io.IOUtils; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.HttpChunk; @@ -59,7 +58,7 @@ public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Ex if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.headers().set(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { - IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); + new ChannelBufferInputStream(chunk.getContent()).transferTo(this.out); if (chunk.isLast()) { this.out.flush(); diff --git a/framework/src/play/utils/Java.java b/framework/src/play/utils/Java.java index 0f36341ed0..cebdc8eda3 100644 --- a/framework/src/play/utils/Java.java +++ b/framework/src/play/utils/Java.java @@ -1,8 +1,6 @@ package play.utils; import static java.util.Collections.addAll; -import static java.util.Collections.sort; -import static org.apache.commons.io.IOUtils.closeQuietly; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -345,16 +343,11 @@ public static byte[] serialize(Object o) throws IOException { } public static Object deserialize(byte[] b) throws Exception { - ByteArrayInputStream bais = new ByteArrayInputStream(b); - try { - ObjectInputStream oi = new ObjectInputStream(bais); - try { - return oi.readObject(); - } finally { - closeQuietly(oi); - } - } finally { - closeQuietly(bais); + try ( + ByteArrayInputStream bais = new ByteArrayInputStream(b); + ObjectInputStream oi = new ObjectInputStream(bais) + ) { + return oi.readObject(); } } diff --git a/framework/src/play/utils/OrderSafeProperties.java b/framework/src/play/utils/OrderSafeProperties.java index 2279c4b0e4..a81db26f0d 100644 --- a/framework/src/play/utils/OrderSafeProperties.java +++ b/framework/src/play/utils/OrderSafeProperties.java @@ -1,15 +1,18 @@ package play.utils; -import org.apache.commons.io.IOUtils; import org.apache.commons.text.StringEscapeUtils; +import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UncheckedIOException; import java.util.*; import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; /** * Custom impl of java.util.properties that preserves the key-order from the file @@ -22,25 +25,27 @@ public class OrderSafeProperties extends java.util.Properties { @Override public void load(InputStream inputStream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); // read all lines from file as utf-8 - List lines = IOUtils.readLines(inputStream, "utf-8"); - IOUtils.closeQuietly(inputStream); - - ByteArrayOutputStream out = new ByteArrayOutputStream(); - // escape "special-chars" (to utf-16 on the format \\uxxxx) in lines and store as iso-8859-1 - // see info about escaping - http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html - "public void load(InputStream inStream)" - for (String line : lines) { - - // due to "...by the rule above, single and double quote characters preceded - // by a backslash still yield single and double quote characters, respectively." - // we must transform \" => " and \' => ' before escaping to prevent escaping the backslash - line = line.replaceAll("\\\\\"", "\"").replaceAll("(^|[^\\\\])(\\\\')", "$1'"); - - String escapedLine = StringEscapeUtils.escapeJava( line ) + "\n"; - // remove escaped backslashes - escapedLine = escapedLine.replaceAll("\\\\\\\\","\\\\"); - out.write( escapedLine.getBytes(ISO_8859_1)); + try (var r = new BufferedReader(new InputStreamReader(inputStream, UTF_8))) { + // escape "special-chars" (to utf-16 on the format \\uxxxx) in lines and store as iso-8859-1 + // see info about escaping - http://download.oracle.com/javase/1.5.0/docs/api/java/util/Properties.html - "public void load(InputStream inStream)" + r.lines().forEach(line -> { + // due to "...by the rule above, single and double quote characters preceded + // by a backslash still yield single and double quote characters, respectively." + // we must transform \" => " and \' => ' before escaping to prevent escaping the backslash + line = line.replaceAll("\\\\\"", "\"").replaceAll("(^|[^\\\\])(\\\\')", "$1'"); + + String escapedLine = StringEscapeUtils.escapeJava( line ) + '\n'; + // remove escaped backslashes + escapedLine = escapedLine.replaceAll("\\\\\\\\","\\\\"); + try { + out.write(escapedLine.getBytes(ISO_8859_1)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }); } // read properties-file with regular java.util.Properties impl @@ -85,35 +90,10 @@ public void putAll(Map map) { public Set> entrySet() { Set> entrySet = new LinkedHashSet<>(keys.size()); for (Object key : keys) { - entrySet.add(new Entry(key, get(key))); + entrySet.add(Map.entry(key, get(key))); } return entrySet; } - static class Entry implements Map.Entry { - private final Object key; - private final Object value; - - private Entry(Object key, Object value) { - this.key = key; - this.value = value; - } - - @Override - public Object getKey() { - return key; - } - - @Override - public Object getValue() { - return value; - } - - @Override - public Object setValue(Object o) { - throw new IllegalStateException("not implemented"); - } - } - } diff --git a/framework/src/play/vfs/VirtualFile.java b/framework/src/play/vfs/VirtualFile.java index 95d55084e6..cb86e2d0be 100644 --- a/framework/src/play/vfs/VirtualFile.java +++ b/framework/src/play/vfs/VirtualFile.java @@ -1,7 +1,5 @@ package play.vfs; -import static org.apache.commons.io.IOUtils.closeQuietly; - import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -9,6 +7,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.io.UncheckedIOException; import java.nio.channels.Channel; import java.security.AccessControlException; import java.util.ArrayList; @@ -19,8 +18,6 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.commons.io.IOUtils; - import play.Play; import play.exceptions.UnexpectedException; import play.libs.IO; @@ -161,15 +158,12 @@ public VirtualFile child(String name) { } public Channel channel() { - try { - FileInputStream fis = new FileInputStream(realFile); - try { - return fis.getChannel(); - } finally { - closeQuietly(fis); - } + try (FileInputStream fis = new FileInputStream(realFile)) { + return fis.getChannel(); } catch (FileNotFoundException e) { return null; + } catch (IOException e) { + throw new UncheckedIOException(e); } } @@ -182,13 +176,8 @@ public static VirtualFile open(File file) { } public String contentAsString() { - try { - InputStream is = inputstream(); - try { - return IO.readContentAsString(is); - } finally { - closeQuietly(is); - } + try (InputStream is = inputstream()) { + return IO.readContentAsString(is); } catch (Exception e) { throw new UnexpectedException(e); } @@ -207,13 +196,8 @@ public void write(CharSequence string) { } public byte[] content() { - try { - InputStream is = inputstream(); - try { - return IOUtils.toByteArray(is); - } finally { - closeQuietly(is); - } + try (InputStream is = inputstream()) { + return is.readAllBytes(); } catch (Exception e) { throw new UnexpectedException(e); } @@ -270,7 +254,7 @@ public static VirtualFile fromRelativePath(String relativePath) { * @return true if match */ public boolean matchName(String fileName) { - // we need to check the name case to be sure we is not conflict with a file with the same name + // we need to check the name case to be sure we are not conflict with a file with the same name String canonicalName = null; try { canonicalName = this.realFile.getCanonicalFile().getName();