Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import org.eclipse.birt.report.engine.i18n.MessageConstants;
Expand Down Expand Up @@ -74,15 +78,28 @@ public byte[] findResource(URL url) {
}
byte[] inBytes = cache.get(url);
if (inBytes == null) {
URLConnection connection = null;
try {
InputStream in = url.openStream();
connection = url.openConnection();
InputStream in = connection.getInputStream();
inBytes = getByteArrayFromInputStream(in);
in.close();
cache.put(url, inBytes);
} catch (IOException e) {
logger.log(Level.WARNING, MessageConstants.RESOURCE_NOT_ACCESSIBLE, url.toExternalForm());
String errorBody = extractErrorBody(connection);
LogRecord record = new LogRecord(Level.WARNING, MessageConstants.RESOURCE_NOT_ACCESSIBLE);
record.setParameters(new Object[] { url.toExternalForm() });
record.setLoggerName(logger.getName());
if (!errorBody.isEmpty()) {
record.setThrown(new IOException(errorBody));
}
logger.log(record);
cache.put(url, DUMMY_BYTES);
return DUMMY_BYTES;
} finally {
if (connection instanceof HttpURLConnection httpConn) {
httpConn.disconnect();
}
}
}
return inBytes;
Expand All @@ -102,4 +119,24 @@ private byte[] getByteArrayFromInputStream(InputStream in) throws IOException {
return buffer;
}

private String extractErrorBody(URLConnection connection) {
if (!(connection instanceof HttpURLConnection httpConn)) {
return "No HTTP-Protocol";
}

try {
InputStream errorStream = httpConn.getErrorStream();
if (errorStream == null) {
return "No Error-Body";
}

try (errorStream) {
String body = new String(errorStream.readAllBytes(), StandardCharsets.UTF_8);
return body.length() > 1024 ? body.substring(0, 1024) + "..." : body;
}
} catch (Exception ex) {
return "Can't read Error-Body: " + ex.getMessage();
}
}

}