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 java.lang.reflect.InvocationTargetException;
19  import java.lang.reflect.Method;
20  import java.net.SocketAddress;
21  import java.nio.file.Path;
22  
23  final class NioDomainSocketUtil {
24  
25      private static final Method OF_METHOD;
26      private static final Method GET_PATH_METHOD;
27  
28      static {
29          Method ofMethod;
30          Method getPathMethod;
31          try {
32              Class<?> clazz = Class.forName("java.net.UnixDomainSocketAddress");
33              ofMethod = clazz.getMethod("of", String.class);
34              getPathMethod = clazz.getMethod("getPath");
35  
36          } catch (Throwable error) {
37              ofMethod = null;
38              getPathMethod = null;
39          }
40          OF_METHOD = ofMethod;
41          GET_PATH_METHOD = getPathMethod;
42      }
43  
44      static SocketAddress newUnixDomainSocketAddress(String path) {
45          if (OF_METHOD == null) {
46              throw new IllegalStateException();
47          }
48          try {
49              return (SocketAddress) OF_METHOD.invoke(null, path);
50          } catch (IllegalAccessException e) {
51              throw new IllegalStateException(e);
52          } catch (InvocationTargetException e) {
53              throw new IllegalStateException(e);
54          }
55      }
56  
57      static void deleteSocketFile(SocketAddress address) {
58          if (GET_PATH_METHOD == null) {
59              throw new IllegalStateException();
60          }
61          try {
62              Path path = (Path) GET_PATH_METHOD.invoke(address);
63              if (path != null) {
64                  path.toFile().delete();
65              }
66          } catch (IllegalAccessException e) {
67              throw new IllegalStateException(e);
68          } catch (InvocationTargetException e) {
69              throw new IllegalStateException(e);
70          }
71      }
72  
73      private NioDomainSocketUtil() { }
74  }