View Javadoc
1   /*
2    * Copyright 2024 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.channel.socket.nio;
17  
18  import io.netty.util.internal.SuppressJava6Requirement;
19  
20  import java.lang.reflect.InvocationTargetException;
21  import java.lang.reflect.Method;
22  import java.net.SocketAddress;
23  import java.nio.file.Path;
24  
25  final class NioDomainSocketUtil {
26  
27      private static final Method OF_METHOD;
28      private static final Method GET_PATH_METHOD;
29  
30      static {
31          Method ofMethod;
32          Method getPathMethod;
33          try {
34              Class<?> clazz = Class.forName("java.net.UnixDomainSocketAddress");
35              ofMethod = clazz.getMethod("of", String.class);
36              getPathMethod = clazz.getMethod("getPath");
37  
38          } catch (Throwable error) {
39              ofMethod = null;
40              getPathMethod = null;
41          }
42          OF_METHOD = ofMethod;
43          GET_PATH_METHOD = getPathMethod;
44      }
45  
46      static SocketAddress newUnixDomainSocketAddress(String path) {
47          if (OF_METHOD == null) {
48              throw new IllegalStateException();
49          }
50          try {
51              return (SocketAddress) OF_METHOD.invoke(null, path);
52          } catch (IllegalAccessException e) {
53              throw new IllegalStateException(e);
54          } catch (InvocationTargetException e) {
55              throw new IllegalStateException(e);
56          }
57      }
58  
59      @SuppressJava6Requirement(reason = "Guarded by version check")
60      static void deleteSocketFile(SocketAddress address) {
61          if (GET_PATH_METHOD == null) {
62              throw new IllegalStateException();
63          }
64          try {
65              Path path = (Path) GET_PATH_METHOD.invoke(address);
66              if (path != null) {
67                  path.toFile().delete();
68              }
69          } catch (IllegalAccessException e) {
70              throw new IllegalStateException(e);
71          } catch (InvocationTargetException e) {
72              throw new IllegalStateException(e);
73          }
74      }
75  
76      private NioDomainSocketUtil() { }
77  }