|
| 1 | +/* |
| 2 | + * Copyright 2021 - 2023 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * 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, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.sbm.java.util; |
| 17 | + |
| 18 | +import java.io.File; |
| 19 | +import java.util.regex.Matcher; |
| 20 | +import java.util.regex.Pattern; |
| 21 | + |
| 22 | +public class JavaSourceUtil { |
| 23 | + |
| 24 | + public static final Pattern PACKAGE_PATTERN = Pattern.compile("package ([\\w\\d\\.]*);"); |
| 25 | + public static final Pattern CLASS_PATTERN = Pattern.compile("(class|interface|enum)\\s([\\w]+).*"); |
| 26 | + |
| 27 | + public static String retrieveFullyQualifiedClassFileName(String code) { |
| 28 | + Matcher classMatcher = CLASS_PATTERN.matcher(code); |
| 29 | + |
| 30 | + String packageName = retrievePackageName(code); |
| 31 | + |
| 32 | + if (!classMatcher.find()) throw new RuntimeException("Could not extract classname from code '" + code + "'."); |
| 33 | + String className = classMatcher.group(2); |
| 34 | + if (packageName.isEmpty()) { |
| 35 | + return className + ".java"; |
| 36 | + } else { |
| 37 | + return packageName.replace(".", File.separator) + File.separator + className + ".java"; |
| 38 | + } |
| 39 | + |
| 40 | + } |
| 41 | + |
| 42 | + public static String retrievePackageName(String js) { |
| 43 | + Matcher packageMatcher = PACKAGE_PATTERN.matcher(js); |
| 44 | + String packageName = ""; |
| 45 | + if (packageMatcher.find()) { |
| 46 | + packageName = packageMatcher.group(1); |
| 47 | + } |
| 48 | + return packageName; |
| 49 | + } |
| 50 | +} |
0 commit comments