Skip to content

Commit

Permalink
Code modernization (#587)
Browse files Browse the repository at this point in the history
  • Loading branch information
offa authored Sep 16, 2022
1 parent 4bd1026 commit 26e2449
Show file tree
Hide file tree
Showing 49 changed files with 554 additions and 717 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ public void terminate(IOException e) {
@Override
public final void write(Command cmd, boolean last) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(baos);
cmd.writeTo(channel,oos);
oos.close();
try (ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(baos)) {
cmd.writeTo(channel, oos);
}
byte[] block = baos.toByteArray();
channel.notifyWrite(cmd, block.length);
writeBlock(channel, block);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ public Command read() throws IOException, ClassNotFoundException {
@Override
public void write(Command cmd, boolean last) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(baos);
cmd.writeTo(channel,oos);
oos.close();
try (ObjectOutputStream oos = AnonymousClassWarnings.checkingObjectOutputStream(baos)) {
cmd.writeTo(channel, oos);
}
byte[] block = baos.toByteArray();
channel.notifyWrite(cmd, block.length);
writeBlock(channel, block);
Expand Down
8 changes: 2 additions & 6 deletions src/main/java/hudson/remoting/Channel.java
Original file line number Diff line number Diff line change
Expand Up @@ -1027,7 +1027,7 @@ Future<V> callAsync(final Callable<V,T> callable) throws IOException {
}

final Future<UserRequest.ResponseToUserRequest<V, T>> f = new UserRequest<V, T>(this, callable).callAsync(this);
return new FutureAdapter<V, UserRequest.ResponseToUserRequest<V, T>>(f) {
return new FutureAdapter<>(f) {
@Override
protected V adapt(UserRequest.ResponseToUserRequest<V, T> r) throws ExecutionException {
try {
Expand Down Expand Up @@ -2125,11 +2125,7 @@ public int hashCode() {
*/
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Channel.Ref{");
sb.append("channel=").append(channel);
sb.append(",name=").append(name);
sb.append('}');
return sb.toString();
return "Channel.Ref{channel=" + channel + ",name=" + name + "}";
}
}
}
2 changes: 1 addition & 1 deletion src/main/java/hudson/remoting/Command.java
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ private Source(@CheckForNull Throwable cause) {

@Override
public String toString() {
return "Command "+Command.this.toString()+" created at";
return "Command " + Command.this + " created at";
}

private static final long serialVersionUID = 1L;
Expand Down
8 changes: 3 additions & 5 deletions src/main/java/hudson/remoting/ExportTable.java
Original file line number Diff line number Diff line change
Expand Up @@ -178,15 +178,13 @@ void dump(PrintWriter w) throws IOException {
}

String dump() {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
dump(pw);
pw.close();
return sw.toString();
} catch (IOException e) {
throw new Error(e); // impossible
}
return sw.toString();
}

synchronized Class<? super T>[] getInterfaces() {
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/hudson/remoting/LocalChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public <V, T extends Throwable> Future<V> callAsync(@NonNull final Callable<V,T>
}
});

return new Future<V>() {
return new Future<>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return f.cancel(mayInterruptIfRunning);
Expand All @@ -82,7 +82,7 @@ public V get() throws InterruptedException, ExecutionException {

@Override
public V get(long timeout, @NonNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return f.get(timeout,unit);
return f.get(timeout, unit);
}
};
}
Expand Down
8 changes: 2 additions & 6 deletions src/main/java/hudson/remoting/ProxyInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
package hudson.remoting;

import edu.umd.cs.findbugs.annotations.NonNull;
import org.jenkinsci.remoting.util.IOUtils;

import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -176,12 +177,7 @@ protected void execute(Channel channel) {
}

channel.unexport(oid,createdAt,false);

try {
in.close();
} catch (IOException e) {
// ignore errors
}
IOUtils.closeQuietly(in);
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/hudson/remoting/RemoteClassLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -1195,7 +1195,7 @@ public int hashCode() {

@Override
public String toString() {
return super.toString() + '[' + cl.toString() + ']';
return super.toString() + '[' + cl + ']';
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/hudson/remoting/RemoteInputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,9 @@ public enum Flag {
private static final class Greedy extends Exception {
public String print() {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
printStackTrace(pw);
pw.close();
try (PrintWriter pw = new PrintWriter(sw)) {
printStackTrace(pw);
}
return sw.toString();
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/hudson/remoting/RemoteInvocationHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ private RemoteInvocationHandler(Channel channel, int id, boolean userProxy,
this.channel = channel == null ? null : channel.ref();
this.oid = id;
this.userProxy = userProxy;
this.origin = recordCreatedAt ? new Exception("Proxy " + toString() + " was created for " + proxyType) : null;
this.origin = recordCreatedAt ? new Exception("Proxy " + this + " was created for " + proxyType) : null;
this.autoUnexportByCaller = autoUnexportByCaller;
this.userSpace = userSpace;
this.recordCreatedAt = recordCreatedAt;
Expand Down
17 changes: 9 additions & 8 deletions src/main/java/hudson/remoting/Request.java
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ final hudson.remoting.Future<RSP> callAsync(final Channel channel) throws IOExce
startTime = System.nanoTime();
channel.send(this);

return new hudson.remoting.Future<RSP>() {
return new hudson.remoting.Future<>() {

private volatile boolean cancelled;

Expand All @@ -264,23 +264,23 @@ public boolean isCancelled() {

@Override
public boolean isDone() {
return isCancelled() || response!=null;
return isCancelled() || response != null;
}

@Override
public RSP get() throws InterruptedException, ExecutionException {
synchronized(Request.this) {
synchronized (Request.this) {
String oldThreadName = Thread.currentThread().getName();
Thread.currentThread().setName(oldThreadName+" for "+channel.getName()+" id="+id);
Thread.currentThread().setName(oldThreadName + " for " + channel.getName() + " id=" + id);
try {
while(response==null) {
while (response == null) {
if (isCancelled()) {
throw new CancellationException();
}
if (channel.isInClosed()) {
throw new ExecutionException(new RequestAbortedException(null));
}
Request.this.wait(30*1000); // wait until the response arrives
Request.this.wait(30 * 1000); // wait until the response arrives
}
} catch (InterruptedException e) {
try {
Expand All @@ -293,8 +293,9 @@ public RSP get() throws InterruptedException, ExecutionException {
Thread.currentThread().setName(oldThreadName);
}

if(response.exception!=null)
if (response.exception != null) {
throw new ExecutionException(response.exception);
}

return response.returnValue;
}
Expand All @@ -314,7 +315,7 @@ public RSP get(long timeout, @NonNull TimeUnit unit) throws InterruptedException
if (channel.isInClosed()) {
throw new ExecutionException(new RequestAbortedException(null));
}
Request.this.wait(Math.min(30*1000,Math.max(1, TimeUnit.NANOSECONDS.toMillis(end - now))));
Request.this.wait(Math.min(30 * 1000, Math.max(1, TimeUnit.NANOSECONDS.toMillis(end - now))));
now = System.nanoTime();
}
if (response == null)
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/hudson/remoting/ResourceImageInJar.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ class ResourceImageInJar extends ResourceImageRef {

@Override
Future<byte[]> resolve(Channel channel, final String resourcePath) throws IOException, InterruptedException {
return new FutureAdapter<byte[],URL>(_resolveJarURL(channel)) {
return new FutureAdapter<>(_resolveJarURL(channel)) {
@Override
@SuppressFBWarnings(value = "URLCONNECTION_SSRF_FD", justification = "This is only used for managing the jar cache as files.")
protected byte[] adapt(URL jar) throws ExecutionException {
try {
return Util.readFully(toResourceURL(jar,resourcePath).openStream());
return Util.readFully(toResourceURL(jar, resourcePath).openStream());
} catch (IOException e) {
throw new ExecutionException(e);
}
Expand All @@ -57,7 +57,7 @@ protected byte[] adapt(URL jar) throws ExecutionException {

@Override
Future<URLish> resolveURL(Channel channel, final String resourcePath) throws IOException, InterruptedException {
return new FutureAdapter<URLish,URL>(_resolveJarURL(channel)) {
return new FutureAdapter<>(_resolveJarURL(channel)) {
@Override
protected URLish adapt(URL jar) throws ExecutionException {
try {
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/hudson/remoting/UserRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ protected ResponseToUserRequest<RSP,EXC> perform(Channel channel) throws EXC {
Thread.currentThread().setContextClassLoader(old);
}
} catch (LinkageError e) {
LOGGER.log(channel.isClosingOrClosed() ? Level.FINE : Level.WARNING, "LinkageError while performing " + toString(), e);
LOGGER.log(channel.isClosingOrClosed() ? Level.FINE : Level.WARNING, "LinkageError while performing " + this, e);
throw e;
} finally {
Channel.setCurrent(oldc);
Expand Down
9 changes: 4 additions & 5 deletions src/main/java/hudson/remoting/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,12 @@ static byte[] readFully(InputStream in) throws IOException {
}

public static void copy(InputStream in, OutputStream out) throws IOException {
try {
try (in) {
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
} finally {
in.close();
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ public Socket open(int socketTimeout) throws IOException {
}
String suffix = "";
if (isHttpProxy) {
suffix = " through proxy " + targetAddress.toString();
suffix = " through proxy " + targetAddress;
}
throw new IOException("Failed to connect to " + host + ':' + port + suffix, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException;
import org.jenkinsci.remoting.protocol.impl.NIONetworkLayer;
import org.jenkinsci.remoting.protocol.impl.SSLEngineFilterLayer;
import org.jenkinsci.remoting.util.IOUtils;

/**
* Implements the JNLP4-connect protocol. This protocol uses {@link SSLEngine} to perform a TLS upgrade of the plaintext
Expand Down Expand Up @@ -359,11 +360,7 @@ public void onClosed(Channel channel, IOException cause) {
}
event.fireChannelClosed(cause);
channel.removeListener(this);
try {
event.getSocket().close();
} catch (IOException e) {
// ignore
}
IOUtils.closeQuietly(event.getSocket());
}

/**
Expand All @@ -375,11 +372,7 @@ public void onClosed(ProtocolStack<?> stack, IOException cause) {
event.fireAfterDisconnect();
} finally {
stack.removeListener(this);
try {
event.getSocket().close();
} catch (IOException e) {
// ignore
}
IOUtils.closeQuietly(event.getSocket());
}
}
}
Expand Down
13 changes: 0 additions & 13 deletions src/main/java/org/jenkinsci/remoting/nio/FifoBuffer.java
Original file line number Diff line number Diff line change
Expand Up @@ -453,19 +453,6 @@ private void releaseRing() {
r = w = null;
}

// /**
// * Returns a {@link ByteBuffer} for peeking into
// */
// public ByteBuffer peek(int max) {
// synchronized (lock) {
// if (closed) {
// releaseRing();
// return null;
// }
// return r.asBuffer(Math.min(max, readable()));
// }
// }

/**
* Peek the specified number of bytes ({@code len}) at the specified offset in this buffer ({@code offset})
* and places it into the specified position ({@code start}) of the array ({@code data})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,15 +239,13 @@ public String[] getAllAddresses() {
*/
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
buf.append("CIDR Signature:\t[").append(getCidrSignature()).append("]")
.append(" Netmask: [").append(getNetmask()).append("]\n")
.append("Network:\t[").append(getNetworkAddress()).append("]\n")
.append("Broadcast:\t[").append(getBroadcastAddress()).append("]\n")
.append("First Address:\t[").append(getLowAddress()).append("]\n")
.append("Last Address:\t[").append(getHighAddress()).append("]\n")
.append("# Addresses:\t[").append(getAddressCount()).append("]\n");
return buf.toString();
return "CIDR Signature:\t[" + getCidrSignature() + "]" +
" Netmask: [" + getNetmask() + "]\n" +
"Network:\t[" + getNetworkAddress() + "]\n" +
"Broadcast:\t[" + getBroadcastAddress() + "]\n" +
"First Address:\t[" + getLowAddress() + "]\n" +
"Last Address:\t[" + getHighAddress() + "]\n" +
"# Addresses:\t[" + getAddressCount() + "]\n";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public boolean isValidInet6Address(String inet6Address) {
} else if (inet6Address.startsWith("::") && !octetList.isEmpty()) {
octetList.remove(0);
}
octets = octetList.toArray(new String[octetList.size()]);
octets = octetList.toArray(new String[0]);
}
if (octets.length > IPV6_MAX_HEX_GROUPS) {
return false;
Expand Down
5 changes: 0 additions & 5 deletions src/test/java/Driver8703.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,6 @@
public class Driver8703 {
@Issue("JENKINS-8703")
public static void main(String[] args) throws Throwable {
// int i=0;
// while (true) {
// System.out.println(i++);
// foo();
// }

ExecutorService es = Executors.newCachedThreadPool();
List<Future<Object>> flist = new ArrayList<>();
Expand Down
7 changes: 3 additions & 4 deletions src/test/java/OISInterception.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@
public class OISInterception {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);

oos.writeObject(Set.of("foo"));
oos.close();
try (ObjectOutputStream oos = new ObjectOutputStream(baos) ) {
oos.writeObject(Set.of("foo"));
}

ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray())) {
@Override
Expand Down
Loading

0 comments on commit 26e2449

Please sign in to comment.