Skip to content

Commit

Permalink
Removed dependency on 'org.apache.commons.io' (openhab#1441)
Browse files Browse the repository at this point in the history
Signed-off-by: Christoph Weitkamp <github@christophweitkamp.de>
  • Loading branch information
cweitkamp authored May 21, 2020
1 parent 53a749f commit 8808f04
Show file tree
Hide file tree
Showing 56 changed files with 242 additions and 199 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.audio.utils.AudioStreamUtils;

Expand Down Expand Up @@ -102,7 +101,10 @@ public long length() {

@Override
public synchronized void reset() throws IOException {
IOUtils.closeQuietly(inputStream);
try {
inputStream.close();
} catch (IOException e) {
}
try {
inputStream = getInputStream(file);
} catch (AudioException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,14 @@
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.audio.utils.AudioStreamUtils;
Expand Down Expand Up @@ -65,24 +67,20 @@ private InputStream createInputStream() throws AudioException {
try {
switch (extension) {
case M3U_EXTENSION:
try (final InputStream isM3U = new URL(url).openStream()) {
for (final String line : IOUtils.readLines(isM3U)) {
if (!line.isEmpty() && !line.startsWith("#")) {
url = line;
break;
}
for (final String line : Files.readAllLines(Paths.get(URI.create(url)))) {
if (!line.isEmpty() && !line.startsWith("#")) {
url = line;
break;
}
}
break;
case PLS_EXTENSION:
try (final InputStream isPLS = new URL(url).openStream()) {
for (final String line : IOUtils.readLines(isPLS)) {
if (!line.isEmpty() && line.startsWith("File")) {
final Matcher matcher = PLS_STREAM_PATTERN.matcher(line);
if (matcher.find()) {
url = matcher.group(1);
break;
}
for (final String line : Files.readAllLines(Paths.get(URI.create(url)))) {
if (!line.isEmpty() && line.startsWith("File")) {
final Matcher matcher = PLS_STREAM_PATTERN.matcher(line);
if (matcher.find()) {
url = matcher.group(1);
break;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.audio.AudioException;
Expand Down Expand Up @@ -144,7 +143,7 @@ protected void doGet(@NonNullByDefault({}) HttpServletRequest req, @NonNullByDef
logger.debug("Received request for invalid stream id at {}", req.getRequestURI());
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
} else {
IOUtils.copy(stream, resp.getOutputStream());
stream.transferTo(resp.getOutputStream());
resp.flushBuffer();
}
} catch (final AudioException ex) {
Expand All @@ -164,7 +163,10 @@ private synchronized void removeTimedOutStreams() {
// the stream has expired, we need to remove it!
final FixedLengthAudioStream stream = multiTimeStreams.remove(streamId);
streamTimeouts.remove(streamId);
IOUtils.closeQuietly(stream);
try {
stream.close();
} catch (IOException e) {
}
logger.debug("Removed timed out stream {}", streamId);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@

import java.io.File;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.automation.RuleRegistry;
Expand Down Expand Up @@ -90,9 +91,10 @@ public DefaultScriptScopeProvider(final @Reference ItemRegistry itemRegistry,
elements.put("State", State.class);
elements.put("Command", Command.class);
elements.put("URLEncoder", URLEncoder.class);
elements.put("FileUtils", FileUtils.class);
elements.put("FilenameUtils", FilenameUtils.class);
elements.put("File", File.class);
elements.put("Files", Files.class);
elements.put("Path", Path.class);
elements.put("Paths", Paths.class);

// types
elements.put("IncreaseDecreaseType", IncreaseDecreaseType.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@
package org.openhab.core.config.dispatch.internal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
Expand All @@ -29,7 +30,6 @@
import java.util.Properties;
import java.util.stream.Collectors;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.config.core.ConfigConstants;
Expand Down Expand Up @@ -300,7 +300,7 @@ private void internalProcessConfigFile(File configFile) throws IOException, File
String context = null;

// configuration file contains a PID Marker
List<String> lines = IOUtils.readLines(new FileInputStream(configFile));
List<String> lines = Files.readAllLines(configFile.toPath(), StandardCharsets.UTF_8);
String exclusivePID = lines.size() > 0 ? getPIDFromLine(lines.get(0)) : null;
if (exclusivePID != null) {
if (exclusivePIDMap.contains(exclusivePID)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,12 @@
*/
package org.openhab.core.id;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

import org.apache.commons.io.IOUtils;
import org.openhab.core.config.core.ConfigConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand All @@ -37,7 +35,7 @@ public class InstanceUUID {

static final String UUID_FILE_NAME = "uuid";

static String uuid = null;
static String uuid;

/**
* Retrieves a unified unique id, based on {@link java.util.UUID.randomUUID()}
Expand All @@ -48,7 +46,6 @@ public static synchronized String get() {
if (uuid == null) {
try {
File file = new File(ConfigConstants.getUserDataFolder() + File.separator + UUID_FILE_NAME);

if (!file.exists()) {
uuid = java.util.UUID.randomUUID().toString();
writeFile(file, uuid);
Expand All @@ -64,29 +61,26 @@ public static synchronized String get() {
}
}
} catch (IOException e) {
LOGGER.error("Failed writing instance uuid file: {}", e.getMessage());
LOGGER.error("Failed writing the UUID file: {}", e.getMessage());
return null;
}
}

return uuid;
}

private static void writeFile(File file, String content) throws IOException {
// create intermediary directories
file.getParentFile().mkdirs();
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.write(content, outputStream);
}
Files.writeString(file.toPath(), content, StandardCharsets.UTF_8);
}

private static String readFirstLine(File file) {
List<String> lines = null;
try {
lines = IOUtils.readLines(new FileInputStream(file));
try (final BufferedReader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
return (line = reader.readLine()) == null ? "" : line;
} catch (IOException ioe) {
LOGGER.warn("Failed reading the UUID file '{}': {}", file.getAbsolutePath(), ioe.getMessage());
return "";
}
return lines == null || lines.isEmpty() ? "" : lines.get(0);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* @author Kai Kreuzer - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
public class UUIDTest {
public class InstanceUUIDTest {

@Test
public void sameUUID() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
Expand All @@ -28,7 +29,6 @@
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.http.HttpStatus;
Expand Down Expand Up @@ -93,7 +93,7 @@ public AuthorizePageServlet(BundleContext bundleContext, @Reference HttpService
URL resource = bundleContext.getBundle().getResource("pages/authorize.html");
if (resource != null) {
try {
pageTemplate = IOUtils.toString(resource.openStream());
pageTemplate = new String(resource.openStream().readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ public static String executeCommandLineAndWaitResponse(String commandLine, int t
process.waitFor(timeout, TimeUnit.MILLISECONDS);
int exitCode = process.exitValue();
final StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
try (final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()))) {
String line = "";
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,19 @@
*/
package org.openhab.core.io.rest.auth.internal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.security.sasl.AuthenticationException;

import org.apache.commons.io.IOUtils;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.jose4j.jwa.AlgorithmConstraints.ConstraintType;
import org.jose4j.jwk.JsonWebKey;
Expand Down Expand Up @@ -78,14 +79,13 @@ private RsaJsonWebKey generateNewKey() throws JoseException, FileNotFoundExcepti

String keyJson = newKey.toJson(OutputControlLevel.INCLUDE_PRIVATE);

IOUtils.write(keyJson, new FileOutputStream(file));
Files.writeString(file.toPath(), keyJson, StandardCharsets.UTF_8);
return newKey;
}

private RsaJsonWebKey loadOrGenerateKey() throws FileNotFoundException, JoseException, IOException {
try {
List<String> lines = IOUtils.readLines(new FileInputStream(KEY_FILE_PATH));
return (RsaJsonWebKey) JsonWebKey.Factory.newJwk(lines.get(0));
try (final BufferedReader reader = Files.newBufferedReader(Paths.get(KEY_FILE_PATH))) {
return (RsaJsonWebKey) JsonWebKey.Factory.newJwk(reader.readLine());
} catch (IOException | JoseException e) {
RsaJsonWebKey key = generateNewKey();
logger.debug("Created JWT signature key in {}", KEY_FILE_PATH);
Expand Down Expand Up @@ -116,7 +116,7 @@ public String getJwtAccessToken(User user, String clientId, String scope, int to
jwtClaims.setClaim("client_id", clientId);
jwtClaims.setClaim("scope", scope);
jwtClaims.setStringListClaim("role",
new ArrayList<>((user.getRoles() != null) ? user.getRoles() : Collections.emptySet()));
new ArrayList<>(user.getRoles() != null ? user.getRoles() : Collections.emptySet()));

JsonWebSignature jws = new JsonWebSignature();
jws.setPayload(jwtClaims.toJson());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
*/
package org.openhab.core.io.rest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.stream.Stream;

import org.apache.commons.io.IOUtils;
import org.openhab.core.library.types.DateTimeType;

import com.google.gson.Gson;
Expand Down Expand Up @@ -53,7 +54,7 @@ public Stream2JSONInputStream(Stream<?> source) {
}

iterator = source.map(e -> gson.toJson(e)).iterator();
jsonElementStream = IOUtils.toInputStream("");
jsonElementStream = new ByteArrayInputStream(new byte[0]);
firstIteratorElement = true;
}

Expand Down Expand Up @@ -94,8 +95,11 @@ private void fillBuffer() {
postfix = "]";
}

IOUtils.closeQuietly(jsonElementStream);
jsonElementStream = IOUtils.toInputStream(prefix + entity + postfix);
try {
jsonElementStream.close();
} catch (IOException e) {
}
jsonElementStream = new ByteArrayInputStream((prefix + entity + postfix).getBytes(StandardCharsets.UTF_8));
}

private boolean finished() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import com.google.gson.JsonObject;
Expand Down Expand Up @@ -120,7 +120,7 @@ public void shouldCreateSuccessResponseWithLargeStreamEntity() throws IOExceptio
assertThat(entity.getClass(), is(typeCompatibleWith(InputStream.class)));

try (InputStream entityInStream = (InputStream) entity) {
String largeEntityJSON = IOUtils.toString(entityInStream);
String largeEntityJSON = new String(entityInStream.readAllBytes(), StandardCharsets.UTF_8);
assertThat(largeEntityJSON, is(notNullValue()));
assertTrue(largeEntityJSON.startsWith("{"));
assertTrue(largeEntityJSON.endsWith("}"));
Expand Down
Loading

0 comments on commit 8808f04

Please sign in to comment.