diff --git a/.gitignore b/.gitignore index 35b7961..da61d09 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ .DS_Store .idea/ out/ +.gradle +gradle +gradlew +gradlew.bat +build \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..e90dab1 --- /dev/null +++ b/build.gradle @@ -0,0 +1,79 @@ +plugins { + id 'org.jetbrains.intellij' version '0.4.18' +} + +group 'com.zhaow' +version '2.0.10' + +// See https://github.com/JetBrains/gradle-intellij-plugin/ +intellij { + version '2020.1' + localPath 'D:\\sft\\ideaIC-2020.1.win' + plugins = ['java', 'Kotlin', 'yaml', 'properties'] +} +patchPluginXml { + description """ +

A toolkit for RESTful services development.

+ +

support Spring framework (Spring MVC / Spring Boot) +

support JAX-RS +

support Java and Kotlin languages + +


+

一套 RESTful 服务开发辅助工具集。

+ +

支持 Spring 体系 (Spring MVC / Spring Boot) +

支持 JAX-RS +

支持 Java 和 Kotlin 语言。 +""" + changeNotes """ +

  • 2.0.10 移除了 2020.1 版本不兼容的内容(只是简单注释掉,不知道是否移除了重要内容) 注意:2020.3移除了更多的东西
  • +
  • 2.0.5 Bug fixed, supported http request OPTIONS,TRACE,CONNECT methods.
  • +
  • 2.0.4 Fixed NullPointerException with Kotlin project.
    + Fixed IllegalArgumentException: No enum constant com.zhaow.restful.method.HttpMethod.HEAD
    + Supported Kotlin 1.2 level.
  • +
  • 2.0.3 Improvements in navigate service(url), auto pasted copied http url to from clipboard.
    + Bug fixed.
  • +
  • 2.0.2 Match mapped URLs for Controllers without @RequestMapping annotations;
    + Supported mapped URLs for Controllers extended supper Object with @RequestMapping annotations.
    + Added Popup Menus ( "Copy Full Url", "Jump to Source") for service nodes. +
  • +
  • 2.0.1 Fixed JSON generation issue with POJO contains array fields; +
  • +
  • 2.0 Add Kotlin language supported;
    + Fixed some bugs. +
  • +
  • 1.1 Supported JAX-RS;
    + Format JSON data , use "Command + Enter" on Mac + (增强 POJO 生成 json 功能,处理 List、Enum等类型,处理自关联场景);
    + Fixed some bugs.
    +
  • +
  • 1.0.9 Service url navigation: matched restful style request mappings (e.g.:"/product/{productId}");
    +
  • +
  • 1.0.8 Bug fixed
  • +
  • 1.0.7 Match more mapped URLs ; (识别更多映射)
    + Replaced icons;
    + Add "Convert to JSON (Compressed)" function to java class; +
  • +
  • 1.0.6 Compatible with IDEA 2016 (兼容 IDEA 2016)
  • +
  • 1.0.5 修复发送请求IDE卡死的问题.
  • +
  • 1.0.4 Format Date type (格式化 Date 类型)
  • +
  • 1.0.3 Small cleanup some code.
  • + """ +} +dependencies { + 'commons-codec:commons-codec:1.14' + 'org.apache.httpcomponents:httpclient:4.5.12' +} diff --git a/resources/META-INF/plugin.xml b/resources/META-INF/plugin.xml deleted file mode 100644 index da52735..0000000 --- a/resources/META-INF/plugin.xml +++ /dev/null @@ -1,218 +0,0 @@ - - com.zhaow.restful.toolkit - RestfulToolkit - 2.0.5 - zhaow - - A toolkit for RESTful services development. -
      -
    • 1.ONE STEP to navigate to service declaration. ( use: Ctrl + \ or Ctrl + Alt + N )
    • -
    • 2.Show RESTful services structure.
    • -
    • 3.A simple http request tool.
    • -
    • 4.Add some useful functions at request method, Generate&Copy Query Param, Generate&Copy URL, etc.
    • -
    • 5.Other functions: Convert to JSON; to java class,format json data ( Windows: Ctrl + Enter; Mac: Command + Enter ) .
    • -
    -

    support Spring framework (Spring MVC / Spring Boot) -

    support JAX-RS -

    support Java and Kotlin languages - -


    -

    一套 RESTful 服务开发辅助工具集。

    -
      -
    • 1.根据 URL 直接跳转到对应的方法定义 ( Ctrl \ or Ctrl Alt N );
    • -
    • 2.提供了一个 Services tree 的显示窗口;
    • -
    • 3.一个简单的 http 请求工具;
    • -
    • 4.在请求方法上添加了有用功能: 复制生成 URL;,复制方法参数...
    • -
    • 5.其他功能: java 类上添加 Convert to JSON 功能,格式化 json 数据 ( Windows: Ctrl + Enter; Mac: Command + Enter )。
    • -
    -

    支持 Spring 体系 (Spring MVC / Spring Boot) -

    支持 JAX-RS -

    支持 Java 和 Kotlin 语言。 - - ]]> - - 2.0.5 Bug fixed, supported http request OPTIONS,TRACE,CONNECT methods. -

  • 2.0.4 Fixed NullPointerException with Kotlin project.
    - Fixed IllegalArgumentException: No enum constant com.zhaow.restful.method.HttpMethod.HEAD
    - Supported Kotlin 1.2 level.
  • -
  • 2.0.3 Improvements in navigate service(url), auto pasted copied http url to from clipboard.
    - Bug fixed.
  • -
  • 2.0.2 Match mapped URLs for Controllers without @RequestMapping annotations;
    - Supported mapped URLs for Controllers extended supper Object with @RequestMapping annotations.
    - Added Popup Menus ( "Copy Full Url", "Jump to Source") for service nodes. -
  • -
  • 2.0.1 Fixed JSON generation issue with POJO contains array fields; -
  • -
  • 2.0 Add Kotlin language supported;
    - Fixed some bugs. -
  • -
  • 1.1 Supported JAX-RS;
    - Format JSON data , use "Command + Enter" on Mac - (增强 POJO 生成 json 功能,处理 List、Enum等类型,处理自关联场景);
    - Fixed some bugs.
    -
  • -
  • 1.0.9 Service url navigation: matched restful style request mappings (e.g.:"/product/{productId}");
    -
  • -
  • 1.0.8 Bug fixed
  • -
  • 1.0.7 Match more mapped URLs ; (识别更多映射)
    - Replaced icons;
    - Add "Convert to JSON (Compressed)" function to java class; -
  • -
  • 1.0.6 Compatible with IDEA 2016 (兼容 IDEA 2016)
  • -
  • 1.0.5 修复发送请求IDE卡死的问题.
  • -
  • 1.0.4 Format Date type (格式化 Date 类型)
  • -
  • 1.0.3 Small cleanup some code.
  • - ]]> - - - - - - - - com.intellij.modules.platform - com.intellij.properties - org.jetbrains.plugins.yaml - org.jetbrains.kotlin - - - - com.zhaow.restful.navigator.RestServicesNavigator - - - com.zhaow.restful.navigator.RestServiceProjectsManager - - - - com.zhaow.restful.navigator.RestServiceDetail - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    \ No newline at end of file diff --git a/resources/RestfulToolkitBundle.properties b/resources/RestfulToolkitBundle.properties deleted file mode 100644 index a769786..0000000 --- a/resources/RestfulToolkitBundle.properties +++ /dev/null @@ -1,3 +0,0 @@ -toolkit.name=RestfulToolkit -toolkit.scanning.projects=Scanning projects... -toolkit.navigator.nothing.to.display= No Services Found ,try use {0} to refresh services \ No newline at end of file diff --git a/resources/tips/GotoService.html b/resources/tips/GotoService.html deleted file mode 100644 index b2cd177..0000000 --- a/resources/tips/GotoService.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - -

    - To navigate any rest service in the editor quickly, press &shortcut:GotoService; - (Navigate | Rest Service) - and start typing the url of the service. Choose the item from a drop-down list that appears.

    -

    -

    - - diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8f458d8 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'RestfulToolkit' + diff --git a/src/java/com/zhaow/restful/common/ChineseUtill.java b/src/java/com/zhaow/restful/common/ChineseUtill.java deleted file mode 100644 index ede117a..0000000 --- a/src/java/com/zhaow/restful/common/ChineseUtill.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.zhaow.restful.common; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ChineseUtill { - - private static boolean isChinese(char c) { - Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); - if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS - || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS - || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A - || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION - || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION - || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { - return true; - } - return false; - } - - public static boolean isMessyCode(String strName) { - Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*"); - Matcher m = p.matcher(strName); - String after = m.replaceAll(""); - String temp = after.replaceAll("\\p{P}", ""); - char[] ch = temp.trim().toCharArray(); - float chLength = 0 ; - float count = 0; - for (int i = 0; i < ch.length; i++) { - char c = ch[i]; - if (!Character.isLetterOrDigit(c)) { - if (!isChinese(c)) { - count = count + 1; - } - chLength++; - } - } - float result = count / chLength ; - if (result > 0.4) { - return true; - } else { - return false; - } - } - - - public static String toChinese(Object msg){ -// String tempMsg = TransformUtils.toString(msg) ; - String tempMsg = msg.toString() ; - if(isMessyCode(tempMsg)){ - try { - return new String(tempMsg.getBytes("ISO8859-1"), "UTF-8"); - } catch (Exception e) { - } - } - return tempMsg ; - } -} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/common/spring/AntPathMatcher.java b/src/java/com/zhaow/restful/common/spring/AntPathMatcher.java deleted file mode 100644 index ea8b0a1..0000000 --- a/src/java/com/zhaow/restful/common/spring/AntPathMatcher.java +++ /dev/null @@ -1,655 +0,0 @@ -/* - * Copyright 2002-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.zhaow.restful.common.spring; - -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * {@link PathMatcher} implementation for Ant-style path patterns. - * - *

    Part of this mapping code has been kindly borrowed from Apache Ant. - * - *

    The mapping matches URLs using the following rules:
    - *

    - * - *

    Examples

    - * - * - *

    Note: a pattern and a path must both be absolute or must - * both be relative in order for the two to match. Therefore it is recommended - * that users of this implementation to sanitize patterns in order to prefix - * them with "/" as it makes sense in the context in which they're used. - * - * @author Alef Arendsen - * @author Juergen Hoeller - * @author Rob Harrop - * @author Arjen Poutsma - * @author Rossen Stoyanchev - * @author Sam Brannen - * @since 16.07.2003 - */ -public class AntPathMatcher /*implements PathMatcher*/ { - - /** Default path separator: "/" */ - public static final String DEFAULT_PATH_SEPARATOR = "/"; - - private static final int CACHE_TURNOFF_THRESHOLD = 65536; - - private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); - - private static final char[] WILDCARD_CHARS = { '*', '?', '{' }; - - private String pathSeparator; - -// private PathSeparatorPatternCache pathSeparatorPatternCache; - - private boolean caseSensitive = true; - - private boolean trimTokens = false; - - private volatile Boolean cachePatterns; - - private final Map tokenizedPatternCache = new ConcurrentHashMap(256); - - final Map stringMatcherCache = new ConcurrentHashMap(256); - - - /** - * Create a new instance with the {@link #DEFAULT_PATH_SEPARATOR}. - */ - public AntPathMatcher() { - this.pathSeparator = DEFAULT_PATH_SEPARATOR; -// this.pathSeparatorPatternCache = new PathSeparatorPatternCache(DEFAULT_PATH_SEPARATOR); - } - private void deactivatePatternCache() { - this.cachePatterns = false; - this.tokenizedPatternCache.clear(); - this.stringMatcherCache.clear(); - } - - public boolean match(String pattern, String path) { - return doMatch(pattern, path, true, null); - } - - /** - * Actually match the given {@code path} against the given {@code pattern}. - * @param pattern the pattern to match against - * @param path the path String to test - * @param fullMatch whether a full pattern match is required (else a pattern match - * as far as the given base path goes is sufficient) - * @return {@code true} if the supplied {@code path} matched, {@code false} if it didn't - */ - protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) { - if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) { - return false; - } - - String[] pattDirs = tokenizePattern(pattern); - if (fullMatch && this.caseSensitive && !isPotentialMatch(path, pattDirs)) { - return false; - } - - String[] pathDirs = tokenizePath(path); - - int pattIdxStart = 0; - int pattIdxEnd = pattDirs.length - 1; - int pathIdxStart = 0; - int pathIdxEnd = pathDirs.length - 1; - - // Match all elements up to the first ** - while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { - String pattDir = pattDirs[pattIdxStart]; - if ("**".equals(pattDir)) { - break; - } - if (!matchStrings(pattDir, pathDirs[pathIdxStart], uriTemplateVariables)) { - return false; - } - pattIdxStart++; - pathIdxStart++; - } - - if (pathIdxStart > pathIdxEnd) { - // Path is exhausted, only match if rest of pattern is * or **'s - if (pattIdxStart > pattIdxEnd) { - return (pattern.endsWith(this.pathSeparator) == path.endsWith(this.pathSeparator)); - } - if (!fullMatch) { - return true; - } - if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) { - return true; - } - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - return true; - } - else if (pattIdxStart > pattIdxEnd) { - // String not exhausted, but pattern is. Failure. - return false; - } - else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { - // Path start definitely matches due to "**" part in pattern. - return true; - } - - // up to last '**' - while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { - String pattDir = pattDirs[pattIdxEnd]; - if (pattDir.equals("**")) { - break; - } - if (!matchStrings(pattDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { - return false; - } - pattIdxEnd--; - pathIdxEnd--; - } - if (pathIdxStart > pathIdxEnd) { - // String is exhausted - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - return true; - } - - while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { - int patIdxTmp = -1; - for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { - if (pattDirs[i].equals("**")) { - patIdxTmp = i; - break; - } - } - if (patIdxTmp == pattIdxStart + 1) { - // '**/**' situation, so skip one - pattIdxStart++; - continue; - } - // Find the pattern between padIdxStart & padIdxTmp in str between - // strIdxStart & strIdxEnd - int patLength = (patIdxTmp - pattIdxStart - 1); - int strLength = (pathIdxEnd - pathIdxStart + 1); - int foundIdx = -1; - - strLoop: - for (int i = 0; i <= strLength - patLength; i++) { - for (int j = 0; j < patLength; j++) { - String subPat = pattDirs[pattIdxStart + j + 1]; - String subStr = pathDirs[pathIdxStart + i + j]; - if (!matchStrings(subPat, subStr, uriTemplateVariables)) { - continue strLoop; - } - } - foundIdx = pathIdxStart + i; - break; - } - - if (foundIdx == -1) { - return false; - } - - pattIdxStart = patIdxTmp; - pathIdxStart = foundIdx + patLength; - } - - for (int i = pattIdxStart; i <= pattIdxEnd; i++) { - if (!pattDirs[i].equals("**")) { - return false; - } - } - - return true; - } - - private boolean isPotentialMatch(String path, String[] pattDirs) { - if (!this.trimTokens) { - int pos = 0; - for (String pattDir : pattDirs) { - int skipped = skipSeparator(path, pos, this.pathSeparator); - pos += skipped; - skipped = skipSegment(path, pos, pattDir); - if (skipped < pattDir.length()) { - return (skipped > 0 || (pattDir.length() > 0 && isWildcardChar(pattDir.charAt(0)))); - } - pos += skipped; - } - } - return true; - } - - private int skipSegment(String path, int pos, String prefix) { - int skipped = 0; - for (int i = 0; i < prefix.length(); i++) { - char c = prefix.charAt(i); - if (isWildcardChar(c)) { - return skipped; - } - int currPos = pos + skipped; - if (currPos >= path.length()) { - return 0; - } - if (c == path.charAt(currPos)) { - skipped++; - } - } - return skipped; - } - - private int skipSeparator(String path, int pos, String separator) { - int skipped = 0; - while (path.startsWith(separator, pos + skipped)) { - skipped += separator.length(); - } - return skipped; - } - - private boolean isWildcardChar(char c) { - for (char candidate : WILDCARD_CHARS) { - if (c == candidate) { - return true; - } - } - return false; - } - - /** - * Tokenize the given path pattern into parts, based on this matcher's settings. - *

    Performs caching based on {@link #setCachePatterns}, delegating to - * {@link #tokenizePath(String)} for the actual tokenization algorithm. - * @param pattern the pattern to tokenize - * @return the tokenized pattern parts - */ - protected String[] tokenizePattern(String pattern) { - String[] tokenized = null; - Boolean cachePatterns = this.cachePatterns; - if (cachePatterns == null || cachePatterns.booleanValue()) { - tokenized = this.tokenizedPatternCache.get(pattern); - } - if (tokenized == null) { - tokenized = tokenizePath(pattern); - if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) { - // Try to adapt to the runtime situation that we're encountering: - // There are obviously too many different patterns coming in here... - // So let's turn off the cache since the patterns are unlikely to be reoccurring. - deactivatePatternCache(); - return tokenized; - } - if (cachePatterns == null || cachePatterns.booleanValue()) { - this.tokenizedPatternCache.put(pattern, tokenized); - } - } - return tokenized; - } - - /** - * Tokenize the given path String into parts, based on this matcher's settings. - * @param path the path to tokenize - * @return the tokenized path parts - */ - protected String[] tokenizePath(String path) { - return StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); - } - - /** - * one.Test whether or not a string matches against a pattern. - * @param pattern the pattern to match against (never {@code null}) - * @param str the String which must be matched against the pattern (never {@code null}) - * @return {@code true} if the string matches against the pattern, or {@code false} otherwise - */ - private boolean matchStrings(String pattern, String str, Map uriTemplateVariables) { - return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables); - } - - /** - * Build or retrieve an {@link AntPathStringMatcher} for the given pattern. - *

    The default implementation checks this AntPathMatcher's internal cache - * (see {@link #setCachePatterns}), creating a new AntPathStringMatcher instance - * if no cached copy is found. - *

    When encountering too many patterns to cache at runtime (the threshold is 65536), - * it turns the default cache off, assuming that arbitrary permutations of patterns - * are coming in, with little chance for encountering a recurring pattern. - *

    This method may be overridden to implement a custom cache strategy. - * @param pattern the pattern to match against (never {@code null}) - * @return a corresponding AntPathStringMatcher (never {@code null}) - * @see #setCachePatterns - */ - protected AntPathStringMatcher getStringMatcher(String pattern) { - AntPathStringMatcher matcher = null; - Boolean cachePatterns = this.cachePatterns; - if (cachePatterns == null || cachePatterns.booleanValue()) { - matcher = this.stringMatcherCache.get(pattern); - } - if (matcher == null) { - matcher = new AntPathStringMatcher(pattern, this.caseSensitive); - if (cachePatterns == null && this.stringMatcherCache.size() >= CACHE_TURNOFF_THRESHOLD) { - // Try to adapt to the runtime situation that we're encountering: - // There are obviously too many different patterns coming in here... - // So let's turn off the cache since the patterns are unlikely to be reoccurring. - deactivatePatternCache(); - return matcher; - } - if (cachePatterns == null || cachePatterns.booleanValue()) { - this.stringMatcherCache.put(pattern, matcher); - } - } - return matcher; - } - - /** - * Tests whether or not a string matches against a pattern via a {@link Pattern}. - *

    The pattern may contain special characters: '*' means zero or more characters; '?' means one and - * only one character; '{' and '}' indicate a URI template pattern. For example /users/{user}. - */ - protected static class AntPathStringMatcher { - - private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); - - private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; - - private final Pattern pattern; - - private final List variableNames = new LinkedList(); - - public AntPathStringMatcher(String pattern) { - this(pattern, true); - } - - public AntPathStringMatcher(String pattern, boolean caseSensitive) { - StringBuilder patternBuilder = new StringBuilder(); - Matcher matcher = GLOB_PATTERN.matcher(pattern); - int end = 0; - while (matcher.find()) { - patternBuilder.append(quote(pattern, end, matcher.start())); - String match = matcher.group(); - if ("?".equals(match)) { - patternBuilder.append('.'); - } - else if ("*".equals(match)) { - patternBuilder.append(".*"); - } - else if (match.startsWith("{") && match.endsWith("}")) { - int colonIdx = match.indexOf(':'); - if (colonIdx == -1) { - patternBuilder.append(DEFAULT_VARIABLE_PATTERN); - this.variableNames.add(matcher.group(1)); - } - else { - String variablePattern = match.substring(colonIdx + 1, match.length() - 1); - patternBuilder.append('('); - patternBuilder.append(variablePattern); - patternBuilder.append(')'); - String variableName = match.substring(1, colonIdx); - this.variableNames.add(variableName); - } - } - end = matcher.end(); - } - patternBuilder.append(quote(pattern, end, pattern.length())); - this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) : - Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE)); - } - - private String quote(String s, int start, int end) { - if (start == end) { - return ""; - } - return Pattern.quote(s.substring(start, end)); - } - - /** - * Main entry point. - * @return {@code true} if the string matches against the pattern, or {@code false} otherwise. - */ - public boolean matchStrings(String str, Map uriTemplateVariables) { - Matcher matcher = this.pattern.matcher(str); - if (matcher.matches()) { - if (uriTemplateVariables != null) { - // SPR-8455 - if (this.variableNames.size() != matcher.groupCount()) { - throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + - this.pattern + " does not match the number of URI template variables it defines, " + - "which can occur if capturing groups are used in a URI template regex. " + - "Use non-capturing groups instead."); - } - for (int i = 1; i <= matcher.groupCount(); i++) { - String name = this.variableNames.get(i - 1); - String value = matcher.group(i); - uriTemplateVariables.put(name, value); - } - } - return true; - } - else { - return false; - } - } - } - - - /** - * The default {@link Comparator} implementation returned by - * {@link #getPatternComparator(String)}. - *

    In order, the most "generic" pattern is determined by the following: - *

    - */ - protected static class AntPatternComparator implements Comparator { - - private final String path; - - public AntPatternComparator(String path) { - this.path = path; - } - - /** - * Compare two patterns to determine which should match first, i.e. which - * is the most specific regarding the current path. - * @return a negative integer, zero, or a positive integer as pattern1 is - * more specific, equally specific, or less specific than pattern2. - */ - @Override - public int compare(String pattern1, String pattern2) { - PatternInfo info1 = new PatternInfo(pattern1); - PatternInfo info2 = new PatternInfo(pattern2); - - if (info1.isLeastSpecific() && info2.isLeastSpecific()) { - return 0; - } - else if (info1.isLeastSpecific()) { - return 1; - } - else if (info2.isLeastSpecific()) { - return -1; - } - - boolean pattern1EqualsPath = pattern1.equals(path); - boolean pattern2EqualsPath = pattern2.equals(path); - if (pattern1EqualsPath && pattern2EqualsPath) { - return 0; - } - else if (pattern1EqualsPath) { - return -1; - } - else if (pattern2EqualsPath) { - return 1; - } - - if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { - return 1; - } - else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) { - return -1; - } - - if (info1.getTotalCount() != info2.getTotalCount()) { - return info1.getTotalCount() - info2.getTotalCount(); - } - - if (info1.getLength() != info2.getLength()) { - return info2.getLength() - info1.getLength(); - } - - if (info1.getSingleWildcards() < info2.getSingleWildcards()) { - return -1; - } - else if (info2.getSingleWildcards() < info1.getSingleWildcards()) { - return 1; - } - - if (info1.getUriVars() < info2.getUriVars()) { - return -1; - } - else if (info2.getUriVars() < info1.getUriVars()) { - return 1; - } - - return 0; - } - - - /** - * Value class that holds information about the pattern, e.g. number of - * occurrences of "*", "**", and "{" pattern elements. - */ - private static class PatternInfo { - - private final String pattern; - - private int uriVars; - - private int singleWildcards; - - private int doubleWildcards; - - private boolean catchAllPattern; - - private boolean prefixPattern; - - private Integer length; - - public PatternInfo(String pattern) { - this.pattern = pattern; - if (this.pattern != null) { - initCounters(); - this.catchAllPattern = this.pattern.equals("/**"); - this.prefixPattern = !this.catchAllPattern && this.pattern.endsWith("/**"); - } - if (this.uriVars == 0) { - this.length = (this.pattern != null ? this.pattern.length() : 0); - } - } - - protected void initCounters() { - int pos = 0; - while (pos < this.pattern.length()) { - if (this.pattern.charAt(pos) == '{') { - this.uriVars++; - pos++; - } - else if (this.pattern.charAt(pos) == '*') { - if (pos + 1 < this.pattern.length() && this.pattern.charAt(pos + 1) == '*') { - this.doubleWildcards++; - pos += 2; - } - else if (pos > 0 && !this.pattern.substring(pos - 1).equals(".*")) { - this.singleWildcards++; - pos++; - } - else { - pos++; - } - } - else { - pos++; - } - } - } - - public int getUriVars() { - return this.uriVars; - } - - public int getSingleWildcards() { - return this.singleWildcards; - } - - public int getDoubleWildcards() { - return this.doubleWildcards; - } - - public boolean isLeastSpecific() { - return (this.pattern == null || this.catchAllPattern); - } - - public boolean isPrefixPattern() { - return this.prefixPattern; - } - - public int getTotalCount() { - return this.uriVars + this.singleWildcards + (2 * this.doubleWildcards); - } - - /** - * Returns the length of the given pattern, where template variables are considered to be 1 long. - */ - public int getLength() { - if (this.length == null) { - this.length = VARIABLE_PATTERN.matcher(this.pattern).replaceAll("#").length(); - } - return this.length; - } - } - } - -} diff --git a/src/java/com/zhaow/restful/common/spring/StringUtils.java b/src/java/com/zhaow/restful/common/spring/StringUtils.java deleted file mode 100644 index e5013cd..0000000 --- a/src/java/com/zhaow/restful/common/spring/StringUtils.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2002-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.zhaow.restful.common.spring; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.StringTokenizer; - -/** - * Miscellaneous {@link String} utility methods. - * - *

    Mainly for internal use within the framework; consider - * Apache's Commons Lang - * for a more comprehensive suite of {@code String} utilities. - * - *

    This class delivers some simple functionality that should really be - * provided by the core Java {@link String} and {@link StringBuilder} - * classes. It also provides easy-to-use methods to convert between - * delimited strings, such as CSV strings, and collections and arrays. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @author Keith Donald - * @author Rob Harrop - * @author Rick Evans - * @author Arjen Poutsma - * @author Sam Brannen - * @author Brian Clozel - * @since 16 April 2001 - */ -public abstract class StringUtils { - - /** - * Check that the given {@code CharSequence} is neither {@code null} nor - * of length 0. - *

    Note: this method returns {@code true} for a {@code CharSequence} - * that purely consists of whitespace. - *

    -	 * StringUtils.hasLength(null) = false
    -	 * StringUtils.hasLength("") = false
    -	 * StringUtils.hasLength(" ") = true
    -	 * StringUtils.hasLength("Hello") = true
    -	 * 
    - * @param str the {@code CharSequence} to check (may be {@code null}) - * @return {@code true} if the {@code CharSequence} is not {@code null} and has length - * @see #hasText(String) - */ - public static boolean hasLength(CharSequence str) { - return (str != null && str.length() > 0); - } - - /** - * Copy the given {@code Collection} into a {@code String} array. - *

    The {@code Collection} must contain {@code String} elements only. - * @param collection the {@code Collection} to copy - * @return the {@code String} array ({@code null} if the supplied - * {@code Collection} was {@code null}) - */ - public static String[] toStringArray(Collection collection) { - if (collection == null) { - return null; - } - - return collection.toArray(new String[collection.size()]); - } - /** - * Tokenize the given {@code String} into a {@code String} array via a - * {@link StringTokenizer}. - *

    The given {@code delimiters} string can consist of any number of - * delimiter characters. Each of those characters can be used to separate - * tokens. A delimiter is always a single character; for multi-character - * delimiters, consider using {@link #delimitedListToStringArray}. - * @param str the {@code String} to tokenize - * @param delimiters the delimiter characters, assembled as a {@code String} - * (each of the characters is individually considered as a delimiter) - * @param trimTokens trim the tokens via {@link String#trim()} - * @param ignoreEmptyTokens omit empty tokens from the result array - * (only applies to tokens that are empty after trimming; StringTokenizer - * will not consider subsequent delimiters as token in the first place). - * @return an array of the tokens ({@code null} if the input {@code String} - * was {@code null}) - * @see StringTokenizer - * @see String#trim() - * @see #delimitedListToStringArray - */ - public static String[] tokenizeToStringArray( - String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { - - if (str == null) { - return null; - } - - StringTokenizer st = new StringTokenizer(str, delimiters); - List tokens = new ArrayList(); - while (st.hasMoreTokens()) { - String token = st.nextToken(); - if (trimTokens) { - token = token.trim(); - } - if (!ignoreEmptyTokens || token.length() > 0) { - tokens.add(token); - } - } - return toStringArray(tokens); - } -} diff --git a/src/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java b/src/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java deleted file mode 100644 index 0fcf663..0000000 --- a/src/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.zhaow.restful.navigation.action; - -import com.intellij.ide.util.gotoByName.ChooseByNameItemProvider; -import com.intellij.ide.util.gotoByName.ChooseByNameModel; -import com.intellij.ide.util.gotoByName.ChooseByNamePopup; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Key; -import com.intellij.openapi.util.text.StringUtil; -import com.zhaow.utils.ToolkitUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class RestServiceChooseByNamePopup extends ChooseByNamePopup { - public static final Key CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY = new Key<>("ChooseByNamePopup"); - - protected RestServiceChooseByNamePopup(@Nullable Project project, @NotNull ChooseByNameModel model, @NotNull ChooseByNameItemProvider provider, @Nullable ChooseByNamePopup oldPopup, @Nullable String predefinedText, boolean mayRequestOpenInCurrentWindow, int initialIndex) { - super(project, model, provider, oldPopup, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); - } - - public static RestServiceChooseByNamePopup createPopup(final Project project, - @NotNull final ChooseByNameModel model, - @NotNull ChooseByNameItemProvider provider, - @Nullable final String predefinedText, - boolean mayRequestOpenInCurrentWindow, - final int initialIndex) { - if (!StringUtil.isEmptyOrSpaces(predefinedText)) { - return new RestServiceChooseByNamePopup(project, model, provider, null, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); - } - - final RestServiceChooseByNamePopup oldPopup = project == null ? null : project.getUserData(CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY); - if (oldPopup != null) { - oldPopup.close(false); - } - RestServiceChooseByNamePopup newPopup = new RestServiceChooseByNamePopup(project, model, provider, oldPopup, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); - - if (project != null) { - project.putUserData(CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, newPopup); - } - return newPopup; - } - - @Override - public String transformPattern(String pattern) { - final ChooseByNameModel model = getModel(); - return getTransformedPattern(pattern, model); - } - -//TODO: resolve PathVariable - public static String getTransformedPattern(String pattern, ChooseByNameModel model) { - if (! (model instanceof GotoRequestMappingModel) ) { - return pattern; - } - - pattern = ToolkitUtil.removeRedundancyMarkup(pattern);; - return pattern; - } - - - @Nullable - public String getMemberPattern() { - final String enteredText = getTrimmedText(); - final int index = enteredText.lastIndexOf('#'); - if (index == -1) { - return null; - } - - String name = enteredText.substring(index + 1).trim(); - return StringUtil.isEmptyOrSpaces(name) ? null : name; - } - -/* public void repaintList() { - myRepaintQueue.cancelAllUpdates(); - myRepaintQueue.queue(new Update(this) { - @Override - public void run() { - RestServiceChooseByNamePopup.this.repaintListImmediate(); - } - }); - }*/ - -} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/navigator/CopyFullUrlAction.java b/src/java/com/zhaow/restful/navigator/CopyFullUrlAction.java deleted file mode 100644 index 3ae8398..0000000 --- a/src/java/com/zhaow/restful/navigator/CopyFullUrlAction.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.zhaow.restful.navigator; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.ide.CopyPasteManager; -import com.intellij.openapi.project.DumbAware; -import com.zhaow.restful.navigation.action.RestServiceItem; -import com.zhaow.utils.RestServiceDataKeys; - -import java.awt.datatransfer.StringSelection; -import java.util.List; - -public class CopyFullUrlAction extends AnAction implements DumbAware { - @Override - public void update(AnActionEvent e) { - super.update(e); - Presentation p = e.getPresentation(); - p.setEnabled(isAvailable(e)); - p.setVisible(isVisible(e)); - } - - @Override - public void actionPerformed(AnActionEvent e) { - List serviceItems = RestServiceDataKeys.SERVICE_ITEMS.getData(e.getDataContext()); - StringBuilder sb = new StringBuilder(); - for (RestServiceItem serviceItem : serviceItems) { - if (sb.length() > 1) { - sb.append("\n\n"); - } - sb.append(serviceItem.getFullUrl()); - } - - CopyPasteManager.getInstance().setContents(new StringSelection(sb.toString())); - -// RestServiceProjectsManager.getInstance(getEventProject(e)). - /* CopyPasteManager.getInstance().setContents(...);*/ - } - - /* getSelectRestServiceNodes */ - - protected boolean isAvailable(AnActionEvent e) { - return true; - } - - protected boolean isVisible(AnActionEvent e) { - return true; - } -} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/navigator/EditSourceAction.java b/src/java/com/zhaow/restful/navigator/EditSourceAction.java deleted file mode 100644 index a85a11b..0000000 --- a/src/java/com/zhaow/restful/navigator/EditSourceAction.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.zhaow.restful.navigator; - -import com.intellij.openapi.actionSystem.AnAction; -import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.Presentation; -import com.intellij.openapi.project.DumbAware; -import com.intellij.util.PsiNavigateUtil; -import com.zhaow.restful.navigation.action.RestServiceItem; -import com.zhaow.utils.RestServiceDataKeys; - -import java.util.List; - -public class EditSourceAction extends AnAction implements DumbAware { - @Override - public void update(AnActionEvent e) { - super.update(e); - Presentation p = e.getPresentation(); - p.setVisible(isVisible(e)); - } - - @Override - public void actionPerformed(AnActionEvent e) { - List serviceItems = RestServiceDataKeys.SERVICE_ITEMS.getData(e.getDataContext()); - - for (RestServiceItem serviceItem : serviceItems) { - PsiNavigateUtil.navigate(serviceItem.getPsiElement()); - } - - } - - - protected boolean isVisible(AnActionEvent e) { - return true; - } -} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java b/src/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java deleted file mode 100644 index bfc4588..0000000 --- a/src/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.zhaow.restful.statistics; - -import com.intellij.featureStatistics.ApplicabilityFilter; -import com.intellij.featureStatistics.FeatureDescriptor; -import com.intellij.featureStatistics.GroupDescriptor; -import com.intellij.featureStatistics.ProductivityFeaturesProvider; -import com.intellij.remoteServer.util.CloudBundle; - -import java.util.Collections; - -public class RestfulToolkitFeaturesProvider extends ProductivityFeaturesProvider { - public static final String CLOUDS_GROUP_ID = "clouds"; - public static final String UPLOAD_SSH_KEY_FEATURE_ID = "upload.ssh.key"; - - @Override - public FeatureDescriptor[] getFeatureDescriptors() { - return new FeatureDescriptor[]{new FeatureDescriptor(UPLOAD_SSH_KEY_FEATURE_ID, - CLOUDS_GROUP_ID, - "UploadSshKey.html", - CloudBundle.getText("upload.ssh.key.display.name"), - 0, - 0, - Collections.emptySet(), - 0, - this)}; - } - - @Override - public GroupDescriptor[] getGroupDescriptors() - { - return new GroupDescriptor[] { - new GroupDescriptor(CLOUDS_GROUP_ID, CloudBundle.getText("group.display.name")) - }; - } - - @Override - public ApplicabilityFilter[] getApplicabilityFilters() { - return new ApplicabilityFilter[0]; - } -} \ No newline at end of file diff --git a/src/java/com/zhaow/utils/RestfulToolkitBundle.java b/src/java/com/zhaow/utils/RestfulToolkitBundle.java deleted file mode 100644 index 32a9c39..0000000 --- a/src/java/com/zhaow/utils/RestfulToolkitBundle.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.zhaow.utils; - -import com.intellij.CommonBundle; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.PropertyKey; - -import java.lang.ref.Reference; -import java.lang.ref.SoftReference; -import java.util.ResourceBundle; - -/** - * @author zhaow - */ -public class RestfulToolkitBundle { - - private static Reference ourBundle; - - @NonNls private static final String BUNDLE = "RestfulToolkitBundle"; - - private RestfulToolkitBundle() { - - } - - public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { - return CommonBundle.message(getBundle(), key, params); - } - - private static ResourceBundle getBundle() { - ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle); - if (bundle == null) { - bundle = ResourceBundle.getBundle(BUNDLE); - ourBundle = new SoftReference<>(bundle); - } - return bundle; - } -} \ No newline at end of file diff --git a/src/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java b/src/main/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java similarity index 57% rename from src/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java rename to src/main/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java index 20ba828..22ef314 100644 --- a/src/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java +++ b/src/main/java/com/zhaow/livetemplate/RestToolkitTemplatesProvider.java @@ -3,14 +3,14 @@ import com.intellij.codeInsight.template.impl.DefaultLiveTemplatesProvider; public class RestToolkitTemplatesProvider implements DefaultLiveTemplatesProvider { - @Override - public String[] getDefaultLiveTemplateFiles() { + @Override + public String[] getDefaultLiveTemplateFiles() { // return new String[]{"/liveTemplates/RestToolkit"}; - return null; - } + return null; + } - @Override - public String[] getHiddenLiveTemplateFiles() { - return null; - } + @Override + public String[] getHiddenLiveTemplateFiles() { + return null; + } } \ No newline at end of file diff --git a/src/java/com/zhaow/restful/action/AbstractBaseAction.java b/src/main/java/com/zhaow/restful/action/AbstractBaseAction.java similarity index 99% rename from src/java/com/zhaow/restful/action/AbstractBaseAction.java rename to src/main/java/com/zhaow/restful/action/AbstractBaseAction.java index 66413bf..392162e 100644 --- a/src/java/com/zhaow/restful/action/AbstractBaseAction.java +++ b/src/main/java/com/zhaow/restful/action/AbstractBaseAction.java @@ -19,6 +19,7 @@ protected Project myProject(AnActionEvent e) { /** * 设置触发有效条件 + * * @param e * @param visible */ diff --git a/src/java/com/zhaow/restful/action/ConvertClassToJSONAction.java b/src/main/java/com/zhaow/restful/action/ConvertClassToJSONAction.java similarity index 88% rename from src/java/com/zhaow/restful/action/ConvertClassToJSONAction.java rename to src/main/java/com/zhaow/restful/action/ConvertClassToJSONAction.java index 9f63b7a..36eea1a 100644 --- a/src/java/com/zhaow/restful/action/ConvertClassToJSONAction.java +++ b/src/main/java/com/zhaow/restful/action/ConvertClassToJSONAction.java @@ -19,7 +19,7 @@ public void actionPerformed(AnActionEvent e) { PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT); PsiClass psiClass = getPsiClass(psiElement); - if(psiClass == null) return; + if (psiClass == null) return; String json = PsiClassHelper.create(psiClass).convertClassToJSON(myProject(e), true); CopyPasteManager.getInstance().setContents(new StringSelection(json)); @@ -31,7 +31,7 @@ protected PsiClass getPsiClass(PsiElement psiElement) { if (psiElement instanceof PsiClass) { psiClass = (PsiClass) psiElement; - }else if (psiElement instanceof KtClassOrObject) { + } else if (psiElement instanceof KtClassOrObject) { if (LightClassUtil.INSTANCE.canGenerateLightClass((KtClassOrObject) psiElement)) { psiClass = LightClassUtilsKt.toLightClass((KtClassOrObject) psiElement); } @@ -42,6 +42,6 @@ protected PsiClass getPsiClass(PsiElement psiElement) { @Override public void update(AnActionEvent e) { PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT); - setActionPresentationVisible(e,psiElement instanceof PsiClass || psiElement instanceof KtClassOrObject); + setActionPresentationVisible(e, psiElement instanceof PsiClass || psiElement instanceof KtClassOrObject); } } diff --git a/src/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java b/src/main/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java similarity index 95% rename from src/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java rename to src/main/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java index 42ffd25..fecd89e 100644 --- a/src/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java +++ b/src/main/java/com/zhaow/restful/action/ConvertClassToJSONCompressedAction.java @@ -16,7 +16,7 @@ public void actionPerformed(AnActionEvent e) { PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT); PsiClass psiClass = getPsiClass(psiElement); - if(psiClass == null) return; + if (psiClass == null) return; String json = PsiClassHelper.create(psiClass).convertClassToJSON(myProject(e), false); CopyPasteManager.getInstance().setContents(new StringSelection(json)); diff --git a/src/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java b/src/main/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java similarity index 92% rename from src/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java rename to src/main/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java index 73fac0c..9fc49fb 100644 --- a/src/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java +++ b/src/main/java/com/zhaow/restful/action/ConvertKtClassToJSONAction.java @@ -22,6 +22,6 @@ public void actionPerformed(AnActionEvent e) { @Override public void update(AnActionEvent e) { PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT); - setActionPresentationVisible(e,psiElement instanceof KtClass); + setActionPresentationVisible(e, psiElement instanceof KtClass); } } diff --git a/src/java/com/zhaow/restful/annotations/BasePathMapping.java b/src/main/java/com/zhaow/restful/annotations/BasePathMapping.java similarity index 100% rename from src/java/com/zhaow/restful/annotations/BasePathMapping.java rename to src/main/java/com/zhaow/restful/annotations/BasePathMapping.java diff --git a/src/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java b/src/main/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java similarity index 81% rename from src/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java index 9ae8914..609e054 100644 --- a/src/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java +++ b/src/main/java/com/zhaow/restful/annotations/JaxrsHttpMethodAnnotation.java @@ -3,10 +3,10 @@ public enum JaxrsHttpMethodAnnotation { GET("javax.ws.rs.GET", "GET"), - POST( "javax.ws.rs.POST", "POST"), - PUT( "javax.ws.rs.PUT", "PUT"), - DELETE( "javax.ws.rs.DELETE", "DELETE"), - HEAD( "javax.ws.rs.HEAD", "HEAD"), + POST("javax.ws.rs.POST", "POST"), + PUT("javax.ws.rs.PUT", "PUT"), + DELETE("javax.ws.rs.DELETE", "DELETE"), + HEAD("javax.ws.rs.HEAD", "HEAD"), PATCH("javax.ws.rs.PATCH", "PATCH"); JaxrsHttpMethodAnnotation(String qualifiedName, String methodName) { @@ -17,7 +17,7 @@ public enum JaxrsHttpMethodAnnotation { private String qualifiedName; private String methodName; - public String methodName() { + public String methodName() { return this.methodName; } @@ -26,7 +26,7 @@ public String getQualifiedName() { } public String getShortName() { - return qualifiedName.substring(qualifiedName.lastIndexOf(".")-1); + return qualifiedName.substring(qualifiedName.lastIndexOf(".") - 1); } public static JaxrsHttpMethodAnnotation getByQualifiedName(String qualifiedName) { @@ -35,7 +35,7 @@ public static JaxrsHttpMethodAnnotation getByQualifiedName(String qualifiedName) return springRequestAnnotation; } } - return null; + return null; } } \ No newline at end of file diff --git a/src/java/com/zhaow/restful/annotations/JaxrsPathAnnotation.java b/src/main/java/com/zhaow/restful/annotations/JaxrsPathAnnotation.java similarity index 100% rename from src/java/com/zhaow/restful/annotations/JaxrsPathAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/JaxrsPathAnnotation.java diff --git a/src/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java b/src/main/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java similarity index 95% rename from src/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java index 26538e1..acabb6f 100644 --- a/src/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java +++ b/src/main/java/com/zhaow/restful/annotations/JaxrsRequestAnnotation.java @@ -15,7 +15,7 @@ public enum JaxrsRequestAnnotation { private String qualifiedName; private String methodName; - public String methodName() { + public String methodName() { return this.methodName; } @@ -42,7 +42,7 @@ public static JaxrsRequestAnnotation getByQualifiedName(String qualifiedName) { return requestAnnotation; } } - return null; + return null; } } \ No newline at end of file diff --git a/src/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java b/src/main/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java similarity index 80% rename from src/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java index a00dec8..68c6ed7 100644 --- a/src/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java +++ b/src/main/java/com/zhaow/restful/annotations/JaxrsRequestParamAnnotation.java @@ -2,7 +2,7 @@ public enum JaxrsRequestParamAnnotation { - QUERY_PARAM("QueryParam","javax.ws.rs.QueryParam"), PATH_PARAM("PathParam","javax.ws.rs.PathParam"); + QUERY_PARAM("QueryParam", "javax.ws.rs.QueryParam"), PATH_PARAM("PathParam", "javax.ws.rs.PathParam"); JaxrsRequestParamAnnotation(String shortName, String qualifiedName) { this.shortName = shortName; diff --git a/src/java/com/zhaow/restful/annotations/PathMappingAnnotation.java b/src/main/java/com/zhaow/restful/annotations/PathMappingAnnotation.java similarity index 65% rename from src/java/com/zhaow/restful/annotations/PathMappingAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/PathMappingAnnotation.java index 317afdd..17177a3 100644 --- a/src/java/com/zhaow/restful/annotations/PathMappingAnnotation.java +++ b/src/main/java/com/zhaow/restful/annotations/PathMappingAnnotation.java @@ -1,8 +1,8 @@ package com.zhaow.restful.annotations; public interface PathMappingAnnotation { -// List allPathMappingAnnotations = new ArrayList<>(); - public String getQualifiedName() ; + // List allPathMappingAnnotations = new ArrayList<>(); + public String getQualifiedName(); public String getShortName(); diff --git a/src/java/com/zhaow/restful/annotations/SpringControllerAnnotation.java b/src/main/java/com/zhaow/restful/annotations/SpringControllerAnnotation.java similarity index 100% rename from src/java/com/zhaow/restful/annotations/SpringControllerAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/SpringControllerAnnotation.java diff --git a/src/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java b/src/main/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java similarity index 83% rename from src/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java rename to src/main/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java index 5e4fed5..8cad745 100644 --- a/src/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java +++ b/src/main/java/com/zhaow/restful/annotations/SpringRequestMethodAnnotation.java @@ -5,9 +5,9 @@ public enum SpringRequestMethodAnnotation { REQUEST_MAPPING("org.springframework.web.bind.annotation.RequestMapping", null), GET_MAPPING("org.springframework.web.bind.annotation.GetMapping", "GET"), - POST_MAPPING( "org.springframework.web.bind.annotation.PostMapping", "POST"), - PUT_MAPPING( "org.springframework.web.bind.annotation.PutMapping", "PUT"), - DELETE_MAPPING( "org.springframework.web.bind.annotation.DeleteMapping", "DELETE"), + POST_MAPPING("org.springframework.web.bind.annotation.PostMapping", "POST"), + PUT_MAPPING("org.springframework.web.bind.annotation.PutMapping", "PUT"), + DELETE_MAPPING("org.springframework.web.bind.annotation.DeleteMapping", "DELETE"), PATCH_MAPPING("org.springframework.web.bind.annotation.PatchMapping", "PATCH"); SpringRequestMethodAnnotation(String qualifiedName, String methodName) { @@ -18,7 +18,7 @@ public enum SpringRequestMethodAnnotation { private String qualifiedName; private String methodName; - public String methodName() { + public String methodName() { return this.methodName; } @@ -27,7 +27,7 @@ public String getQualifiedName() { } public String getShortName() { - return qualifiedName.substring(qualifiedName.lastIndexOf(".")-1); + return qualifiedName.substring(qualifiedName.lastIndexOf(".") - 1); } public static SpringRequestMethodAnnotation getByQualifiedName(String qualifiedName) { @@ -36,7 +36,7 @@ public static SpringRequestMethodAnnotation getByQualifiedName(String qualifiedN return springRequestAnnotation; } } - return null; + return null; } public static SpringRequestMethodAnnotation getByShortName(String requestMapping) { diff --git a/src/java/com/zhaow/restful/annotations/SpringRequestParamAnnotations.java b/src/main/java/com/zhaow/restful/annotations/SpringRequestParamAnnotations.java similarity index 100% rename from src/java/com/zhaow/restful/annotations/SpringRequestParamAnnotations.java rename to src/main/java/com/zhaow/restful/annotations/SpringRequestParamAnnotations.java diff --git a/src/java/com/zhaow/restful/codegen/SpringBootGenerator.java b/src/main/java/com/zhaow/restful/codegen/SpringBootGenerator.java similarity index 95% rename from src/java/com/zhaow/restful/codegen/SpringBootGenerator.java rename to src/main/java/com/zhaow/restful/codegen/SpringBootGenerator.java index ddeabde..c3f62a0 100644 --- a/src/java/com/zhaow/restful/codegen/SpringBootGenerator.java +++ b/src/main/java/com/zhaow/restful/codegen/SpringBootGenerator.java @@ -48,8 +48,6 @@ public void actionPerformed(AnActionEvent e) { String content = editor.getDocument().getText(); - - // createPackage(); // createFile() @@ -62,7 +60,7 @@ public void actionPerformed(AnActionEvent e) { } - public void createFile(String fileName,String content) { + public void createFile(String fileName, String content) { PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, FileTypes.PLAIN_TEXT, content); PsiDirectory directory = PsiManager.getInstance(project).findDirectory(project.getBaseDir()); @@ -77,7 +75,7 @@ public void createFile(String fileName,String content) { } } - private String genFromTemplate(String templateName, Map dataMap) { + private String genFromTemplate(String templateName, Map dataMap) { VelocityContext context = new VelocityContext(); @@ -106,7 +104,7 @@ private String genFromTemplate(String templateName, Map dataMap // 创建目录,文件 private void createController(String basePackage, String path, String modelName) { - createFile(modelName +"Controller" , genFromTemplate("controller",new HashMap<>())) ; + createFile(modelName + "Controller", genFromTemplate("controller", new HashMap<>())); } private void refreshProject(AnActionEvent e) { diff --git a/src/main/java/com/zhaow/restful/common/ChineseUtill.java b/src/main/java/com/zhaow/restful/common/ChineseUtill.java new file mode 100644 index 0000000..be0d492 --- /dev/null +++ b/src/main/java/com/zhaow/restful/common/ChineseUtill.java @@ -0,0 +1,58 @@ +package com.zhaow.restful.common; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ChineseUtill { + + private static boolean isChinese(char c) { + Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); + if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS + || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS + || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A + || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION + || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION + || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { + return true; + } + return false; + } + + public static boolean isMessyCode(String strName) { + Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*"); + Matcher m = p.matcher(strName); + String after = m.replaceAll(""); + String temp = after.replaceAll("\\p{P}", ""); + char[] ch = temp.trim().toCharArray(); + float chLength = 0; + float count = 0; + for (int i = 0; i < ch.length; i++) { + char c = ch[i]; + if (!Character.isLetterOrDigit(c)) { + if (!isChinese(c)) { + count = count + 1; + } + chLength++; + } + } + float result = count / chLength; + if (result > 0.4) { + return true; + } else { + return false; + } + } + + + public static String toChinese(Object msg) { +// String tempMsg = TransformUtils.toString(msg) ; + String tempMsg = msg.toString(); + if (isMessyCode(tempMsg)) { + try { + return new String(tempMsg.getBytes("ISO8859-1"), "UTF-8"); + } catch (Exception e) { + } + } + return tempMsg; + } +} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/common/IntellijUtils.java b/src/main/java/com/zhaow/restful/common/IntellijUtils.java similarity index 100% rename from src/java/com/zhaow/restful/common/IntellijUtils.java rename to src/main/java/com/zhaow/restful/common/IntellijUtils.java diff --git a/src/java/com/zhaow/restful/common/KtClassHelper.java b/src/main/java/com/zhaow/restful/common/KtClassHelper.java similarity index 94% rename from src/java/com/zhaow/restful/common/KtClassHelper.java rename to src/main/java/com/zhaow/restful/common/KtClassHelper.java index 169f1de..6365d57 100644 --- a/src/java/com/zhaow/restful/common/KtClassHelper.java +++ b/src/main/java/com/zhaow/restful/common/KtClassHelper.java @@ -19,7 +19,7 @@ public class KtClassHelper { KtClass psiClass; - private static int autoCorrelationCount=0; //标记实体递归 + private static int autoCorrelationCount = 0; //标记实体递归 private int listIterateCount = 0; //标记List递归 private Module myModule; @@ -74,7 +74,7 @@ public KtClassOrObject findOnePsiClassByClassName(String className, Project proj } -//PsiShortNamesCache : PsiClass:Demo KtLightClassImpl:data class Greeting(val id: Long, val content: String) { 代码体 } + //PsiShortNamesCache : PsiClass:Demo KtLightClassImpl:data class Greeting(val id: Long, val content: String) { 代码体 } public Collection tryDetectPsiClassByShortClassName(Project project, String shortClassName) { PsiClass[] psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName(shortClassName, GlobalSearchScope.allScope(project));// 所有的 PsiClass[] classesByName = KotlinShortNamesCache.getInstance(project).getClassesByName(shortClassName, GlobalSearchScope.allScope(project)); @@ -87,7 +87,7 @@ public Collection tryDetectPsiClassByShortClassName(Project pro if (ktClassOrObjects.size() > 0) { return ktClassOrObjects; } - if(myModule != null) { + if (myModule != null) { ktClassOrObjects = KotlinClassShortNameIndex.getInstance().get(shortClassName, project, GlobalSearchScope.allScope(project)); } return ktClassOrObjects; diff --git a/src/java/com/zhaow/restful/common/KtFunctionHelper.java b/src/main/java/com/zhaow/restful/common/KtFunctionHelper.java similarity index 95% rename from src/java/com/zhaow/restful/common/KtFunctionHelper.java rename to src/main/java/com/zhaow/restful/common/KtFunctionHelper.java index fe02935..efc0058 100644 --- a/src/java/com/zhaow/restful/common/KtFunctionHelper.java +++ b/src/main/java/com/zhaow/restful/common/KtFunctionHelper.java @@ -19,7 +19,7 @@ public class KtFunctionHelper extends PsiMethodHelper { Project myProject; Module myModule; - private String pathSeparator= "/"; + private String pathSeparator = "/"; public static KtFunctionHelper create(@NotNull KtNamedFunction psiMethod) { return new KtFunctionHelper(psiMethod); @@ -40,12 +40,13 @@ protected KtFunctionHelper(@NotNull KtNamedFunction ktNamedFunction) { @NotNull protected Project getProject() { - myProject = psiMethod.getProject(); + myProject = psiMethod.getProject(); return myProject; } /** * 构建URL参数 key value + * * @return */ public String buildParamString() { @@ -60,7 +61,7 @@ public String buildParamString() { baseTypeParamMap.forEach((s, o) -> param.append(s).append("=").append(o).append("&")); } - return param.length() >0 ? param.deleteCharAt(param.length()-1).toString() : ""; + return param.length() > 0 ? param.deleteCharAt(param.length() - 1).toString() : ""; } /*获取方法中基础类型(primitive和string、date等以及这些类型数组)*/ @@ -110,7 +111,7 @@ public Map getBaseTypeParameterMap() { } }*//* - *//* if (ktClass instanceof KtClass) { + *//* if (ktClass instanceof KtClass) { List ktProperties = ((KtClass) ktClass).getProperties(); for (KtProperty ktProperty : ktProperties) { System.out.println(ktProperty); @@ -124,5 +125,4 @@ public Map getBaseTypeParameterMap() { }*/ - } diff --git a/src/java/com/zhaow/restful/common/PsiAnnotationHelper.java b/src/main/java/com/zhaow/restful/common/PsiAnnotationHelper.java similarity index 100% rename from src/java/com/zhaow/restful/common/PsiAnnotationHelper.java rename to src/main/java/com/zhaow/restful/common/PsiAnnotationHelper.java diff --git a/src/java/com/zhaow/restful/common/PsiClassHelper.java b/src/main/java/com/zhaow/restful/common/PsiClassHelper.java similarity index 85% rename from src/java/com/zhaow/restful/common/PsiClassHelper.java rename to src/main/java/com/zhaow/restful/common/PsiClassHelper.java index 21e4680..65a2b2c 100644 --- a/src/java/com/zhaow/restful/common/PsiClassHelper.java +++ b/src/main/java/com/zhaow/restful/common/PsiClassHelper.java @@ -15,11 +15,12 @@ import java.math.BigDecimal; import java.util.*; + // 处理 实体自关联,第二层自关联字段 public class PsiClassHelper { PsiClass psiClass; - private static int autoCorrelationCount=0; //标记实体递归 + private static int autoCorrelationCount = 0; //标记实体递归 private int listIterateCount = 0; //标记List递归 private Module myModule; @@ -43,10 +44,10 @@ public String convertClassToJSON(String className, Project project) { String queryJson; if (className.contains("List<")) { //参数为 List - List> jsonList = new ArrayList<>(); + List> jsonList = new ArrayList<>(); // 没处理泛型嵌套, - String entityName = className.substring(className.indexOf("<")+1,className.lastIndexOf(">")); + String entityName = className.substring(className.indexOf("<") + 1, className.lastIndexOf(">")); // build RequestBody Json Map jsonMap = assembleClassToMap(entityName, project); @@ -62,23 +63,23 @@ public String convertClassToJSON(String className, Project project) { private String convertPojoEntityToJSON(String className, Project project) { String queryJson; GsonBuilder gsonBuilder = new GsonBuilder().setPrettyPrinting(); - Gson gson = gsonBuilder.create() ; + Gson gson = gsonBuilder.create(); Map jsonMap = assembleClassToMap(className, project); - queryJson = gson.toJson(jsonMap) ; + queryJson = gson.toJson(jsonMap); return queryJson; } - public String convertClassToJSON(Project project , boolean prettyFormat) { + public String convertClassToJSON(Project project, boolean prettyFormat) { GsonBuilder gsonBuilder = new GsonBuilder(); - if(prettyFormat) gsonBuilder.setPrettyPrinting(); - Gson gson = gsonBuilder.create() ; + if (prettyFormat) gsonBuilder.setPrettyPrinting(); + Gson gson = gsonBuilder.create(); Map jsonMap = new HashMap<>(); - if(psiClass != null){ + if (psiClass != null) { jsonMap = assembleClassToMap(psiClass, project); } - String queryJson = gson.toJson(jsonMap) ; + String queryJson = gson.toJson(jsonMap); return queryJson; } @@ -88,19 +89,44 @@ public static Object getJavaBaseTypeDefaultValue(String paramType) { Object paramValue = null; // todo: using map later switch (paramType.toLowerCase()) { - case "byte": paramValue = Byte.valueOf("1");break; - case "char": paramValue = Character.valueOf('Z');break; - case "character": paramValue = Character.valueOf('Z');break; - case "boolean": paramValue = Boolean.TRUE;break; - case "int": paramValue = Integer.valueOf(1);break; - case "integer": paramValue = Integer.valueOf(1);break; - case "double": paramValue = Double.valueOf(1);break; - case "float": paramValue = Float.valueOf(1.0F);break; - case "long": paramValue = Long.valueOf(1L);break; - case "short": paramValue = Short.valueOf("1");break; - case "bigdecimal": return BigDecimal.ONE; - case "string": paramValue = "demoData";break; - case "date": paramValue = DateFormatUtil.formatDateTime(new Date());break; // todo: format date + case "byte": + paramValue = Byte.valueOf("1"); + break; + case "char": + paramValue = Character.valueOf('Z'); + break; + case "character": + paramValue = Character.valueOf('Z'); + break; + case "boolean": + paramValue = Boolean.TRUE; + break; + case "int": + paramValue = Integer.valueOf(1); + break; + case "integer": + paramValue = Integer.valueOf(1); + break; + case "double": + paramValue = Double.valueOf(1); + break; + case "float": + paramValue = Float.valueOf(1.0F); + break; + case "long": + paramValue = Long.valueOf(1L); + break; + case "short": + paramValue = Short.valueOf("1"); + break; + case "bigdecimal": + return BigDecimal.ONE; + case "string": + paramValue = "demoData"; + break; + case "date": + paramValue = DateFormatUtil.formatDateTime(new Date()); + break; // todo: format date // default: paramValue = paramType; } return paramValue; @@ -124,7 +150,6 @@ private Object setFieldDefaultValue(PsiType psiFieldType, Project project) { } - if (psiFieldType instanceof PsiClassReferenceType) { String className = ((PsiClassReferenceType) psiFieldType).getClassName(); // PsiUtil.getTopLevelClass(psiFieldType); @@ -147,9 +172,9 @@ private Object setFieldDefaultValue(PsiType psiFieldType, Project project) { // 处理递归 if (fieldClass != null) { // todo: 处理递归问题 autoCorrelationCount - if(autoCorrelationCount > 0) return new HashMap(); - if(fullName.equals(fieldClass.getQualifiedName())){ - autoCorrelationCount ++; + if (autoCorrelationCount > 0) return new HashMap(); + if (fullName.equals(fieldClass.getQualifiedName())) { + autoCorrelationCount++; } return assembleClassToMap(fieldClass, project); @@ -205,7 +230,7 @@ public Collection tryDetectPsiClassByShortClassName(Project project, S return psiClassCollection; } - if(myModule != null) { + if (myModule != null) { psiClassCollection = JavaShortClassNameIndex.getInstance().get(shortClassName, project, GlobalSearchScope.allScope(project)); } @@ -222,7 +247,7 @@ public PsiClass findOnePsiClassByClassName2(String className, Project project) { // psiClass.getPrimaryConstructor().getText(); // (val id: Long, val content: String) // psiClass.getFqName(); // class fullQualifiedName :org.jetbrains.kotlin.demo.Greeting - PsiClass[] psiClasses = tryDetectPsiClassByShortClassName2( shortClassName,project); + PsiClass[] psiClasses = tryDetectPsiClassByShortClassName2(shortClassName, project); if (psiClasses.length == 0) { return null; @@ -259,7 +284,8 @@ public PsiClass findOnePsiClassByClassName2(String className, Project project) { } return psiClass; } - public PsiClass[] tryDetectPsiClassByShortClassName2(String shortClassName,Project project) { + + public PsiClass[] tryDetectPsiClassByShortClassName2(String shortClassName, Project project) { PsiClass[] psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName(shortClassName, GlobalSearchScope.allScope(project));// 所有的 @@ -267,7 +293,7 @@ public PsiClass[] tryDetectPsiClassByShortClassName2(String shortClassName,Proje return psiClasses; } - if(myModule != null) { + if (myModule != null) { psiClasses = PsiShortNamesCache.getInstance(project).getClassesByName(shortClassName, GlobalSearchScope.allScope(project));// 所有的 if (psiClasses != null && psiClasses.length > 0) { return psiClasses; @@ -282,7 +308,7 @@ public Map assembleClassToMap(String className, Project project) PsiClass psiClass = findOnePsiClassByClassName(className, project); Map jsonMap = new HashMap<>(); - if(psiClass != null){ + if (psiClass != null) { jsonMap = assembleClassToMap(psiClass, project); } return jsonMap; @@ -293,7 +319,7 @@ public Map assembleClassToMap(PsiClass psiClass, Project project return assembleClassToMap(psiClass, project, defaultRecursiveCount); } - public Map assembleClassToMap(PsiClass psiClass, Project project,int recursiveCount) { + public Map assembleClassToMap(PsiClass psiClass, Project project, int recursiveCount) { Map map = new LinkedHashMap<>(); PsiField[] fields = psiClass.getFields(); @@ -312,11 +338,11 @@ public Map assembleClassToMap(PsiClass psiClass, Project project if (psiFieldType instanceof PsiArrayType) { PsiType psiType = ((PsiArrayType) psiFieldType).getComponentType(); - Object baseTypeDefaultValue = getJavaBaseTypeDefaultValue( psiType.getPresentableText() ); + Object baseTypeDefaultValue = getJavaBaseTypeDefaultValue(psiType.getPresentableText()); if (baseTypeDefaultValue != null) { List objects = new ArrayList<>(); objects.add(baseTypeDefaultValue); - map.put(fieldName, objects ); + map.put(fieldName, objects); } continue; @@ -332,7 +358,7 @@ public Map assembleClassToMap(PsiClass psiClass, Project project // self recursion if (resolveClass.getQualifiedName().equals(psiClass.getQualifiedName())) { if (recursiveCount > 0) { - Map objectMap = assembleClassToMap(resolveClass, project,0); + Map objectMap = assembleClassToMap(resolveClass, project, 0); map.put(fieldName, objectMap); continue; } @@ -345,7 +371,7 @@ public Map assembleClassToMap(PsiClass psiClass, Project project if (parameters != null && parameters.length > 0) { PsiType parameter = parameters[0]; // 自关联 - if (recursiveCount <= 0 ) { + if (recursiveCount <= 0) { continue; } @@ -355,11 +381,11 @@ public Map assembleClassToMap(PsiClass psiClass, Project project continue; } - Object baseTypeDefaultValue = getJavaBaseTypeDefaultValue( parameter.getPresentableText() ); + Object baseTypeDefaultValue = getJavaBaseTypeDefaultValue(parameter.getPresentableText()); if (baseTypeDefaultValue != null) { List objects = new ArrayList<>(); objects.add(baseTypeDefaultValue); - map.put(fieldName, objects ); + map.put(fieldName, objects); continue; } @@ -385,13 +411,13 @@ public Map assembleClassToMap(PsiClass psiClass, Project project /* 字段是否为List 类型*/ private static boolean isListFieldType(PsiType psiFieldType) { - if (! (psiFieldType instanceof PsiClassReferenceType)) { + if (!(psiFieldType instanceof PsiClassReferenceType)) { return false; } PsiClass resolvePsiClass = ((PsiClassReferenceType) psiFieldType).resolve(); if (resolvePsiClass.getQualifiedName().equals("java.util.List")) { - return true ; + return true; } /*if (resolvePsiClass.getSuperClass().getQualifiedName().equals("java.util.List")) { @@ -415,7 +441,7 @@ private static boolean isListFieldType(PsiType psiFieldType) { /* 字段是否为List 类型*/ private static boolean isEnum(PsiType psiFieldType) { - if (! (psiFieldType instanceof PsiClassReferenceType)) { + if (!(psiFieldType instanceof PsiClassReferenceType)) { return false; } return ((PsiClassReferenceType) psiFieldType).resolve().isEnum(); diff --git a/src/java/com/zhaow/restful/common/PsiMethodHelper.java b/src/main/java/com/zhaow/restful/common/PsiMethodHelper.java similarity index 89% rename from src/java/com/zhaow/restful/common/PsiMethodHelper.java rename to src/main/java/com/zhaow/restful/common/PsiMethodHelper.java index b1c2dae..6fee2f6 100644 --- a/src/java/com/zhaow/restful/common/PsiMethodHelper.java +++ b/src/main/java/com/zhaow/restful/common/PsiMethodHelper.java @@ -28,7 +28,7 @@ public class PsiMethodHelper { Project myProject; Module myModule; - private String pathSeparator= "/"; + private String pathSeparator = "/"; public static PsiMethodHelper create(@NotNull PsiMethod psiMethod) { return new PsiMethodHelper(psiMethod); @@ -45,12 +45,13 @@ protected PsiMethodHelper(PsiMethod psiMethod) { @NotNull protected Project getProject() { - myProject = psiMethod.getProject(); + myProject = psiMethod.getProject(); return myProject; } /** * 构建URL参数 key value + * * @return */ public String buildParamString() { @@ -65,7 +66,7 @@ public String buildParamString() { baseTypeParamMap.forEach((s, o) -> param.append(s).append("=").append(o).append("&")); } - return param.length() >0 ? param.deleteCharAt(param.length()-1).toString() : ""; + return param.length() > 0 ? param.deleteCharAt(param.length() - 1).toString() : ""; } /*获取方法中基础类型(primitive和string、date等以及这些类型数组)*/ @@ -73,7 +74,7 @@ public String buildParamString() { public Map getBaseTypeParameterMap() { List parameterList = getParameterList(); - Map baseTypeParamMap = new LinkedHashMap(); + Map baseTypeParamMap = new LinkedHashMap(); // 拼接参数 for (Parameter parameter : parameterList) { @@ -89,7 +90,7 @@ public Map getBaseTypeParameterMap() { Object defaultValue = PsiClassHelper.getJavaBaseTypeDefaultValue(shortTypeName); //简单常用类型 if (defaultValue != null) { - baseTypeParamMap.put(parameter.getParamName(),(defaultValue)); + baseTypeParamMap.put(parameter.getParamName(), (defaultValue)); continue; } @@ -99,8 +100,8 @@ public Map getBaseTypeParameterMap() { if (psiClass != null) { PsiField[] fields = psiClass.getFields(); for (PsiField field : fields) { - Object fieldDefaultValue = PsiClassHelper.getJavaBaseTypeDefaultValue(field.getType().getPresentableText()); - if(fieldDefaultValue != null) + Object fieldDefaultValue = PsiClassHelper.getJavaBaseTypeDefaultValue(field.getType().getPresentableText()); + if (fieldDefaultValue != null) baseTypeParamMap.put(field.getName(), fieldDefaultValue); } } @@ -120,8 +121,8 @@ public Map getBaseTypeParameterMap() { /* 基础类型默认值 */ @Nullable - public Map getJavaBaseTypeDefaultValue(String paramName, String paramType) { - Map paramMap = new LinkedHashMap<>(); + public Map getJavaBaseTypeDefaultValue(String paramName, String paramType) { + Map paramMap = new LinkedHashMap<>(); Object paramValue = null; paramValue = PsiClassHelper.getJavaBaseTypeDefaultValue(paramType); if (paramValue != null) { @@ -140,7 +141,7 @@ public List getParameterList() { //忽略 request response String paramType = psiParameter.getType().getCanonicalText(); - if(paramType.equals("javax.servlet.http.HttpServletRequest") + if (paramType.equals("javax.servlet.http.HttpServletRequest") || paramType.equals("javax.servlet.http.HttpServletResponse")) continue; //必传参数 @RequestParam @@ -154,14 +155,14 @@ public List getParameterList() { PsiAnnotation pathVariableAnno = modifierList.findAnnotation(PATH_VARIABLE.getQualifiedName()); if (pathVariableAnno != null) { requestName = getAnnotationValue(pathVariableAnno); - Parameter parameter = new Parameter(paramType, requestName != null ? requestName: paramName).setRequired(true).requestBodyFound(requestBodyFound); + Parameter parameter = new Parameter(paramType, requestName != null ? requestName : paramName).setRequired(true).requestBodyFound(requestBodyFound); parameterList.add(parameter); } PsiAnnotation requestParamAnno = modifierList.findAnnotation(REQUEST_PARAM.getQualifiedName()); if (requestParamAnno != null) { requestName = getAnnotationValue(requestParamAnno); - Parameter parameter = new Parameter(paramType, requestName != null ? requestName: paramName).setRequired(true).requestBodyFound(requestBodyFound); + Parameter parameter = new Parameter(paramType, requestName != null ? requestName : paramName).setRequired(true).requestBodyFound(requestBodyFound); parameterList.add(parameter); } @@ -185,6 +186,7 @@ public String getAnnotationValue(PsiAnnotation annotation) { /** * 构建RequestBody json 参数 + * * @param parameter * @return */ @@ -192,14 +194,13 @@ public String buildRequestBodyJson(Parameter parameter) { // JavaFullClassNameIndex.getInstance(); Project project = psiMethod.getProject(); - final String className = parameter.getParamType(); + final String className = parameter.getParamType(); String queryJson = PsiClassHelper.create(psiMethod.getContainingClass()).withModule(myModule).convertClassToJSON(className, project); return queryJson; } - public String buildRequestBodyJson() { List parameterList = this.getParameterList(); for (Parameter parameter : parameterList) { @@ -221,7 +222,7 @@ public String buildServiceUriPath() { if (isSpringRestSupported(containingClass)) { ctrlPath = RequestMappingAnnotationHelper.getOneRequestMappingPath(containingClass); methodPath = RequestMappingAnnotationHelper.getOneRequestMappingPath(psiMethod); - }else if(isJaxrsRestSupported(containingClass)){ + } else if (isJaxrsRestSupported(containingClass)) { ctrlPath = JaxrsAnnotationHelper.getClassUriPath(containingClass); methodPath = JaxrsAnnotationHelper.getMethodUriPath(psiMethod); } @@ -245,9 +246,9 @@ public String buildServiceUriPathWithParams() { // RequestMapping 注解设置了 param if (!params.isEmpty()) { StringBuilder urlBuilder = new StringBuilder(serviceUriPath); - return urlBuilder.append(serviceUriPath.contains("?") ? "&": "?").append(params).toString(); + return urlBuilder.append(serviceUriPath.contains("?") ? "&" : "?").append(params).toString(); } - return serviceUriPath; + return serviceUriPath; } //包含 "RestController" "Controller" @@ -258,18 +259,17 @@ public static boolean isSpringRestSupported(PsiClass containingClass) { modifierList.findAnnotation(SpringControllerAnnotation.CONTROLLER.getQualifiedName()) != null ;*/ return modifierList.findAnnotation(SpringControllerAnnotation.REST_CONTROLLER.getQualifiedName()) != null || - modifierList.findAnnotation(SpringControllerAnnotation.CONTROLLER.getQualifiedName()) != null ; + modifierList.findAnnotation(SpringControllerAnnotation.CONTROLLER.getQualifiedName()) != null; } //包含 "RestController" "Controller" public static boolean isJaxrsRestSupported(PsiClass containingClass) { PsiModifierList modifierList = containingClass.getModifierList(); - return modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null ; + return modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null; } - /* 生成完整 URL , 附带参数 */ @NotNull public String buildFullUrlWithParams() { @@ -281,9 +281,9 @@ public String buildFullUrlWithParams() { // RequestMapping 注解设置了 param if (!params.isEmpty()) { StringBuilder urlBuilder = new StringBuilder(fullUrl); - return urlBuilder.append(fullUrl.contains("?") ? "&": "?").append(params).toString(); + return urlBuilder.append(fullUrl.contains("?") ? "&" : "?").append(params).toString(); } - return fullUrl; + return fullUrl; } @NotNull diff --git a/src/java/com/zhaow/restful/common/RequestHelper.java b/src/main/java/com/zhaow/restful/common/RequestHelper.java similarity index 88% rename from src/java/com/zhaow/restful/common/RequestHelper.java rename to src/main/java/com/zhaow/restful/common/RequestHelper.java index fd94628..cbb11a7 100644 --- a/src/java/com/zhaow/restful/common/RequestHelper.java +++ b/src/main/java/com/zhaow/restful/common/RequestHelper.java @@ -31,18 +31,23 @@ public static String request(String url, String method) { } switch (method.toUpperCase()) { - case "GET": return get(url); - case "POST": return post(url); - case "PUT": return put(url); - case "DELETE": return delete(url); - default:return "not supported method : "+method + "."; + case "GET": + return get(url); + case "POST": + return post(url); + case "PUT": + return put(url); + case "DELETE": + return delete(url); + default: + return "not supported method : " + method + "."; } } public static String get(String url) { CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpMethod = new HttpGet(completed(url)); String result = null; try { @@ -74,7 +79,7 @@ public static String post(String url) { String result = null; CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpEntity httpEntity; httpEntity = new UrlEncodedFormEntity(params); @@ -108,7 +113,7 @@ public static String put(String url) { String result; CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPut httpMethod = new HttpPut(completed(url)); response = httpClient.execute(httpMethod); @@ -138,10 +143,10 @@ public static String delete(String url) { url = "http://" + url; } - String result ; + String result; CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpDelete httpMethod = new HttpDelete(url); response = httpClient.execute(httpMethod); @@ -168,7 +173,7 @@ public static String delete(String url) { public static String postRequestBodyWithJson(String url, String json) { CloseableHttpResponse response = null; - CloseableHttpClient httpClient = HttpClients.createDefault(); + CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postMethod = new HttpPost(completed(url)); @@ -179,7 +184,7 @@ public static String postRequestBodyWithJson(String url, String json) { httpEntity.setContentType("application/json"); httpEntity.setContentEncoding("UTF-8"); - postMethod.addHeader("Content-type","application/json; charset=utf-8"); + postMethod.addHeader("Content-type", "application/json; charset=utf-8"); postMethod.setHeader("Accept", "application/json"); // postMethod.setEntity(new StringEntity(parameters, Charset.forName("UTF-8"))); postMethod.setEntity(httpEntity); //设置post请求实体 @@ -204,12 +209,14 @@ private static void release(CloseableHttpResponse response, CloseableHttpClient if (response != null) { try { response.close(); - } catch (IOException e) { } + } catch (IOException e) { + } } if (httpClient != null) { try { httpClient.close(); - } catch (IOException e) { } + } catch (IOException e) { + } } } @@ -230,7 +237,7 @@ private static String toString(HttpEntity entity) { e.printStackTrace(); } - if(result != null && JsonUtils.isValidJson(result)) + if (result != null && JsonUtils.isValidJson(result)) return JsonUtils.format(result); return ""; diff --git a/src/java/com/zhaow/restful/common/RestSupportedAnnotationHelper.java b/src/main/java/com/zhaow/restful/common/RestSupportedAnnotationHelper.java similarity index 100% rename from src/java/com/zhaow/restful/common/RestSupportedAnnotationHelper.java rename to src/main/java/com/zhaow/restful/common/RestSupportedAnnotationHelper.java diff --git a/src/java/com/zhaow/restful/common/ServiceHelper.java b/src/main/java/com/zhaow/restful/common/ServiceHelper.java similarity index 94% rename from src/java/com/zhaow/restful/common/ServiceHelper.java rename to src/main/java/com/zhaow/restful/common/ServiceHelper.java index 2195d27..5ed3c24 100644 --- a/src/java/com/zhaow/restful/common/ServiceHelper.java +++ b/src/main/java/com/zhaow/restful/common/ServiceHelper.java @@ -47,7 +47,7 @@ public static List buildRestServiceItemListUsingResolver(Module SpringResolver springResolver = new SpringResolver(module); JaxrsResolver jaxrsResolver = new JaxrsResolver(module); - ServiceResolver[] resolvers = {springResolver,jaxrsResolver}; + ServiceResolver[] resolvers = {springResolver, jaxrsResolver}; for (ServiceResolver resolver : resolvers) { List allSupportedServiceItemsInModule = resolver.findAllSupportedServiceItemsInModule(); @@ -65,7 +65,7 @@ public static List buildRestServiceItemListUsingResolver(Projec SpringResolver springResolver = new SpringResolver(project); JaxrsResolver jaxrsResolver = new JaxrsResolver(project); - ServiceResolver[] resolvers = {springResolver,jaxrsResolver}; + ServiceResolver[] resolvers = {springResolver, jaxrsResolver}; for (ServiceResolver resolver : resolvers) { List allSupportedServiceItemsInProject = resolver.findAllSupportedServiceItemsInProject(); diff --git a/src/java/com/zhaow/restful/common/ToolkitIcons.java b/src/main/java/com/zhaow/restful/common/ToolkitIcons.java similarity index 58% rename from src/java/com/zhaow/restful/common/ToolkitIcons.java rename to src/main/java/com/zhaow/restful/common/ToolkitIcons.java index 711125d..055e96a 100644 --- a/src/java/com/zhaow/restful/common/ToolkitIcons.java +++ b/src/main/java/com/zhaow/restful/common/ToolkitIcons.java @@ -16,31 +16,31 @@ public static Icon get(HttpMethod method) { } if (method.equals(HttpMethod.GET)) { return METHOD.GET; - }else if(method.equals(HttpMethod.POST)) { + } else if (method.equals(HttpMethod.POST)) { return METHOD.POST; } else if (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PATCH)) { return METHOD.PUT; - }else if(method.equals(HttpMethod.DELETE)) { + } else if (method.equals(HttpMethod.DELETE)) { return METHOD.DELETE; } return null; } - public static Icon GET = IconLoader.getIcon("/icons/method/g.png"); // 16x16 GREEN + public static Icon GET = IconLoader.getIcon("/icons/method/g.png"); // 16x16 GREEN // post put patch - public static Icon PUT = IconLoader.getIcon("/icons/method/p2.png"); // 16x16 ORANGE - public static Icon POST = IconLoader.getIcon("/icons/method/p.png"); // 16x16 BLUE - public static Icon PATCH = IconLoader.getIcon("/icons/method/p3.png"); // 16x16 GRAY - public static Icon DELETE = IconLoader.getIcon("/icons/method/d.png"); // 16x16 RED - public static Icon UNDEFINED = IconLoader.getIcon("/icons/method/undefined.png"); // 16x16 GRAY + public static Icon PUT = IconLoader.getIcon("/icons/method/p2.png"); // 16x16 ORANGE + public static Icon POST = IconLoader.getIcon("/icons/method/p.png"); // 16x16 BLUE + public static Icon PATCH = IconLoader.getIcon("/icons/method/p3.png"); // 16x16 GRAY + public static Icon DELETE = IconLoader.getIcon("/icons/method/d.png"); // 16x16 RED + public static Icon UNDEFINED = IconLoader.getIcon("/icons/method/undefined.png"); // 16x16 GRAY // OPTIONS HEAD } - public static final Icon MODULE = AllIcons.Modules.ModulesNode; // 16x16 + public static final Icon MODULE = AllIcons.Nodes.ModuleGroup; // 16x16 public static final Icon Refresh = AllIcons.Actions.Refresh; // 16x16 // public static final Icon SERVICE = IconLoader.getIcon("/icons/service.png"); // 16x16 -// public static final Icon SERVICE = IconLoader.getIcon("/icons/s1.png"); // 16x16 + // public static final Icon SERVICE = IconLoader.getIcon("/icons/s1.png"); // 16x16 // public static final Icon SERVICE = IconLoader.getIcon("/icons/s2.png"); // 16x16 // public static final Icon SERVICE = IconLoader.getIcon("/icons/s3.png"); // 16x16 public static final Icon SERVICE = IconLoader.getIcon("/icons/service.png"); // 16x16 diff --git a/src/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java b/src/main/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java similarity index 93% rename from src/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java rename to src/main/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java index 0f8b58e..7f27e67 100644 --- a/src/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java +++ b/src/main/java/com/zhaow/restful/common/jaxrs/JaxrsAnnotationHelper.java @@ -25,12 +25,13 @@ private static String getWsPathValue(PsiAnnotation annotation) { /** * 过滤所有注解 + * * @param psiMethod * @return */ public static RequestPath[] getRequestPaths(PsiMethod psiMethod) { PsiAnnotation[] annotations = psiMethod.getModifierList().getAnnotations(); - if(annotations == null) return null; + if (annotations == null) return null; List list = new ArrayList<>(); PsiAnnotation wsPathAnnotation = psiMethod.getModifierList().findAnnotation(JaxrsPathAnnotation.PATH.getQualifiedName()); @@ -46,7 +47,7 @@ public static RequestPath[] getRequestPaths(PsiMethod psiMethod) { } }*/ - Arrays.stream(annotations).forEach(a-> Arrays.stream(jaxrsHttpMethodAnnotations).forEach(methodAnnotation-> { + Arrays.stream(annotations).forEach(a -> Arrays.stream(jaxrsHttpMethodAnnotations).forEach(methodAnnotation -> { if (a.getQualifiedName().equals(methodAnnotation.getQualifiedName())) { list.add(new RequestPath(path, methodAnnotation.getShortName())); } @@ -81,10 +82,10 @@ public static String getMethodUriPath(PsiMethod psiMethod) { } String mappingPath; - if(requestAnnotation != null){ + if (requestAnnotation != null) { PsiAnnotation annotation = psiMethod.getModifierList().findAnnotation(JaxrsPathAnnotation.PATH.getQualifiedName()); mappingPath = getWsPathValue(annotation); - }else { + } else { String methodName = psiMethod.getName(); mappingPath = StringUtils.uncapitalize(methodName); } diff --git a/src/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java b/src/main/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java similarity index 96% rename from src/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java rename to src/main/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java index 13a7105..e2beac7 100644 --- a/src/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java +++ b/src/main/java/com/zhaow/restful/common/resolver/BaseServiceResolver.java @@ -12,7 +12,7 @@ import java.util.ArrayList; import java.util.List; -public abstract class BaseServiceResolver implements ServiceResolver{ +public abstract class BaseServiceResolver implements ServiceResolver { Module myModule; Project myProject; @@ -40,12 +40,12 @@ public List findAllSupportedServiceItemsInModule() { } - public abstract List getRestServiceItemList(Project project, GlobalSearchScope globalSearchScope) ; + public abstract List getRestServiceItemList(Project project, GlobalSearchScope globalSearchScope); @Override public List findAllSupportedServiceItemsInProject() { List itemList = null; - if(myProject == null && myModule != null){ + if (myProject == null && myModule != null) { myProject = myModule.getProject(); } diff --git a/src/java/com/zhaow/restful/common/resolver/JaxrsResolver.java b/src/main/java/com/zhaow/restful/common/resolver/JaxrsResolver.java similarity index 72% rename from src/java/com/zhaow/restful/common/resolver/JaxrsResolver.java rename to src/main/java/com/zhaow/restful/common/resolver/JaxrsResolver.java index e90c001..97f8c8c 100644 --- a/src/java/com/zhaow/restful/common/resolver/JaxrsResolver.java +++ b/src/main/java/com/zhaow/restful/common/resolver/JaxrsResolver.java @@ -17,7 +17,7 @@ //import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex; -public class JaxrsResolver extends BaseServiceResolver { +public class JaxrsResolver extends BaseServiceResolver { public JaxrsResolver(Module module) { myModule = module; @@ -82,35 +82,35 @@ public List getRestServiceItemList(Project project, GlobalSearc // 标注了 jaxrs Path 注解的类 // Collection psiAnnotations = JavaAnnotationIndex.getInstance().get(supportedAnnotation.getShortName(), project, globalSearchScope); - Collection psiAnnotations = JavaAnnotationIndex.getInstance().get(JaxrsPathAnnotation.PATH.getShortName(), project, globalSearchScope); + Collection psiAnnotations = JavaAnnotationIndex.getInstance().get(JaxrsPathAnnotation.PATH.getShortName(), project, globalSearchScope); - for (PsiAnnotation psiAnnotation : psiAnnotations) { - PsiModifierList psiModifierList = (PsiModifierList) psiAnnotation.getParent(); - PsiElement psiElement = psiModifierList.getParent(); + for (PsiAnnotation psiAnnotation : psiAnnotations) { + PsiModifierList psiModifierList = (PsiModifierList) psiAnnotation.getParent(); + PsiElement psiElement = psiModifierList.getParent(); - if (!(psiElement instanceof PsiClass)) continue; + if (!(psiElement instanceof PsiClass)) continue; - PsiClass psiClass = (PsiClass) psiElement; - PsiMethod[] psiMethods = psiClass.getMethods(); + PsiClass psiClass = (PsiClass) psiElement; + PsiMethod[] psiMethods = psiClass.getMethods(); - if (psiMethods == null) { - continue; - } + if (psiMethods == null) { + continue; + } // psiMethodList.addAll(Arrays.asList(psiMethods)); - String classUriPath = JaxrsAnnotationHelper.getClassUriPath(psiClass); + String classUriPath = JaxrsAnnotationHelper.getClassUriPath(psiClass); - for (PsiMethod psiMethod : psiMethods) { - RequestPath[] methodUriPaths = JaxrsAnnotationHelper.getRequestPaths(psiMethod); + for (PsiMethod psiMethod : psiMethods) { + RequestPath[] methodUriPaths = JaxrsAnnotationHelper.getRequestPaths(psiMethod); - for (RequestPath methodUriPath : methodUriPaths) { - RestServiceItem item = createRestServiceItem(psiMethod, classUriPath, methodUriPath); - itemList.add(item); - } + for (RequestPath methodUriPath : methodUriPaths) { + RestServiceItem item = createRestServiceItem(psiMethod, classUriPath, methodUriPath); + itemList.add(item); } - } + + } // } diff --git a/src/java/com/zhaow/restful/common/resolver/ServiceResolver.java b/src/main/java/com/zhaow/restful/common/resolver/ServiceResolver.java similarity index 100% rename from src/java/com/zhaow/restful/common/resolver/ServiceResolver.java rename to src/main/java/com/zhaow/restful/common/resolver/ServiceResolver.java diff --git a/src/java/com/zhaow/restful/common/resolver/SpringResolver.java b/src/main/java/com/zhaow/restful/common/resolver/SpringResolver.java similarity index 94% rename from src/java/com/zhaow/restful/common/resolver/SpringResolver.java rename to src/main/java/com/zhaow/restful/common/resolver/SpringResolver.java index dca668e..22047a0 100644 --- a/src/java/com/zhaow/restful/common/resolver/SpringResolver.java +++ b/src/main/java/com/zhaow/restful/common/resolver/SpringResolver.java @@ -21,10 +21,11 @@ import java.util.Collections; import java.util.List; -public class SpringResolver extends BaseServiceResolver { -/* Module myModule; - Project myProject;*/ - PropertiesHandler propertiesHandler ; +public class SpringResolver extends BaseServiceResolver { + /* Module myModule; + Project myProject;*/ + PropertiesHandler propertiesHandler; + public SpringResolver(Module module) { myModule = module; propertiesHandler = new PropertiesHandler(module); @@ -182,7 +183,7 @@ protected List getServiceItemList(PsiClass psiClass) { for (RequestPath classRequestPath : classRequestPaths) { for (RequestPath methodRequestPath : methodRequestPaths) { - String path = classRequestPath.getPath(); + String path = classRequestPath.getPath(); // String path = tryReplacePlaceholderValueInPath( classRequestPath.getPath() ); RestServiceItem item = createRestServiceItem(psiMethod, path, methodRequestPath); @@ -213,7 +214,7 @@ private List getRequestPaths(KtClass ktClass) { //方法注解 List annotationEntries = ktClass.getModifierList().getAnnotationEntries(); - List requestPaths = getRequestMappings( defaultPath, annotationEntries); + List requestPaths = getRequestMappings(defaultPath, annotationEntries); return requestPaths; } @@ -223,11 +224,11 @@ private List getRequestPaths(KtNamedFunction fun) { String defaultPath = "/"; //方法注解 List annotationEntries = fun.getModifierList().getAnnotationEntries(); - List requestPaths = getRequestMappings( defaultPath, annotationEntries); + List requestPaths = getRequestMappings(defaultPath, annotationEntries); return requestPaths; } - private List getRequestMappings(String defaultPath, List annotationEntries) { + private List getRequestMappings(String defaultPath, List annotationEntries) { List requestPaths = new ArrayList<>(); for (KtAnnotationEntry entry : annotationEntries) { // List requestMappings = getRequestMappings(defaultPath, entry); @@ -334,7 +335,6 @@ private List getRequestMappings(String defaultPath, List getRequestMappings(String defaultPath, KtAnnotationEntry entry) { List requestPaths = new ArrayList<>(); List methodList = new ArrayList<>(); @@ -349,14 +349,14 @@ private List getRequestMappings(String defaultPath, KtAnnotationEnt if (requestMethodAnnotation.methodName() != null) { // GetMapping PostMapping ... methodList.add(requestMethodAnnotation.methodName()); } else { - methodList.addAll(getAttributeValues( entry, "method") ); // RequestMapping + methodList.addAll(getAttributeValues(entry, "method")); // RequestMapping } //注解参数值 // KtValueArgumentList valueArgumentList = entry.getValueArgumentList(); if (entry.getValueArgumentList() != null) { List mappingValues = getAttributeValues(entry, null); - if(!mappingValues.isEmpty() ) + if (!mappingValues.isEmpty()) pathList.addAll(mappingValues); else pathList.addAll(getAttributeValues(entry, "value")); // path @@ -364,7 +364,7 @@ private List getRequestMappings(String defaultPath, KtAnnotationEnt pathList.addAll(getAttributeValues(entry, "path")); // path } - if(pathList.isEmpty()) pathList.add(defaultPath); //没指定参数 + if (pathList.isEmpty()) pathList.add(defaultPath); //没指定参数 if (methodList.size() > 0) { for (String method : methodList) { @@ -384,7 +384,7 @@ private List getRequestMappings(String defaultPath, KtAnnotationEnt private List getAttributeValues(KtAnnotationEntry entry, String attribute) { KtValueArgumentList valueArgumentList = entry.getValueArgumentList(); - if(valueArgumentList == null) return Collections.emptyList(); + if (valueArgumentList == null) return Collections.emptyList(); List arguments = valueArgumentList.getArguments(); @@ -394,7 +394,7 @@ private List getAttributeValues(KtAnnotationEntry entry, String attribut KtExpression argumentExpression = ktValueArgument.getArgumentExpression(); - if (( argumentName == null && attribute == null ) || (argumentName != null && argumentName.getText().equals(attribute) ) ) { + if ((argumentName == null && attribute == null) || (argumentName != null && argumentName.getText().equals(attribute))) { List methodList = new ArrayList<>(); // array, kotlin 1.1- if (argumentExpression.getText().startsWith("arrayOf")) { @@ -412,7 +412,7 @@ private List getAttributeValues(KtAnnotationEntry entry, String attribut // 有且仅有一个value PsiElement[] paths = ktValueArgument.getArgumentExpression().getChildren(); // Arrays.stream(paths).forEach(p -> methodList.add(p.getText())); - methodList.add(paths.length==0? "" : paths[0].getText()); + methodList.add(paths.length == 0 ? "" : paths[0].getText()); } return methodList; diff --git a/src/main/java/com/zhaow/restful/common/spring/AntPathMatcher.java b/src/main/java/com/zhaow/restful/common/spring/AntPathMatcher.java new file mode 100644 index 0000000..1b22c46 --- /dev/null +++ b/src/main/java/com/zhaow/restful/common/spring/AntPathMatcher.java @@ -0,0 +1,648 @@ +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.zhaow.restful.common.spring; + +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * {@link PathMatcher} implementation for Ant-style path patterns. + * + *

    Part of this mapping code has been kindly borrowed from Apache Ant. + * + *

    The mapping matches URLs using the following rules:
    + *

      + *
    • {@code ?} matches one character
    • + *
    • {@code *} matches zero or more characters
    • + *
    • {@code **} matches zero or more directories in a path
    • + *
    • {@code {spring:[a-z]+}} matches the regexp {@code [a-z]+} as a path variable named "spring"
    • + *
    + * + *

    Examples

    + *
      + *
    • {@code com/t?st.jsp} — matches {@code com/test.jsp} but also + * {@code com/tast.jsp} or {@code com/txst.jsp}
    • + *
    • {@code com/*.jsp} — matches all {@code .jsp} files in the + * {@code com} directory
    • + *
    • com/**/test.jsp — matches all {@code test.jsp} + * files underneath the {@code com} path
    • + *
    • org/springframework/**/*.jsp — matches all + * {@code .jsp} files underneath the {@code org/springframework} path
    • + *
    • org/**/servlet/bla.jsp — matches + * {@code org/springframework/servlet/bla.jsp} but also + * {@code org/springframework/testing/servlet/bla.jsp} and {@code org/servlet/bla.jsp}
    • + *
    • {@code com/{filename:\\w+}.jsp} will match {@code com/test.jsp} and assign the value {@code test} + * to the {@code filename} variable
    • + *
    + * + *

    Note: a pattern and a path must both be absolute or must + * both be relative in order for the two to match. Therefore it is recommended + * that users of this implementation to sanitize patterns in order to prefix + * them with "/" as it makes sense in the context in which they're used. + * + * @author Alef Arendsen + * @author Juergen Hoeller + * @author Rob Harrop + * @author Arjen Poutsma + * @author Rossen Stoyanchev + * @author Sam Brannen + * @since 16.07.2003 + */ +public class AntPathMatcher /*implements PathMatcher*/ { + + /** + * Default path separator: "/" + */ + public static final String DEFAULT_PATH_SEPARATOR = "/"; + + private static final int CACHE_TURNOFF_THRESHOLD = 65536; + + private static final Pattern VARIABLE_PATTERN = Pattern.compile("\\{[^/]+?\\}"); + + private static final char[] WILDCARD_CHARS = {'*', '?', '{'}; + + private String pathSeparator; + +// private PathSeparatorPatternCache pathSeparatorPatternCache; + + private boolean caseSensitive = true; + + private boolean trimTokens = false; + + private volatile Boolean cachePatterns; + + private final Map tokenizedPatternCache = new ConcurrentHashMap(256); + + final Map stringMatcherCache = new ConcurrentHashMap(256); + + + /** + * Create a new instance with the {@link #DEFAULT_PATH_SEPARATOR}. + */ + public AntPathMatcher() { + this.pathSeparator = DEFAULT_PATH_SEPARATOR; +// this.pathSeparatorPatternCache = new PathSeparatorPatternCache(DEFAULT_PATH_SEPARATOR); + } + + private void deactivatePatternCache() { + this.cachePatterns = false; + this.tokenizedPatternCache.clear(); + this.stringMatcherCache.clear(); + } + + public boolean match(String pattern, String path) { + return doMatch(pattern, path, true, null); + } + + /** + * Actually match the given {@code path} against the given {@code pattern}. + * + * @param pattern the pattern to match against + * @param path the path String to test + * @param fullMatch whether a full pattern match is required (else a pattern match + * as far as the given base path goes is sufficient) + * @return {@code true} if the supplied {@code path} matched, {@code false} if it didn't + */ + protected boolean doMatch(String pattern, String path, boolean fullMatch, Map uriTemplateVariables) { + if (path.startsWith(this.pathSeparator) != pattern.startsWith(this.pathSeparator)) { + return false; + } + + String[] pattDirs = tokenizePattern(pattern); + if (fullMatch && this.caseSensitive && !isPotentialMatch(path, pattDirs)) { + return false; + } + + String[] pathDirs = tokenizePath(path); + + int pattIdxStart = 0; + int pattIdxEnd = pattDirs.length - 1; + int pathIdxStart = 0; + int pathIdxEnd = pathDirs.length - 1; + + // Match all elements up to the first ** + while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { + String pattDir = pattDirs[pattIdxStart]; + if ("**".equals(pattDir)) { + break; + } + if (!matchStrings(pattDir, pathDirs[pathIdxStart], uriTemplateVariables)) { + return false; + } + pattIdxStart++; + pathIdxStart++; + } + + if (pathIdxStart > pathIdxEnd) { + // Path is exhausted, only match if rest of pattern is * or **'s + if (pattIdxStart > pattIdxEnd) { + return (pattern.endsWith(this.pathSeparator) == path.endsWith(this.pathSeparator)); + } + if (!fullMatch) { + return true; + } + if (pattIdxStart == pattIdxEnd && pattDirs[pattIdxStart].equals("*") && path.endsWith(this.pathSeparator)) { + return true; + } + for (int i = pattIdxStart; i <= pattIdxEnd; i++) { + if (!pattDirs[i].equals("**")) { + return false; + } + } + return true; + } else if (pattIdxStart > pattIdxEnd) { + // String not exhausted, but pattern is. Failure. + return false; + } else if (!fullMatch && "**".equals(pattDirs[pattIdxStart])) { + // Path start definitely matches due to "**" part in pattern. + return true; + } + + // up to last '**' + while (pattIdxStart <= pattIdxEnd && pathIdxStart <= pathIdxEnd) { + String pattDir = pattDirs[pattIdxEnd]; + if (pattDir.equals("**")) { + break; + } + if (!matchStrings(pattDir, pathDirs[pathIdxEnd], uriTemplateVariables)) { + return false; + } + pattIdxEnd--; + pathIdxEnd--; + } + if (pathIdxStart > pathIdxEnd) { + // String is exhausted + for (int i = pattIdxStart; i <= pattIdxEnd; i++) { + if (!pattDirs[i].equals("**")) { + return false; + } + } + return true; + } + + while (pattIdxStart != pattIdxEnd && pathIdxStart <= pathIdxEnd) { + int patIdxTmp = -1; + for (int i = pattIdxStart + 1; i <= pattIdxEnd; i++) { + if (pattDirs[i].equals("**")) { + patIdxTmp = i; + break; + } + } + if (patIdxTmp == pattIdxStart + 1) { + // '**/**' situation, so skip one + pattIdxStart++; + continue; + } + // Find the pattern between padIdxStart & padIdxTmp in str between + // strIdxStart & strIdxEnd + int patLength = (patIdxTmp - pattIdxStart - 1); + int strLength = (pathIdxEnd - pathIdxStart + 1); + int foundIdx = -1; + + strLoop: + for (int i = 0; i <= strLength - patLength; i++) { + for (int j = 0; j < patLength; j++) { + String subPat = pattDirs[pattIdxStart + j + 1]; + String subStr = pathDirs[pathIdxStart + i + j]; + if (!matchStrings(subPat, subStr, uriTemplateVariables)) { + continue strLoop; + } + } + foundIdx = pathIdxStart + i; + break; + } + + if (foundIdx == -1) { + return false; + } + + pattIdxStart = patIdxTmp; + pathIdxStart = foundIdx + patLength; + } + + for (int i = pattIdxStart; i <= pattIdxEnd; i++) { + if (!pattDirs[i].equals("**")) { + return false; + } + } + + return true; + } + + private boolean isPotentialMatch(String path, String[] pattDirs) { + if (!this.trimTokens) { + int pos = 0; + for (String pattDir : pattDirs) { + int skipped = skipSeparator(path, pos, this.pathSeparator); + pos += skipped; + skipped = skipSegment(path, pos, pattDir); + if (skipped < pattDir.length()) { + return (skipped > 0 || (pattDir.length() > 0 && isWildcardChar(pattDir.charAt(0)))); + } + pos += skipped; + } + } + return true; + } + + private int skipSegment(String path, int pos, String prefix) { + int skipped = 0; + for (int i = 0; i < prefix.length(); i++) { + char c = prefix.charAt(i); + if (isWildcardChar(c)) { + return skipped; + } + int currPos = pos + skipped; + if (currPos >= path.length()) { + return 0; + } + if (c == path.charAt(currPos)) { + skipped++; + } + } + return skipped; + } + + private int skipSeparator(String path, int pos, String separator) { + int skipped = 0; + while (path.startsWith(separator, pos + skipped)) { + skipped += separator.length(); + } + return skipped; + } + + private boolean isWildcardChar(char c) { + for (char candidate : WILDCARD_CHARS) { + if (c == candidate) { + return true; + } + } + return false; + } + + /** + * Tokenize the given path pattern into parts, based on this matcher's settings. + *

    Performs caching based on {@link #setCachePatterns}, delegating to + * {@link #tokenizePath(String)} for the actual tokenization algorithm. + * + * @param pattern the pattern to tokenize + * @return the tokenized pattern parts + */ + protected String[] tokenizePattern(String pattern) { + String[] tokenized = null; + Boolean cachePatterns = this.cachePatterns; + if (cachePatterns == null || cachePatterns.booleanValue()) { + tokenized = this.tokenizedPatternCache.get(pattern); + } + if (tokenized == null) { + tokenized = tokenizePath(pattern); + if (cachePatterns == null && this.tokenizedPatternCache.size() >= CACHE_TURNOFF_THRESHOLD) { + // Try to adapt to the runtime situation that we're encountering: + // There are obviously too many different patterns coming in here... + // So let's turn off the cache since the patterns are unlikely to be reoccurring. + deactivatePatternCache(); + return tokenized; + } + if (cachePatterns == null || cachePatterns.booleanValue()) { + this.tokenizedPatternCache.put(pattern, tokenized); + } + } + return tokenized; + } + + /** + * Tokenize the given path String into parts, based on this matcher's settings. + * + * @param path the path to tokenize + * @return the tokenized path parts + */ + protected String[] tokenizePath(String path) { + return StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); + } + + /** + * one.Test whether or not a string matches against a pattern. + * + * @param pattern the pattern to match against (never {@code null}) + * @param str the String which must be matched against the pattern (never {@code null}) + * @return {@code true} if the string matches against the pattern, or {@code false} otherwise + */ + private boolean matchStrings(String pattern, String str, Map uriTemplateVariables) { + return getStringMatcher(pattern).matchStrings(str, uriTemplateVariables); + } + + /** + * Build or retrieve an {@link AntPathStringMatcher} for the given pattern. + *

    The default implementation checks this AntPathMatcher's internal cache + * (see {@link #setCachePatterns}), creating a new AntPathStringMatcher instance + * if no cached copy is found. + *

    When encountering too many patterns to cache at runtime (the threshold is 65536), + * it turns the default cache off, assuming that arbitrary permutations of patterns + * are coming in, with little chance for encountering a recurring pattern. + *

    This method may be overridden to implement a custom cache strategy. + * + * @param pattern the pattern to match against (never {@code null}) + * @return a corresponding AntPathStringMatcher (never {@code null}) + * @see #setCachePatterns + */ + protected AntPathStringMatcher getStringMatcher(String pattern) { + AntPathStringMatcher matcher = null; + Boolean cachePatterns = this.cachePatterns; + if (cachePatterns == null || cachePatterns.booleanValue()) { + matcher = this.stringMatcherCache.get(pattern); + } + if (matcher == null) { + matcher = new AntPathStringMatcher(pattern, this.caseSensitive); + if (cachePatterns == null && this.stringMatcherCache.size() >= CACHE_TURNOFF_THRESHOLD) { + // Try to adapt to the runtime situation that we're encountering: + // There are obviously too many different patterns coming in here... + // So let's turn off the cache since the patterns are unlikely to be reoccurring. + deactivatePatternCache(); + return matcher; + } + if (cachePatterns == null || cachePatterns.booleanValue()) { + this.stringMatcherCache.put(pattern, matcher); + } + } + return matcher; + } + + /** + * Tests whether or not a string matches against a pattern via a {@link Pattern}. + *

    The pattern may contain special characters: '*' means zero or more characters; '?' means one and + * only one character; '{' and '}' indicate a URI template pattern. For example /users/{user}. + */ + protected static class AntPathStringMatcher { + + private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*|\\{((?:\\{[^/]+?\\}|[^/{}]|\\\\[{}])+?)\\}"); + + private static final String DEFAULT_VARIABLE_PATTERN = "(.*)"; + + private final Pattern pattern; + + private final List variableNames = new LinkedList(); + + public AntPathStringMatcher(String pattern) { + this(pattern, true); + } + + public AntPathStringMatcher(String pattern, boolean caseSensitive) { + StringBuilder patternBuilder = new StringBuilder(); + Matcher matcher = GLOB_PATTERN.matcher(pattern); + int end = 0; + while (matcher.find()) { + patternBuilder.append(quote(pattern, end, matcher.start())); + String match = matcher.group(); + if ("?".equals(match)) { + patternBuilder.append('.'); + } else if ("*".equals(match)) { + patternBuilder.append(".*"); + } else if (match.startsWith("{") && match.endsWith("}")) { + int colonIdx = match.indexOf(':'); + if (colonIdx == -1) { + patternBuilder.append(DEFAULT_VARIABLE_PATTERN); + this.variableNames.add(matcher.group(1)); + } else { + String variablePattern = match.substring(colonIdx + 1, match.length() - 1); + patternBuilder.append('('); + patternBuilder.append(variablePattern); + patternBuilder.append(')'); + String variableName = match.substring(1, colonIdx); + this.variableNames.add(variableName); + } + } + end = matcher.end(); + } + patternBuilder.append(quote(pattern, end, pattern.length())); + this.pattern = (caseSensitive ? Pattern.compile(patternBuilder.toString()) : + Pattern.compile(patternBuilder.toString(), Pattern.CASE_INSENSITIVE)); + } + + private String quote(String s, int start, int end) { + if (start == end) { + return ""; + } + return Pattern.quote(s.substring(start, end)); + } + + /** + * Main entry point. + * + * @return {@code true} if the string matches against the pattern, or {@code false} otherwise. + */ + public boolean matchStrings(String str, Map uriTemplateVariables) { + Matcher matcher = this.pattern.matcher(str); + if (matcher.matches()) { + if (uriTemplateVariables != null) { + // SPR-8455 + if (this.variableNames.size() != matcher.groupCount()) { + throw new IllegalArgumentException("The number of capturing groups in the pattern segment " + + this.pattern + " does not match the number of URI template variables it defines, " + + "which can occur if capturing groups are used in a URI template regex. " + + "Use non-capturing groups instead."); + } + for (int i = 1; i <= matcher.groupCount(); i++) { + String name = this.variableNames.get(i - 1); + String value = matcher.group(i); + uriTemplateVariables.put(name, value); + } + } + return true; + } else { + return false; + } + } + } + + + /** + * The default {@link Comparator} implementation returned by + * {@link #getPatternComparator(String)}. + *

    In order, the most "generic" pattern is determined by the following: + *

      + *
    • if it's null or a capture all pattern (i.e. it is equal to "/**")
    • + *
    • if the other pattern is an actual match
    • + *
    • if it's a catch-all pattern (i.e. it ends with "**"
    • + *
    • if it's got more "*" than the other pattern
    • + *
    • if it's got more "{foo}" than the other pattern
    • + *
    • if it's shorter than the other pattern
    • + *
    + */ + protected static class AntPatternComparator implements Comparator { + + private final String path; + + public AntPatternComparator(String path) { + this.path = path; + } + + /** + * Compare two patterns to determine which should match first, i.e. which + * is the most specific regarding the current path. + * + * @return a negative integer, zero, or a positive integer as pattern1 is + * more specific, equally specific, or less specific than pattern2. + */ + @Override + public int compare(String pattern1, String pattern2) { + PatternInfo info1 = new PatternInfo(pattern1); + PatternInfo info2 = new PatternInfo(pattern2); + + if (info1.isLeastSpecific() && info2.isLeastSpecific()) { + return 0; + } else if (info1.isLeastSpecific()) { + return 1; + } else if (info2.isLeastSpecific()) { + return -1; + } + + boolean pattern1EqualsPath = pattern1.equals(path); + boolean pattern2EqualsPath = pattern2.equals(path); + if (pattern1EqualsPath && pattern2EqualsPath) { + return 0; + } else if (pattern1EqualsPath) { + return -1; + } else if (pattern2EqualsPath) { + return 1; + } + + if (info1.isPrefixPattern() && info2.getDoubleWildcards() == 0) { + return 1; + } else if (info2.isPrefixPattern() && info1.getDoubleWildcards() == 0) { + return -1; + } + + if (info1.getTotalCount() != info2.getTotalCount()) { + return info1.getTotalCount() - info2.getTotalCount(); + } + + if (info1.getLength() != info2.getLength()) { + return info2.getLength() - info1.getLength(); + } + + if (info1.getSingleWildcards() < info2.getSingleWildcards()) { + return -1; + } else if (info2.getSingleWildcards() < info1.getSingleWildcards()) { + return 1; + } + + if (info1.getUriVars() < info2.getUriVars()) { + return -1; + } else if (info2.getUriVars() < info1.getUriVars()) { + return 1; + } + + return 0; + } + + + /** + * Value class that holds information about the pattern, e.g. number of + * occurrences of "*", "**", and "{" pattern elements. + */ + private static class PatternInfo { + + private final String pattern; + + private int uriVars; + + private int singleWildcards; + + private int doubleWildcards; + + private boolean catchAllPattern; + + private boolean prefixPattern; + + private Integer length; + + public PatternInfo(String pattern) { + this.pattern = pattern; + if (this.pattern != null) { + initCounters(); + this.catchAllPattern = this.pattern.equals("/**"); + this.prefixPattern = !this.catchAllPattern && this.pattern.endsWith("/**"); + } + if (this.uriVars == 0) { + this.length = (this.pattern != null ? this.pattern.length() : 0); + } + } + + protected void initCounters() { + int pos = 0; + while (pos < this.pattern.length()) { + if (this.pattern.charAt(pos) == '{') { + this.uriVars++; + pos++; + } else if (this.pattern.charAt(pos) == '*') { + if (pos + 1 < this.pattern.length() && this.pattern.charAt(pos + 1) == '*') { + this.doubleWildcards++; + pos += 2; + } else if (pos > 0 && !this.pattern.substring(pos - 1).equals(".*")) { + this.singleWildcards++; + pos++; + } else { + pos++; + } + } else { + pos++; + } + } + } + + public int getUriVars() { + return this.uriVars; + } + + public int getSingleWildcards() { + return this.singleWildcards; + } + + public int getDoubleWildcards() { + return this.doubleWildcards; + } + + public boolean isLeastSpecific() { + return (this.pattern == null || this.catchAllPattern); + } + + public boolean isPrefixPattern() { + return this.prefixPattern; + } + + public int getTotalCount() { + return this.uriVars + this.singleWildcards + (2 * this.doubleWildcards); + } + + /** + * Returns the length of the given pattern, where template variables are considered to be 1 long. + */ + public int getLength() { + if (this.length == null) { + this.length = VARIABLE_PATTERN.matcher(this.pattern).replaceAll("#").length(); + } + return this.length; + } + } + } + +} diff --git a/src/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java b/src/main/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java similarity index 93% rename from src/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java rename to src/main/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java index 707b551..48a2a33 100644 --- a/src/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java +++ b/src/main/java/com/zhaow/restful/common/spring/RequestMappingAnnotationHelper.java @@ -18,12 +18,13 @@ public class RequestMappingAnnotationHelper implements RestSupportedAnnotationHe /** * 过滤所有注解 + * * @param psiClass * @return */ public static List getRequestPaths(PsiClass psiClass) { PsiAnnotation[] annotations = psiClass.getModifierList().getAnnotations(); - if(annotations == null) return null; + if (annotations == null) return null; PsiAnnotation requestMappingAnnotation = null; List list = new ArrayList<>(); @@ -38,7 +39,7 @@ public static List getRequestPaths(PsiClass psiClass) { if (requestMappingAnnotation != null) { List requestMappings = getRequestMappings(requestMappingAnnotation, ""); - if (requestMappings.size()>0) { + if (requestMappings.size() > 0) { list.addAll(requestMappings); } } else { @@ -57,7 +58,7 @@ public static List getRequestPaths(PsiClass psiClass) { public static String[] getRequestMappingValues(PsiClass psiClass) { PsiAnnotation[] annotations = psiClass.getModifierList().getAnnotations(); - if(annotations == null) return null; + if (annotations == null) return null; for (PsiAnnotation annotation : annotations) { if (annotation.getQualifiedName().equals(SpringRequestMethodAnnotation.REQUEST_MAPPING.getQualifiedName())) { @@ -82,13 +83,13 @@ private static List getRequestMappings(PsiAnnotation annotation, St SpringRequestMethodAnnotation requestAnnotation = SpringRequestMethodAnnotation.getByQualifiedName(annotation.getQualifiedName()); - if (requestAnnotation==null) { + if (requestAnnotation == null) { return new ArrayList<>(); } - List methodList ; + List methodList; if (requestAnnotation.methodName() != null) { - methodList = Arrays.asList(requestAnnotation.methodName()) ; + methodList = Arrays.asList(requestAnnotation.methodName()); } else { // RequestMapping 如果没有指定具体method,不写的话,默认支持所有HTTP请求方法 methodList = PsiAnnotationHelper.getAnnotationAttributeValues(annotation, "method"); } @@ -125,13 +126,14 @@ private static List getRequestMappings(PsiAnnotation annotation, St /** * 过滤所有注解 + * * @param psiMethod * @return */ public static RequestPath[] getRequestPaths(PsiMethod psiMethod) { PsiAnnotation[] annotations = psiMethod.getModifierList().getAnnotations(); - if(annotations == null) return null; + if (annotations == null) return null; List list = new ArrayList<>(); for (PsiAnnotation annotation : annotations) { @@ -142,7 +144,7 @@ public static RequestPath[] getRequestPaths(PsiMethod psiMethod) { // String defaultValue = psiMethod.getName(); String defaultValue = "/"; List requestMappings = getRequestMappings(annotation, defaultValue); - if (requestMappings.size()>0) { + if (requestMappings.size() > 0) { list.addAll(requestMappings); } } @@ -160,19 +162,19 @@ private static String getRequestMappingValue(PsiAnnotation annotation) { // if(psiAnnotationMemberValue.) if (StringUtils.isEmpty(value)) - value = PsiAnnotationHelper.getAnnotationAttributeValue(annotation,"path"); + value = PsiAnnotationHelper.getAnnotationAttributeValue(annotation, "path"); return value; } public static String[] getRequestMappingValues(PsiAnnotation annotation) { - String[] values ; + String[] values; //一个value class com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl //多个value class com.intellij.psi.impl.source.tree.java.PsiArrayInitializerMemberValueImpl PsiAnnotationMemberValue attributeValue = annotation.findDeclaredAttributeValue("value"); if (attributeValue instanceof PsiLiteralExpression) { - return new String[]{((PsiLiteralExpression) attributeValue).getValue().toString()}; + return new String[]{((PsiLiteralExpression) attributeValue).getValue().toString()}; } if (attributeValue instanceof PsiArrayInitializerMemberValue) { PsiAnnotationMemberValue[] initializers = ((PsiArrayInitializerMemberValue) attributeValue).getInitializers(); @@ -183,7 +185,7 @@ public static String[] getRequestMappingValues(PsiAnnotation annotation) { } for (int i = 0; i < initializers.length; i++) { - values[i] = ((PsiLiteralExpression)(initializers[i])).getValue().toString(); + values[i] = ((PsiLiteralExpression) (initializers[i])).getValue().toString(); } } @@ -221,10 +223,10 @@ public static String getOneRequestMappingPath(PsiMethod psiMethod) { } String mappingPath; - if(requestAnnotation != null){ + if (requestAnnotation != null) { PsiAnnotation annotation = psiMethod.getModifierList().findAnnotation(requestAnnotation.getQualifiedName()); mappingPath = RequestMappingAnnotationHelper.getRequestMappingValue(annotation); - }else { + } else { String methodName = psiMethod.getName(); mappingPath = StringUtils.uncapitalize(methodName); } @@ -233,5 +235,4 @@ public static String getOneRequestMappingPath(PsiMethod psiMethod) { } - } \ No newline at end of file diff --git a/src/main/java/com/zhaow/restful/common/spring/StringUtils.java b/src/main/java/com/zhaow/restful/common/spring/StringUtils.java new file mode 100644 index 0000000..24e4c11 --- /dev/null +++ b/src/main/java/com/zhaow/restful/common/spring/StringUtils.java @@ -0,0 +1,125 @@ +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.zhaow.restful.common.spring; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.StringTokenizer; + +/** + * Miscellaneous {@link String} utility methods. + * + *

    Mainly for internal use within the framework; consider + * Apache's Commons Lang + * for a more comprehensive suite of {@code String} utilities. + * + *

    This class delivers some simple functionality that should really be + * provided by the core Java {@link String} and {@link StringBuilder} + * classes. It also provides easy-to-use methods to convert between + * delimited strings, such as CSV strings, and collections and arrays. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Keith Donald + * @author Rob Harrop + * @author Rick Evans + * @author Arjen Poutsma + * @author Sam Brannen + * @author Brian Clozel + * @since 16 April 2001 + */ +public abstract class StringUtils { + + /** + * Check that the given {@code CharSequence} is neither {@code null} nor + * of length 0. + *

    Note: this method returns {@code true} for a {@code CharSequence} + * that purely consists of whitespace. + *

    +     * StringUtils.hasLength(null) = false
    +     * StringUtils.hasLength("") = false
    +     * StringUtils.hasLength(" ") = true
    +     * StringUtils.hasLength("Hello") = true
    +     * 
    + * + * @param str the {@code CharSequence} to check (may be {@code null}) + * @return {@code true} if the {@code CharSequence} is not {@code null} and has length + * @see #hasText(String) + */ + public static boolean hasLength(CharSequence str) { + return (str != null && str.length() > 0); + } + + /** + * Copy the given {@code Collection} into a {@code String} array. + *

    The {@code Collection} must contain {@code String} elements only. + * + * @param collection the {@code Collection} to copy + * @return the {@code String} array ({@code null} if the supplied + * {@code Collection} was {@code null}) + */ + public static String[] toStringArray(Collection collection) { + if (collection == null) { + return null; + } + + return collection.toArray(new String[collection.size()]); + } + + /** + * Tokenize the given {@code String} into a {@code String} array via a + * {@link StringTokenizer}. + *

    The given {@code delimiters} string can consist of any number of + * delimiter characters. Each of those characters can be used to separate + * tokens. A delimiter is always a single character; for multi-character + * delimiters, consider using {@link #delimitedListToStringArray}. + * + * @param str the {@code String} to tokenize + * @param delimiters the delimiter characters, assembled as a {@code String} + * (each of the characters is individually considered as a delimiter) + * @param trimTokens trim the tokens via {@link String#trim()} + * @param ignoreEmptyTokens omit empty tokens from the result array + * (only applies to tokens that are empty after trimming; StringTokenizer + * will not consider subsequent delimiters as token in the first place). + * @return an array of the tokens ({@code null} if the input {@code String} + * was {@code null}) + * @see StringTokenizer + * @see String#trim() + * @see #delimitedListToStringArray + */ + public static String[] tokenizeToStringArray( + String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { + + if (str == null) { + return null; + } + + StringTokenizer st = new StringTokenizer(str, delimiters); + List tokens = new ArrayList(); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (trimTokens) { + token = token.trim(); + } + if (!ignoreEmptyTokens || token.length() > 0) { + tokens.add(token); + } + } + return toStringArray(tokens); + } +} diff --git a/src/java/com/zhaow/restful/highlight/JTextAreaHighlight.java b/src/main/java/com/zhaow/restful/highlight/JTextAreaHighlight.java similarity index 96% rename from src/java/com/zhaow/restful/highlight/JTextAreaHighlight.java rename to src/main/java/com/zhaow/restful/highlight/JTextAreaHighlight.java index 45c4fe2..e385eb3 100644 --- a/src/java/com/zhaow/restful/highlight/JTextAreaHighlight.java +++ b/src/main/java/com/zhaow/restful/highlight/JTextAreaHighlight.java @@ -26,7 +26,7 @@ public static void highlightTextAreaData(JTextArea jTextArea) { return; } - int start=0; + int start = 0; String[] lines = text.split("\n"); for (String line : lines) { // String[] split = line.split(":"); @@ -40,7 +40,7 @@ public static void highlightTextAreaData(JTextArea jTextArea) { try { highLighter.addHighlight(start, end, highlightPainter); - start += line.substring(index).length()+1; + start += line.substring(index).length() + 1; } catch (BadLocationException e) { e.printStackTrace(); @@ -78,7 +78,5 @@ public static void highlightTextAreaData(JTextArea jTextArea) { */ - - } } diff --git a/src/java/com/zhaow/restful/method/HttpMethod.java b/src/main/java/com/zhaow/restful/method/HttpMethod.java similarity index 91% rename from src/java/com/zhaow/restful/method/HttpMethod.java rename to src/main/java/com/zhaow/restful/method/HttpMethod.java index 84ac64c..424bf60 100644 --- a/src/java/com/zhaow/restful/method/HttpMethod.java +++ b/src/main/java/com/zhaow/restful/method/HttpMethod.java @@ -4,7 +4,7 @@ import java.util.Map; public enum HttpMethod { - GET, POST, PUT, DELETE, PATCH,HEAD,OPTIONS,TRACE,CONNECT; + GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, TRACE, CONNECT; private static final Map methodMap = new HashMap(8); diff --git a/src/java/com/zhaow/restful/method/Parameter.java b/src/main/java/com/zhaow/restful/method/Parameter.java similarity index 92% rename from src/java/com/zhaow/restful/method/Parameter.java rename to src/main/java/com/zhaow/restful/method/Parameter.java index e0e0d5a..499c07c 100644 --- a/src/java/com/zhaow/restful/method/Parameter.java +++ b/src/main/java/com/zhaow/restful/method/Parameter.java @@ -11,7 +11,8 @@ public class Parameter { // MethodParameter private boolean required = false; private boolean requestBodyFound = false; - public Parameter() { } + public Parameter() { + } public Parameter(String paramType, String paramName) { this.paramType = paramType; @@ -24,17 +25,16 @@ public Parameter(String paramType, String paramName, String defaultValue) { this.defaultValue = defaultValue; } - /* public Parameter required() { - this.required = true; - return this; - } -*/ + /* public Parameter required() { + this.required = true; + return this; + } + */ public String getParamType() { return paramType; } - public void setParamType(String paramType) { this.paramType = paramType; } @@ -78,7 +78,7 @@ public Parameter requestBodyFound(boolean requestBodyFound) { } public String getShortTypeName() { - //todo : List + //todo : List String shortName = paramType.substring(paramType.lastIndexOf(".") + 1, paramType.length()); return shortName; diff --git a/src/java/com/zhaow/restful/method/RequestPath.java b/src/main/java/com/zhaow/restful/method/RequestPath.java similarity index 94% rename from src/java/com/zhaow/restful/method/RequestPath.java rename to src/main/java/com/zhaow/restful/method/RequestPath.java index a212e20..399fdf7 100644 --- a/src/java/com/zhaow/restful/method/RequestPath.java +++ b/src/main/java/com/zhaow/restful/method/RequestPath.java @@ -33,7 +33,7 @@ public void concat(RequestPath classRequestPath) { if (!classUri.endsWith("/")) classUri = classUri.concat("/"); if (this.path.startsWith("/")) methodUri = this.path.substring(1, this.path.length()); - this.path = classUri.concat(methodUri) ; + this.path = classUri.concat(methodUri); // method } } diff --git a/src/java/com/zhaow/restful/method/action/GenerateFullUrlAction.java b/src/main/java/com/zhaow/restful/method/action/GenerateFullUrlAction.java similarity index 100% rename from src/java/com/zhaow/restful/method/action/GenerateFullUrlAction.java rename to src/main/java/com/zhaow/restful/method/action/GenerateFullUrlAction.java diff --git a/src/java/com/zhaow/restful/method/action/GenerateQueryParamAction.java b/src/main/java/com/zhaow/restful/method/action/GenerateQueryParamAction.java similarity index 100% rename from src/java/com/zhaow/restful/method/action/GenerateQueryParamAction.java rename to src/main/java/com/zhaow/restful/method/action/GenerateQueryParamAction.java diff --git a/src/java/com/zhaow/restful/method/action/GenerateQueryParamJsonAction.java b/src/main/java/com/zhaow/restful/method/action/GenerateQueryParamJsonAction.java similarity index 100% rename from src/java/com/zhaow/restful/method/action/GenerateQueryParamJsonAction.java rename to src/main/java/com/zhaow/restful/method/action/GenerateQueryParamJsonAction.java diff --git a/src/java/com/zhaow/restful/method/action/GenerateUrlAction.java b/src/main/java/com/zhaow/restful/method/action/GenerateUrlAction.java similarity index 93% rename from src/java/com/zhaow/restful/method/action/GenerateUrlAction.java rename to src/main/java/com/zhaow/restful/method/action/GenerateUrlAction.java index 15d89df..e962405 100644 --- a/src/java/com/zhaow/restful/method/action/GenerateUrlAction.java +++ b/src/main/java/com/zhaow/restful/method/action/GenerateUrlAction.java @@ -27,7 +27,7 @@ * todo: 没考虑RequestMapping 多个值的情况 */ public class GenerateUrlAction /*extends RestfulMethodSpringSupportedAction*/ extends AbstractBaseAction { - Editor myEditor ; + Editor myEditor; @Override public void actionPerformed(AnActionEvent e) { @@ -53,7 +53,7 @@ private boolean isJaxrsRestMethod(PsiMethod psiMethod) { for (PsiAnnotation annotation : annotations) { boolean match = Arrays.stream(JaxrsHttpMethodAnnotation.values()).map(sra -> sra.getQualifiedName()).anyMatch(name -> name.equals(annotation.getQualifiedName())); - if(match) return match; + if (match) return match; } return false; @@ -61,6 +61,7 @@ private boolean isJaxrsRestMethod(PsiMethod psiMethod) { /** * spring rest 方法被选中才触发 + * * @param e */ @Override @@ -69,10 +70,10 @@ public void update(AnActionEvent e) { boolean visible = false; - if(psiElement instanceof PsiMethod){ + if (psiElement instanceof PsiMethod) { PsiMethod psiMethod = (PsiMethod) psiElement; // rest method 或标注了RestController 注解 - visible = (isRestController(psiMethod.getContainingClass()) || isRestfulMethod(psiMethod) ); + visible = (isRestController(psiMethod.getContainingClass()) || isRestfulMethod(psiMethod)); } setActionPresentationVisible(e, visible); @@ -87,7 +88,7 @@ private boolean isRestController(PsiClass containingClass) { return modifierList.findAnnotation(SpringControllerAnnotation.REST_CONTROLLER.getQualifiedName()) != null || modifierList.findAnnotation(SpringControllerAnnotation.CONTROLLER.getQualifiedName()) != null || - modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null ; + modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null; } private boolean isRestfulMethod(PsiMethod psiMethod) { @@ -95,12 +96,12 @@ private boolean isRestfulMethod(PsiMethod psiMethod) { for (PsiAnnotation annotation : annotations) { boolean match = Arrays.stream(SpringRequestMethodAnnotation.values()).map(sra -> sra.getQualifiedName()).anyMatch(name -> name.equals(annotation.getQualifiedName())); - if(match) return match; + if (match) return match; } for (PsiAnnotation annotation : annotations) { boolean match = Arrays.stream(JaxrsHttpMethodAnnotation.values()).map(sra -> sra.getQualifiedName()).anyMatch(name -> name.equals(annotation.getQualifiedName())); - if(match) return match; + if (match) return match; } return false; diff --git a/src/java/com/zhaow/restful/method/action/ModuleHelper.java b/src/main/java/com/zhaow/restful/method/action/ModuleHelper.java similarity index 94% rename from src/java/com/zhaow/restful/method/action/ModuleHelper.java rename to src/main/java/com/zhaow/restful/method/action/ModuleHelper.java index aff5910..a931f3e 100644 --- a/src/java/com/zhaow/restful/method/action/ModuleHelper.java +++ b/src/main/java/com/zhaow/restful/method/action/ModuleHelper.java @@ -13,7 +13,7 @@ public class ModuleHelper { private static final String SCHEME = "http://"; //PROTOCOL private static final String HOST = "localhost"; private static final String PORT = "8080"; // int - public static String DEFAULT_URI = "http://localhost"+":"+PORT; + public static String DEFAULT_URI = "http://localhost" + ":" + PORT; // private static final String PATH = "http://localhost"+":"+PORT; // PATH or FILE public static String getAUTHORITY() { diff --git a/src/java/com/zhaow/restful/method/action/PropertiesHandler.java b/src/main/java/com/zhaow/restful/method/action/PropertiesHandler.java similarity index 91% rename from src/java/com/zhaow/restful/method/action/PropertiesHandler.java rename to src/main/java/com/zhaow/restful/method/action/PropertiesHandler.java index bd240c7..969c579 100644 --- a/src/java/com/zhaow/restful/method/action/PropertiesHandler.java +++ b/src/main/java/com/zhaow/restful/method/action/PropertiesHandler.java @@ -33,8 +33,9 @@ public String[] getFileExtensions() { //优先级 public String[] getConfigFiles() { // 优先级 return new String[]{"application", "bootstrap"}; } - public List CONFIG_FILES = Arrays.asList("application", "bootstrap"); - public List FILE_EXTENSIONS = Arrays.asList("properties", "yml"); + + public List CONFIG_FILES = Arrays.asList("application", "bootstrap"); + public List FILE_EXTENSIONS = Arrays.asList("properties", "yml"); String SPRING_PROFILE = "spring.profiles.active"; @@ -84,7 +85,6 @@ public String getProperty(String propertyKey) { } - /* try find spring.profiles.active value */ private String findProfilePropertyValue() { String activeProfile = findPropertyValue(SPRING_PROFILE, null); @@ -92,33 +92,33 @@ private String findProfilePropertyValue() { } /* 暂时不考虑路径问题,默认找到的第一文件 */ - private String findPropertyValue(String propertyKey,String activeProfile) { + private String findPropertyValue(String propertyKey, String activeProfile) { String value = null; - String profile = activeProfile != null ? "-"+ activeProfile : ""; + String profile = activeProfile != null ? "-" + activeProfile : ""; // for (String conf : getConfigFiles()) { for (String ext : getFileExtensions()) { // load spring config file - String configFile = conf + profile + "." + ext; + String configFile = conf + profile + "." + ext; if (ext.equals("properties")) { Properties properties = loadProertiesFromConfigFile(configFile); if (properties != null) { Object valueObj = properties.getProperty(propertyKey); if (valueObj != null) { - value = cleanPlaceholderIfExist((String)valueObj); + value = cleanPlaceholderIfExist((String) valueObj); return value; } } - } else if(ext.equals("yml") || ext.equals("yaml")) { + } else if (ext.equals("yml") || ext.equals("yaml")) { Map propertiesMap = getPropertiesMapFromYamlFile(configFile); if (propertiesMap != null) { Object valueObj = propertiesMap.get(propertyKey); if (valueObj == null) return null; if (valueObj instanceof String) { - value = cleanPlaceholderIfExist((String)valueObj); - }else{ + value = cleanPlaceholderIfExist((String) valueObj); + } else { value = valueObj.toString(); } return value; @@ -228,9 +228,9 @@ protected final Map getFlattenedMap(Map source) private void buildFlattenedMap(Map result, Map source, String path) { Iterator iterator = source.entrySet().iterator(); - while(true) { - while(iterator.hasNext()) { - Map.Entry entry = (Map.Entry)iterator.next(); + while (true) { + while (iterator.hasNext()) { + Map.Entry entry = (Map.Entry) iterator.next(); String key = entry.getKey(); if (StringUtils.isNotBlank(path)) { if (key.startsWith("[")) { @@ -244,14 +244,14 @@ private void buildFlattenedMap(Map result, Map s if (value instanceof String) { result.put(key, value); } else if (value instanceof Map) { - Map map = (Map)value; + Map map = (Map) value; this.buildFlattenedMap(result, map, key); } else if (value instanceof Collection) { - Collection collection = (Collection)value; + Collection collection = (Collection) value; int count = 0; Iterator var10 = collection.iterator(); - while(var10.hasNext()) { + while (var10.hasNext()) { Object object = var10.next(); this.buildFlattenedMap(result, Collections.singletonMap("[" + count++ + "]", object), key); } diff --git a/src/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java b/src/main/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java similarity index 89% rename from src/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java rename to src/main/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java index f064462..59b784a 100644 --- a/src/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java +++ b/src/main/java/com/zhaow/restful/method/action/SpringAnnotatedMethodAction.java @@ -21,6 +21,7 @@ public abstract class SpringAnnotatedMethodAction extends AbstractBaseAction { /** * spring rest 方法被选中才触发 + * * @param e */ @Override @@ -29,10 +30,10 @@ public void update(AnActionEvent e) { boolean visible = false; - if(psiElement instanceof PsiMethod){ + if (psiElement instanceof PsiMethod) { PsiMethod psiMethod = (PsiMethod) psiElement; // rest method 或标注了RestController 注解 - visible = (isRestController(psiMethod.getContainingClass()) || isRestfulMethod(psiMethod) ); + visible = (isRestController(psiMethod.getContainingClass()) || isRestfulMethod(psiMethod)); } if (psiElement instanceof KtNamedFunction) { KtNamedFunction ktNamedFunction = (KtNamedFunction) psiElement; @@ -42,7 +43,7 @@ public void update(AnActionEvent e) { List psiMethods = LightClassUtilsKt.toLightMethods(ktNamedFunction); - visible = (isRestController(ktLightClass) || isRestfulMethod(psiMethods.get(0)) ); + visible = (isRestController(ktLightClass) || isRestfulMethod(psiMethods.get(0))); } } @@ -59,7 +60,7 @@ private boolean isRestController(PsiClass containingClass) { return modifierList.findAnnotation(SpringControllerAnnotation.REST_CONTROLLER.getQualifiedName()) != null || modifierList.findAnnotation(SpringControllerAnnotation.CONTROLLER.getQualifiedName()) != null /*|| - modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null*/ ; + modifierList.findAnnotation(JaxrsRequestAnnotation.PATH.getQualifiedName()) != null*/; } private boolean isRestfulMethod(PsiMethod psiMethod) { @@ -67,12 +68,11 @@ private boolean isRestfulMethod(PsiMethod psiMethod) { for (PsiAnnotation annotation : annotations) { boolean match = Arrays.stream(SpringRequestMethodAnnotation.values()).map(sra -> sra.getQualifiedName()).anyMatch(name -> name.equals(annotation.getQualifiedName())); - if(match) return match; + if (match) return match; } return false; } - } diff --git a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java similarity index 94% rename from src/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java rename to src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java index 2dfe3d7..b16a2a5 100644 --- a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java +++ b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingAction.java @@ -2,7 +2,10 @@ import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.actions.GotoActionBase; -import com.intellij.ide.util.gotoByName.*; +import com.intellij.ide.util.gotoByName.ChooseByNameFilter; +import com.intellij.ide.util.gotoByName.ChooseByNameItemProvider; +import com.intellij.ide.util.gotoByName.ChooseByNameModel; +import com.intellij.ide.util.gotoByName.ChooseByNamePopup; import com.intellij.navigation.ChooseByNameContributor; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; @@ -63,12 +66,12 @@ public void elementChosen(ChooseByNamePopup chooseByNamePopup, Object element) { // this.showNavigationPopup(e, model, callback, false); GotoRequestMappingProvider provider = new GotoRequestMappingProvider(getPsiContext(e)); - showNavigationPopup(e, model, callback, "Request Mapping Url matching pattern", true, true, (ChooseByNameItemProvider)provider); + showNavigationPopup(e, model, callback, "Request Mapping Url matching pattern", true, true, (ChooseByNameItemProvider) provider); // showNavigationPopup(callback,"Request Mapping Url matching pattern",); } -// TODO IDEA 2018 删了? + // TODO IDEA 2018 删了? // @Override protected void showNavigationPopup(AnActionEvent e, ChooseByNameModel model, @@ -105,7 +108,7 @@ private String tryFindCopiedURL() { if (contents.startsWith("http")) { if (contents.length() <= 120) { return contents; - }else { + } else { return contents.substring(0, 120); } } diff --git a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java similarity index 63% rename from src/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java rename to src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java index a987c13..e8924cf 100644 --- a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java +++ b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingConfiguration.java @@ -15,18 +15,18 @@ */ @State(name = "GotoRequestMappingConfiguration", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) class GotoRequestMappingConfiguration extends ChooseByNameFilterConfiguration { - /** - * Get configuration instance - * - * @param project a project instance - * @return a configuration instance - */ - public static GotoRequestMappingConfiguration getInstance(Project project) { - return ServiceManager.getService(project, GotoRequestMappingConfiguration.class); - } + /** + * Get configuration instance + * + * @param project a project instance + * @return a configuration instance + */ + public static GotoRequestMappingConfiguration getInstance(Project project) { + return ServiceManager.getService(project, GotoRequestMappingConfiguration.class); + } - @Override - protected String nameForElement(HttpMethod type) { - return type.name(); - } + @Override + protected String nameForElement(HttpMethod type) { + return type.name(); + } } diff --git a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingContributor.java b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingContributor.java similarity index 100% rename from src/java/com/zhaow/restful/navigation/action/GotoRequestMappingContributor.java rename to src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingContributor.java diff --git a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java similarity index 89% rename from src/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java rename to src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java index d23f389..9363894 100644 --- a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java +++ b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingModel.java @@ -39,7 +39,7 @@ public synchronized void setFilterItems(Collection filterItems) { protected HttpMethod filterValueFor(NavigationItem item) { if (item instanceof RestServiceItem) { // if (((RestServiceItem) item).getModule().getName().contains("eureka")) { - return ((RestServiceItem) item).getMethod(); + return ((RestServiceItem) item).getMethod(); // } } @@ -72,19 +72,19 @@ public String getPromptText() { @Override public String getNotInMessage() { - return IdeBundle.message("label.no.matches.found.in.project"); + return IdeBundle.message("label.no.matches.found.in.project"); // return "No matched method found"; } @Override public String getNotFoundMessage() { - return IdeBundle.message("label.no.matches.found"); + return IdeBundle.message("label.no.matches.found"); // return "Service path not found"; } @Override public char getCheckBoxMnemonic() { - return SystemInfo.isMac?'P':'n'; + return SystemInfo.isMac ? 'P' : 'n'; } @Override @@ -113,11 +113,13 @@ public String getFullName(Object element) { @Override public String[] getSeparators() { // return new String[]{":","?"}; - return new String[]{"/","?"}; + return new String[]{"/", "?"}; } - /** return null to hide checkbox panel */ + /** + * return null to hide checkbox panel + */ @Nullable @Override public String getCheckBoxName() { @@ -131,12 +133,12 @@ public boolean willOpenEditor() { return true; } -// CustomMatcherModel 接口,Allows to implement custom matcher for matching items from ChooseByName popup + // CustomMatcherModel 接口,Allows to implement custom matcher for matching items from ChooseByName popup // todo: resolve PathVariable annotation @Override public boolean matches(@NotNull String popupItem, @NotNull String userPattern) { String pattern = userPattern; - if(pattern.equals("/")) return true; + if (pattern.equals("/")) return true; // REST风格的参数 @RequestMapping(value="{departmentId}/employees/{employeeId}") PathVariable // REST风格的参数(正则) @RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}") PathVariable @@ -148,14 +150,14 @@ public boolean matches(@NotNull String popupItem, @NotNull String userPattern) { boolean matches = matcher.matches(popupItem); if (!matches) { AntPathMatcher pathMatcher = new AntPathMatcher(); - matches = pathMatcher.match(popupItem,userPattern); + matches = pathMatcher.match(popupItem, userPattern); } return matches; // return true; } -// 没用 ? + // 没用 ? @NotNull @Override public String removeModelSpecificMarkup(@NotNull String pattern) { diff --git a/src/java/com/zhaow/restful/navigation/action/GotoRequestMappingProvider.java b/src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingProvider.java similarity index 100% rename from src/java/com/zhaow/restful/navigation/action/GotoRequestMappingProvider.java rename to src/main/java/com/zhaow/restful/navigation/action/GotoRequestMappingProvider.java diff --git a/src/main/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java b/src/main/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java new file mode 100644 index 0000000..d8cfb22 --- /dev/null +++ b/src/main/java/com/zhaow/restful/navigation/action/RestServiceChooseByNamePopup.java @@ -0,0 +1,97 @@ +/* + * Copyright 2000-2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.zhaow.restful.navigation.action; + +import com.intellij.ide.util.gotoByName.ChooseByNameItemProvider; +import com.intellij.ide.util.gotoByName.ChooseByNameModel; +import com.intellij.ide.util.gotoByName.ChooseByNamePopup; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.util.Key; +import com.intellij.openapi.util.text.StringUtil; +import com.zhaow.utils.ToolkitUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class RestServiceChooseByNamePopup extends ChooseByNamePopup { + public static final Key CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY = new Key<>("ChooseByNamePopup"); + + protected RestServiceChooseByNamePopup(@Nullable Project project, @NotNull ChooseByNameModel model, @NotNull ChooseByNameItemProvider provider, @Nullable ChooseByNamePopup oldPopup, @Nullable String predefinedText, boolean mayRequestOpenInCurrentWindow, int initialIndex) { + super(project, model, provider, oldPopup, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); + } + + public static RestServiceChooseByNamePopup createPopup(final Project project, + @NotNull final ChooseByNameModel model, + @NotNull ChooseByNameItemProvider provider, + @Nullable final String predefinedText, + boolean mayRequestOpenInCurrentWindow, + final int initialIndex) { + if (!StringUtil.isEmptyOrSpaces(predefinedText)) { + return new RestServiceChooseByNamePopup(project, model, provider, null, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); + } + + final RestServiceChooseByNamePopup oldPopup = project == null ? null : project.getUserData(CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY); + if (oldPopup != null) { + oldPopup.close(false); + } + RestServiceChooseByNamePopup newPopup = new RestServiceChooseByNamePopup(project, model, provider, oldPopup, predefinedText, mayRequestOpenInCurrentWindow, initialIndex); + + if (project != null) { + project.putUserData(CHOOSE_BY_NAME_POPUP_IN_PROJECT_KEY, newPopup); + } + return newPopup; + } + + @Override + public String transformPattern(String pattern) { + final ChooseByNameModel model = getModel(); + return getTransformedPattern(pattern, model); + } + + //TODO: resolve PathVariable + public static String getTransformedPattern(String pattern, ChooseByNameModel model) { + if (!(model instanceof GotoRequestMappingModel)) { + return pattern; + } + + pattern = ToolkitUtil.removeRedundancyMarkup(pattern); + ; + return pattern; + } + + + @Nullable + public String getMemberPattern() { + final String enteredText = getTrimmedText(); + final int index = enteredText.lastIndexOf('#'); + if (index == -1) { + return null; + } + + String name = enteredText.substring(index + 1).trim(); + return StringUtil.isEmptyOrSpaces(name) ? null : name; + } + +/* public void repaintList() { + myRepaintQueue.cancelAllUpdates(); + myRepaintQueue.queue(new Update(this) { + @Override + public void run() { + RestServiceChooseByNamePopup.this.repaintListImmediate(); + } + }); + }*/ + +} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/navigation/action/RestServiceItem.java b/src/main/java/com/zhaow/restful/navigation/action/RestServiceItem.java similarity index 84% rename from src/java/com/zhaow/restful/navigation/action/RestServiceItem.java rename to src/main/java/com/zhaow/restful/navigation/action/RestServiceItem.java index fcb041b..d217afc 100644 --- a/src/java/com/zhaow/restful/navigation/action/RestServiceItem.java +++ b/src/main/java/com/zhaow/restful/navigation/action/RestServiceItem.java @@ -9,11 +9,13 @@ import com.zhaow.restful.common.ToolkitIcons; import com.zhaow.restful.method.HttpMethod; import com.zhaow.restful.method.action.ModuleHelper; +import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import org.jetbrains.kotlin.psi.KtClass; import org.jetbrains.kotlin.psi.KtNamedFunction; import javax.swing.*; +import java.util.Arrays; //RequestMappingNavigationItem public class RestServiceItem implements NavigationItem { @@ -33,6 +35,7 @@ public class RestServiceItem implements NavigationItem { private boolean foundRequestBody;*/ private Navigatable navigationElement; + // ((KtClass) ((KtClassBody) psiElement.getParent()).getParent()).getModifierList().getAnnotationEntries().get(0).getText() public RestServiceItem(PsiElement psiElement, String requestMethod, String urlPath) { this.psiElement = psiElement; @@ -98,7 +101,7 @@ public String getPresentableText() { return url; } -// 对应的文件位置显示 + // 对应的文件位置显示 @Nullable @Override public String getLocationString() { @@ -107,12 +110,22 @@ public String getLocationString() { String location = null; if (psiElement instanceof PsiMethod) { - PsiMethod psiMethod = ((PsiMethod) psiElement);; - location = psiMethod.getContainingClass().getName().concat("#").concat(psiMethod.getName()); + PsiMethod psiMethod = ((PsiMethod) psiElement); + //增加项目名称的显示 这样可以区分是哪个项目或者模块里面的地址 + location = StringUtils.join(Arrays.asList( + psiMethod.getProject().getName(), + psiMethod.getContainingClass() != null ? psiMethod.getContainingClass().getName() : "", + psiMethod.getName() + ), "#"); } else if (psiElement instanceof KtNamedFunction) { KtNamedFunction ktNamedFunction = (KtNamedFunction) RestServiceItem.this.psiElement; String className = ((KtClass) psiElement.getParent().getParent()).getName(); - location = className.concat("#").concat(ktNamedFunction.getName()); + //增加项目名称的显示 这样可以区分是哪个项目或者模块里面的地址 + location = StringUtils.join(Arrays.asList( + psiMethod.getProject().getName(), + className, + ktNamedFunction.getName() + ), "#"); } return "(" + location + ")"; @@ -172,7 +185,7 @@ public String getFullUrl() { return urlWithParams; }*/ - public void setModule(Module module) { + public void setModule(Module module) { this.module = module; } diff --git a/src/main/java/com/zhaow/restful/navigator/CopyFullUrlAction.java b/src/main/java/com/zhaow/restful/navigator/CopyFullUrlAction.java new file mode 100644 index 0000000..563b9a9 --- /dev/null +++ b/src/main/java/com/zhaow/restful/navigator/CopyFullUrlAction.java @@ -0,0 +1,49 @@ +package com.zhaow.restful.navigator; + +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.ide.CopyPasteManager; +import com.intellij.openapi.project.DumbAware; +import com.zhaow.restful.navigation.action.RestServiceItem; +import com.zhaow.utils.RestServiceDataKeys; + +import java.awt.datatransfer.StringSelection; +import java.util.List; + +public class CopyFullUrlAction extends AnAction implements DumbAware { + @Override + public void update(AnActionEvent e) { + super.update(e); + Presentation p = e.getPresentation(); + p.setEnabled(isAvailable(e)); + p.setVisible(isVisible(e)); + } + + @Override + public void actionPerformed(AnActionEvent e) { + List serviceItems = RestServiceDataKeys.SERVICE_ITEMS.getData(e.getDataContext()); + StringBuilder sb = new StringBuilder(); + for (RestServiceItem serviceItem : serviceItems) { + if (sb.length() > 1) { + sb.append("\n\n"); + } + sb.append(serviceItem.getFullUrl()); + } + + CopyPasteManager.getInstance().setContents(new StringSelection(sb.toString())); + +// RestServiceProjectsManager.getInstance(getEventProject(e)). + /* CopyPasteManager.getInstance().setContents(...);*/ + } + + /* getSelectRestServiceNodes */ + + protected boolean isAvailable(AnActionEvent e) { + return true; + } + + protected boolean isVisible(AnActionEvent e) { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/com/zhaow/restful/navigator/EditSourceAction.java b/src/main/java/com/zhaow/restful/navigator/EditSourceAction.java new file mode 100644 index 0000000..f6c3d36 --- /dev/null +++ b/src/main/java/com/zhaow/restful/navigator/EditSourceAction.java @@ -0,0 +1,35 @@ +package com.zhaow.restful.navigator; + +import com.intellij.openapi.actionSystem.AnAction; +import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.actionSystem.Presentation; +import com.intellij.openapi.project.DumbAware; +import com.intellij.util.PsiNavigateUtil; +import com.zhaow.restful.navigation.action.RestServiceItem; +import com.zhaow.utils.RestServiceDataKeys; + +import java.util.List; + +public class EditSourceAction extends AnAction implements DumbAware { + @Override + public void update(AnActionEvent e) { + super.update(e); + Presentation p = e.getPresentation(); + p.setVisible(isVisible(e)); + } + + @Override + public void actionPerformed(AnActionEvent e) { + List serviceItems = RestServiceDataKeys.SERVICE_ITEMS.getData(e.getDataContext()); + + for (RestServiceItem serviceItem : serviceItems) { + PsiNavigateUtil.navigate(serviceItem.getPsiElement()); + } + + } + + + protected boolean isVisible(AnActionEvent e) { + return true; + } +} \ No newline at end of file diff --git a/src/java/com/zhaow/restful/navigator/RefreshProjectAction.java b/src/main/java/com/zhaow/restful/navigator/RefreshProjectAction.java similarity index 56% rename from src/java/com/zhaow/restful/navigator/RefreshProjectAction.java rename to src/main/java/com/zhaow/restful/navigator/RefreshProjectAction.java index 99a00cd..e6f1771 100644 --- a/src/java/com/zhaow/restful/navigator/RefreshProjectAction.java +++ b/src/main/java/com/zhaow/restful/navigator/RefreshProjectAction.java @@ -10,26 +10,26 @@ public class RefreshProjectAction extends AnAction { - protected void perform(@NotNull RestServiceProjectsManager manager) { - manager.forceUpdateAllProjects(); - } + protected void perform(@NotNull RestServiceProjectsManager manager) { + manager.forceUpdateAllProjects(); + } @Override public void actionPerformed(AnActionEvent e) { - final Project project = getProject(e.getDataContext()); + final Project project = getProject(e.getDataContext()); /*if(project == null) return ; RestServiceProjectsManager manager = RestServiceProjectsManager.getInstance(project); perform(manager);*/ - RestServicesNavigator servicesNavigator = RestServicesNavigator.getInstance(project); + RestServicesNavigator servicesNavigator = RestServicesNavigator.getInstance(project); - servicesNavigator.initComponent(); - servicesNavigator.scheduleStructureUpdate(); + servicesNavigator.initComponent(); + servicesNavigator.scheduleStructureUpdate(); } - @Nullable - public static Project getProject(DataContext context) { - return CommonDataKeys.PROJECT.getData(context); - } + @Nullable + public static Project getProject(DataContext context) { + return CommonDataKeys.PROJECT.getData(context); + } } diff --git a/src/java/com/zhaow/restful/navigator/RestServiceDetail.form b/src/main/java/com/zhaow/restful/navigator/RestServiceDetail.form similarity index 100% rename from src/java/com/zhaow/restful/navigator/RestServiceDetail.form rename to src/main/java/com/zhaow/restful/navigator/RestServiceDetail.form diff --git a/src/java/com/zhaow/restful/navigator/RestServiceDetail.java b/src/main/java/com/zhaow/restful/navigator/RestServiceDetail.java similarity index 90% rename from src/java/com/zhaow/restful/navigator/RestServiceDetail.java rename to src/main/java/com/zhaow/restful/navigator/RestServiceDetail.java index 112c6cb..54b89df 100644 --- a/src/java/com/zhaow/restful/navigator/RestServiceDetail.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServiceDetail.java @@ -33,7 +33,7 @@ //import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions; //import com.intellij.ui.components.JBPanelWithEmptyText; -public class RestServiceDetail extends JBPanel/*WithEmptyText*/{ +public class RestServiceDetail extends JBPanel/*WithEmptyText*/ { private static RestServiceDetail restServiceDetail; /* JBTextField methodField = new JBTextField("GET"); @@ -149,7 +149,7 @@ private void initUI() { private void bindSendButtonActionListener() { sendButton.addActionListener(e -> { // PluginManagerMain - ProgressManager.getInstance().run(new Task.Backgroundable(null,"Sending Request") { + ProgressManager.getInstance().run(new Task.Backgroundable(null, "Sending Request") { @Override public void run(@NotNull ProgressIndicator indicator) { final Runnable runnable = () -> { @@ -161,7 +161,7 @@ public void run(@NotNull ProgressIndicator indicator) { if (paramMap != null && paramMap.size() > 0) { // set PathVariable value to request URI for (String key : paramMap.keySet()) { - url = url.replaceFirst("\\{("+key+"[\\s\\S]*?)\\}",paramMap.get(key)); + url = url.replaceFirst("\\{(" + key + "[\\s\\S]*?)\\}", paramMap.get(key)); } } @@ -183,7 +183,7 @@ public void run(@NotNull ProgressIndicator indicator) { String response; if (requestBodyTextArea != null && StringUtils.isNotBlank(requestBodyTextArea.getText())) { response = RequestHelper.postRequestBodyWithJson(url, requestBodyTextArea.getText()); - }else{ + } else { response = RequestHelper.request(url, method); } @@ -207,31 +207,33 @@ public void run(@NotNull ProgressIndicator indicator) { } private void bindUrlTextActionListener() { - requestTabbedPane.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - System.out.println(e.getClickCount()); - super.mouseClicked(e); + requestTabbedPane.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + System.out.println(e.getClickCount()); + super.mouseClicked(e); // urlField.moveCaretPosition(urlField.getDocument().getLength()); // urlField.select(0,0); - } + } - @Override - public void mousePressed(MouseEvent e) { - super.mousePressed(e); + @Override + public void mousePressed(MouseEvent e) { + super.mousePressed(e); urlField.selectAll(); - } - @Override - public void mouseEntered(MouseEvent e) { - super.mousePressed(e); - urlField.selectAll(); - } - @Override - public void mouseMoved(MouseEvent e) { - super.mousePressed(e); - urlField.selectAll(); - } - }); + } + + @Override + public void mouseEntered(MouseEvent e) { + super.mousePressed(e); + urlField.selectAll(); + } + + @Override + public void mouseMoved(MouseEvent e) { + super.mousePressed(e); + urlField.selectAll(); + } + }); /*urlField.addMouseListener(new MouseAdapter() { @@ -286,10 +288,9 @@ public void addRequestParamsTab(String requestParams) { } } - if (requestParamsTextArea == null){ + if (requestParamsTextArea == null) { requestParamsTextArea = createTextArea(paramBuilder.toString()); - } - else { + } else { requestParamsTextArea.setText(paramBuilder.toString()); // addRequestTabbedPane("RequestParams", requestParamsTextArea); } @@ -303,10 +304,9 @@ public void addRequestParamsTab(String requestParams) { public void addRequestBodyTabPanel(String text) { // jTextArea.setAutoscrolls(true); String reqBodyTitle = "RequestBody"; - if (requestBodyTextArea == null){ + if (requestBodyTextArea == null) { requestBodyTextArea = createTextArea(text); - } - else { + } else { requestBodyTextArea.setText(text); } @@ -321,9 +321,9 @@ public void addRequestTabbedPane(String title, JTextArea jTextArea) { JScrollPane jbScrollPane = new JBScrollPane(jTextArea, JBScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JBScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jTextArea.addKeyListener(new TextAreaKeyAdapter(jTextArea)); - requestTabbedPane.addTab(title, jbScrollPane) ; + requestTabbedPane.addTab(title, jbScrollPane); - requestTabbedPane.setSelectedComponent(jbScrollPane) ;//.setSelectedIndex(requestTabbedPane.getTabCount() - 1); + requestTabbedPane.setSelectedComponent(jbScrollPane);//.setSelectedIndex(requestTabbedPane.getTabCount() - 1); } /*添加 Response Tab*/ @@ -333,15 +333,14 @@ public void addResponseTabPanel(String text) { if (responseTextArea == null) { responseTextArea = createTextArea(text); addRequestTabbedPane(responseTabTitle, responseTextArea); - } - else { + } else { Component componentAt = null; responseTextArea.setText(text); int tabCount = requestTabbedPane.getTabCount(); for (int i = 0; i < tabCount; i++) { if (requestTabbedPane.getTitleAt(i).equals(responseTabTitle)) { componentAt = requestTabbedPane.getComponentAt(i); - requestTabbedPane.addTab(responseTabTitle,componentAt); + requestTabbedPane.addTab(responseTabTitle, componentAt); requestTabbedPane.setSelectedComponent(componentAt); break; // Component component = requestTabbedPane.getComponent(i); @@ -390,13 +389,13 @@ public void mouseClicked(MouseEvent e) { @NotNull // editor.xml private Font getEffectiveFont(String text) { - FontPreferences fontPreferences = this.getFontPreferences(); + FontPreferences fontPreferences = this.getFontPreferences(); List effectiveFontFamilies = fontPreferences.getEffectiveFontFamilies(); int size = fontPreferences.getSize(fontPreferences.getFontFamily()); // Font font=new Font(FontPreferences.FALLBACK_FONT_FAMILY,Font.PLAIN,size); - Font font=new Font(FontPreferences.DEFAULT_FONT_NAME,Font.PLAIN,size); + Font font = new Font(FontPreferences.DEFAULT_FONT_NAME, Font.PLAIN, size); // String fallbackFontFamily = getFallbackName(fontFamily, size, null); //有效字体 for (String effectiveFontFamily : effectiveFontFamilies) { @@ -422,7 +421,7 @@ private Font getEffectiveFont() { FontPreferences fontPreferences = this.getFontPreferences(); String fontFamily = fontPreferences.getFontFamily(); int size = fontPreferences.getSize(fontFamily); - return new Font("Monospaced",Font.PLAIN,size); + return new Font("Monospaced", Font.PLAIN, size); } @@ -434,7 +433,7 @@ public void resetRequestTabbedPane() { } private void resetTextComponent(JTextArea textComponent) { - if( textComponent != null && StringUtils.isNotBlank(textComponent.getText())) { + if (textComponent != null && StringUtils.isNotBlank(textComponent.getText())) { textComponent.setText(""); } } @@ -460,7 +459,7 @@ public void keyPressed(KeyEvent event) { // 组合键ctrl+enter自定义,当Ctrl (Command on Mac)+Enter组合键按下时响应 if ((event.getKeyCode() == KeyEvent.VK_ENTER) - && (event.isControlDown() || event.isMetaDown()) ) { + && (event.isControlDown() || event.isMetaDown())) { //解析,格式化json String oldValue = jTextArea.getText(); diff --git a/src/java/com/zhaow/restful/navigator/RestServiceProject.java b/src/main/java/com/zhaow/restful/navigator/RestServiceProject.java similarity index 100% rename from src/java/com/zhaow/restful/navigator/RestServiceProject.java rename to src/main/java/com/zhaow/restful/navigator/RestServiceProject.java diff --git a/src/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java b/src/main/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java similarity index 61% rename from src/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java rename to src/main/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java index 8980057..a8a9122 100644 --- a/src/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServiceProjectsManager.java @@ -29,45 +29,44 @@ @State(name = "RestServiceProjectsManager") public class RestServiceProjectsManager extends AbstractProjectComponent - implements PersistentStateComponent, Disposable, ProjectComponent { - protected final Project myProject; + implements PersistentStateComponent, Disposable, ProjectComponent { + protected final Project myProject; + private RestServicesNavigatorState myState = new RestServicesNavigatorState(); - private RestServicesNavigatorState myState = new RestServicesNavigatorState(); - - public static RestServiceProjectsManager getInstance(Project p) { - return p.getComponent(RestServiceProjectsManager.class); - } + public static RestServiceProjectsManager getInstance(Project p) { + return p.getComponent(RestServiceProjectsManager.class); + } - public RestServiceProjectsManager(Project project) { - super(project); - myProject = project; + public RestServiceProjectsManager(Project project) { + super(project); + myProject = project; // System.out.println("RestServiceProjectsManager"); - } + } - @Override - public void dispose() { + @Override + public void dispose() { - } + } - @Nullable - @Override - public RestServicesNavigatorState getState() { - return null; - } + @Nullable + @Override + public RestServicesNavigatorState getState() { + return null; + } - @Override - public void loadState(RestServicesNavigatorState state) { + @Override + public void loadState(RestServicesNavigatorState state) { - } + } - public List getServiceProjects() { + public List getServiceProjects() { // List list = DumbService.getInstance(myProject).runReadActionInSmartMode(() -> ServiceHelper.buildRestServiceProjectList(myProject)); - List list = DumbService.getInstance(myProject).runReadActionInSmartMode(() -> ServiceHelper.buildRestServiceProjectListUsingResolver(myProject)); - return list; - } + List list = DumbService.getInstance(myProject).runReadActionInSmartMode(() -> ServiceHelper.buildRestServiceProjectListUsingResolver(myProject)); + return list; + } /* public boolean hasProjects() { if (! myProject.isInitialized()) { @@ -77,7 +76,7 @@ public boolean hasProjects() { return getServiceProjects().size() > 0; }*/ - public void forceUpdateAllProjects() { + public void forceUpdateAllProjects() { - } + } } diff --git a/src/java/com/zhaow/restful/navigator/RestServiceStructure.java b/src/main/java/com/zhaow/restful/navigator/RestServiceStructure.java similarity index 88% rename from src/java/com/zhaow/restful/navigator/RestServiceStructure.java rename to src/main/java/com/zhaow/restful/navigator/RestServiceStructure.java index ec31e14..97a9960 100644 --- a/src/java/com/zhaow/restful/navigator/RestServiceStructure.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServiceStructure.java @@ -1,7 +1,6 @@ package com.zhaow.restful.navigator; -import com.intellij.icons.AllIcons; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; @@ -30,19 +29,20 @@ import java.util.List; import java.util.Map; -public class RestServiceStructure extends SimpleTreeStructure { +public class RestServiceStructure extends SimpleTreeStructure { public static final Logger LOG = Logger.getInstance(RestServiceStructure.class); - private SimpleTreeBuilder myTreeBuilder; + // fixme: 2020.3 以后不兼容 + private SimpleTreeBuilder myTreeBuilder; private SimpleTree myTree; private final Project myProject; - private RootNode myRoot = new RootNode(); + private RootNode myRoot = new RootNode(); private int serviceCount = 0; private final RestServiceProjectsManager myProjectsManager; - RestServiceDetail myRestServiceDetail ; + RestServiceDetail myRestServiceDetail; private final Map myProjectToNodeMapping = new THashMap<>(); @@ -55,11 +55,12 @@ public RestServiceStructure(Project project, myRestServiceDetail = project.getComponent(RestServiceDetail.class); configureTree(tree); - - myTreeBuilder = new SimpleTreeBuilder(tree, (DefaultTreeModel)tree.getModel(), this, null); + // fixme: 2020.3 以后不兼容 + myTreeBuilder = new SimpleTreeBuilder(tree, (DefaultTreeModel) tree.getModel(), this, null); Disposer.register(myProject, myTreeBuilder); - + // fixme: 2020.3 以后不兼容 myTreeBuilder.initRoot(); + // fixme: 2020.3 以后不兼容 myTreeBuilder.expand(myRoot, null); } @@ -97,7 +98,6 @@ public void update() { List projects = RestServiceProjectsManager.getInstance(myProject).getServiceProjects(); - // Set deleted = new HashSet<>(myProjectToNodeMapping.keySet()); // deleted.removeAll(projects); updateProjects(projects); @@ -112,10 +112,11 @@ public void updateProjects(List projects) { serviceCount += each.serviceItems.size(); ProjectNode node = findNodeFor(each); if (node == null) { - node = new ProjectNode(myRoot,each); + node = new ProjectNode(myRoot, each); myProjectToNodeMapping.put(each, node); } } +// fixme: 2020.3 以后不兼容 myTreeBuilder.getUi().doUpdateFromRoot(); // ((CachingSimpleNode) myRoot.getParent()).cleanUpCache(); // myRoot.childrenChanged(); @@ -127,6 +128,7 @@ private ProjectNode findNodeFor(RestServiceProject project) { } public void updateFrom(SimpleNode node) { + // fixme: 2020.3 以后不兼容 myTreeBuilder.addSubtreeToUpdateByElement(node); } @@ -150,7 +152,7 @@ public static List getSelectedNodes(SimpleTree tre break; } //noinspection unchecked - filtered.add((T)node); + filtered.add((T) node); } return filtered; } @@ -167,7 +169,7 @@ private static List getSelectedNodes(SimpleTree tree) { } - public abstract class BaseSimpleNode extends CachingSimpleNode{ + public abstract class BaseSimpleNode extends CachingSimpleNode { protected BaseSimpleNode(SimpleNode aParent) { super(aParent); @@ -194,7 +196,7 @@ protected void childrenChanged() { BaseSimpleNode each = this; while (each != null) { each.cleanUpCache(); - each = (BaseSimpleNode)each.getParent(); + each = (BaseSimpleNode) each.getParent(); } updateUpTo(this); } @@ -203,11 +205,12 @@ protected void childrenChanged() { public class RootNode extends BaseSimpleNode { - List projectNodes = new ArrayList<>(); + List projectNodes = new ArrayList<>(); + protected RootNode() { super(null); - getTemplatePresentation().setIcon(AllIcons.Actions.Module); - setIcon(AllIcons.Actions.Module); //兼容 IDEA 2016 +// getTemplatePresentation().setIcon(AllIcons.Actions.Module); +// setIcon(AllIcons.Actions.Module); //兼容 IDEA 2016 } @Override @@ -218,7 +221,7 @@ protected SimpleNode[] buildChildren() { @Override public String getName() { String s = "Found %d services ";// in {controllerCount} Controllers"; - return serviceCount > 0 ? String.format(s,serviceCount) : null; + return serviceCount > 0 ? String.format(s, serviceCount) : null; } @Override @@ -232,7 +235,7 @@ public void updateProjectNodes(List projects) { // cleanUpCache(); projectNodes.clear(); for (RestServiceProject project : projects) { - ProjectNode projectNode = new ProjectNode(this,project); + ProjectNode projectNode = new ProjectNode(this, project); projectNodes.add(projectNode); } @@ -260,8 +263,8 @@ public ProjectNode(SimpleNode parent,/*,List serviceItems*/Rest super(parent); myProject = project; - getTemplatePresentation().setIcon(ToolkitIcons.MODULE); - setIcon(ToolkitIcons.MODULE); //兼容 IDEA 2016 +// getTemplatePresentation().setIcon(ToolkitIcons.MODULE); +// setIcon(ToolkitIcons.MODULE); //兼容 IDEA 2016 updateServiceNodes(project.serviceItems); } @@ -269,7 +272,7 @@ public ProjectNode(SimpleNode parent,/*,List serviceItems*/Rest private void updateServiceNodes(List serviceItems) { serviceNodes.clear(); for (RestServiceItem serviceItem : serviceItems) { - serviceNodes.add(new ServiceNode(this,serviceItem)); + serviceNodes.add(new ServiceNode(this, serviceItem)); } /* for (int i = 0; i < 4; i++) { serviceNodes.add(new ServiceNode(this)); @@ -277,7 +280,7 @@ private void updateServiceNodes(List serviceItems) { SimpleNode parent = getParent(); if (parent != null) { - ((BaseSimpleNode)parent).cleanUpCache(); + ((BaseSimpleNode) parent).cleanUpCache(); } updateFrom(parent); // childrenChanged(); @@ -314,6 +317,7 @@ public void handleSelection(SimpleTree tree) { // System.out.println("ProjectNode handleSelection"); resetRestServiceDetail(); } + @Override public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) { // System.out.println("ProjectNode handleDoubleClickOrEnter"); @@ -356,29 +360,29 @@ public void handleSelection(SimpleTree tree) { /** * 显示服务详情,url - * */ + */ private void showServiceDetail(RestServiceItem serviceItem) { myRestServiceDetail.resetRequestTabbedPane(); - String method = serviceItem.getMethod()!=null? String.valueOf(serviceItem.getMethod()) : HttpMethod.GET.name(); + String method = serviceItem.getMethod() != null ? String.valueOf(serviceItem.getMethod()) : HttpMethod.GET.name(); myRestServiceDetail.setMethodValue(method); myRestServiceDetail.setUrlValue(serviceItem.getFullUrl()); String requestParams = ""; String requestBodyJson = ""; PsiElement psiElement = serviceItem.getPsiElement(); - if (psiElement.getLanguage()== JavaLanguage.INSTANCE) { + if (psiElement.getLanguage() == JavaLanguage.INSTANCE) { PsiMethodHelper psiMethodHelper = PsiMethodHelper.create(serviceItem.getPsiMethod()).withModule(serviceItem.getModule()); requestParams = psiMethodHelper.buildParamString(); requestBodyJson = psiMethodHelper.buildRequestBodyJson(); - }else if(psiElement.getLanguage()== KotlinLanguage.INSTANCE){ + } else if (psiElement.getLanguage() == KotlinLanguage.INSTANCE) { if (psiElement instanceof KtNamedFunction) { KtNamedFunction ktNamedFunction = (KtNamedFunction) psiElement; KtFunctionHelper ktFunctionHelper = KtFunctionHelper.create(ktNamedFunction).withModule(serviceItem.getModule()); requestParams = ktFunctionHelper.buildParamString(); - requestBodyJson =ktFunctionHelper.buildRequestBodyJson(); + requestBodyJson = ktFunctionHelper.buildRequestBodyJson(); } } @@ -406,11 +410,11 @@ public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) { RestServicesNavigator.getInstance(myServiceItem.getModule().getProject()).scheduleStructureUpdate(); } - if (psiElement.getLanguage()== JavaLanguage.INSTANCE) { + if (psiElement.getLanguage() == JavaLanguage.INSTANCE) { PsiMethod psiMethod = myServiceItem.getPsiMethod(); OpenSourceUtil.navigate(psiMethod); - }else if(psiElement.getLanguage()== KotlinLanguage.INSTANCE){ + } else if (psiElement.getLanguage() == KotlinLanguage.INSTANCE) { if (psiElement instanceof KtNamedFunction) { KtNamedFunction ktNamedFunction = (KtNamedFunction) psiElement; OpenSourceUtil.navigate(ktNamedFunction); diff --git a/src/java/com/zhaow/restful/navigator/RestServicesNavigator.java b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigator.java similarity index 91% rename from src/java/com/zhaow/restful/navigator/RestServicesNavigator.java rename to src/main/java/com/zhaow/restful/navigator/RestServicesNavigator.java index 1af6c43..dbb195c 100644 --- a/src/java/com/zhaow/restful/navigator/RestServicesNavigator.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigator.java @@ -39,13 +39,13 @@ public class RestServicesNavigator extends AbstractProjectComponent implements P RestServicesNavigatorState myState = new RestServicesNavigatorState(); private SimpleTree myTree; -// private JTree myTree; + // private JTree myTree; protected RestServiceStructure myStructure; private ToolWindowEx myToolWindow; private RestServiceProjectsManager myProjectsManager; - public RestServicesNavigator(Project myProject,RestServiceProjectsManager projectsManager) { + public RestServicesNavigator(Project myProject, RestServiceProjectsManager projectsManager) { super(myProject); this.myProject = myProject; myProjectsManager = projectsManager; @@ -57,7 +57,6 @@ public static RestServicesNavigator getInstance(Project p) { } - private void initTree() { myTree = new SimpleTree() { @@ -85,8 +84,7 @@ protected void paintComponent(Graphics g) { Graphics g2 = g.create(bounds.x + x, bounds.y + 20, bounds.width, bounds.height); try { myLabel.paint(g2); - } - finally { + } finally { g2.dispose(); } } @@ -109,12 +107,14 @@ public void initComponent() { private void initToolWindow() { final ToolWindowManagerEx manager = ToolWindowManagerEx.getInstanceEx(myProject); - myToolWindow = (ToolWindowEx)manager.getToolWindow(TOOL_WINDOW_ID); - if(myToolWindow != null) {return;} + myToolWindow = (ToolWindowEx) manager.getToolWindow(TOOL_WINDOW_ID); + if (myToolWindow != null) { + return; + } initTree(); - myToolWindow = (ToolWindowEx)manager.registerToolWindow(TOOL_WINDOW_ID, false, ToolWindowAnchor.RIGHT, myProject, true); + myToolWindow = (ToolWindowEx) manager.registerToolWindow(TOOL_WINDOW_ID, false, ToolWindowAnchor.RIGHT, myProject, true); myToolWindow.setIcon(ToolkitIcons.SERVICE); JPanel panel = new RestServicesNavigatorPanel(myProject, myTree); @@ -157,6 +157,7 @@ public void scheduleStructureUpdate() { scheduleStructureRequest(() -> myStructure.update()); } + private void scheduleStructureRequest(final Runnable r) { if (myToolWindow == null) return; @@ -179,7 +180,7 @@ private void scheduleStructureRequest(final Runnable r) { }); // if (isUnitTestMode()) { -/* if (myProject.isInitialized() *//* myProject.isDisposed() *//*) { + /* if (myProject.isInitialized() *//* myProject.isDisposed() *//*) { if (myStructure != null) { r.run(); } @@ -188,7 +189,7 @@ private void scheduleStructureRequest(final Runnable r) { } private void initStructure() { - myStructure = new RestServiceStructure(myProject,myProjectsManager,myTree); + myStructure = new RestServiceStructure(myProject, myProjectsManager, myTree); } @@ -205,8 +206,7 @@ public RestServicesNavigatorState getState() { try { myState.treeState = new Element("root"); TreeState.createOn(myTree).writeExternal(myState.treeState); - } - catch (WriteExternalException e) { + } catch (WriteExternalException e) { LOG.warn(e); } } diff --git a/src/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java similarity index 93% rename from src/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java rename to src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java index 7232652..8eacd54 100644 --- a/src/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorPanel.java @@ -27,7 +27,7 @@ public class RestServicesNavigatorPanel extends SimpleToolWindowPanel implements RestServiceDetail myRestServiceDetail; private JSplitPane servicesContentPaneJSplitPane; - private Splitter servicesContentPaneSplitter ; + private Splitter servicesContentPaneSplitter; private final JTextArea defaultUnderView = new JTextArea(" json format textarea "); @@ -40,12 +40,12 @@ public RestServicesNavigatorPanel(Project project, SimpleTree tree) { final ActionManager actionManager = ActionManager.getInstance(); ActionToolbar actionToolbar = actionManager.createActionToolbar("RestToolkit Navigator Toolbar", - (DefaultActionGroup)actionManager + (DefaultActionGroup) actionManager .getAction("Toolkit.NavigatorActionsToolbar"), true); setToolbar(actionToolbar.getComponent()); - Color gray = new Color(36,38,39); + Color gray = new Color(36, 38, 39); // setContent(ScrollPaneFactory.createScrollPane(myTree)); myTree.setBorder(BorderFactory.createLineBorder(gray)); @@ -53,7 +53,7 @@ public RestServicesNavigatorPanel(Project project, SimpleTree tree) { scrollPane.setBorder(BorderFactory.createLineBorder(Color.RED)); - servicesContentPaneSplitter = new Splitter(true, .5f); + servicesContentPaneSplitter = new Splitter(true, .5f); servicesContentPaneSplitter.setShowDividerControls(true); servicesContentPaneSplitter.setDividerWidth(10); servicesContentPaneSplitter.setBorder(BorderFactory.createLineBorder(Color.RED)); @@ -79,7 +79,7 @@ public RestServicesNavigatorPanel(Project project, SimpleTree tree) { public void invokePopup(final Component comp, final int x, final int y) { final String id = getMenuId(getSelectedNodes(RestServiceStructure.BaseSimpleNode.class)); if (id != null) { - final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(id); + final ActionGroup actionGroup = (ActionGroup) actionManager.getAction(id); if (actionGroup != null) { // actionManager.createActionPopupMenu("", actionGroup).getComponent().show(comp, x, y); JPopupMenu component = actionManager.createActionPopupMenu("", actionGroup).getComponent(); @@ -100,8 +100,7 @@ private String getMenuId(Collection getSelectedNod public Object getData(@NonNls String dataId) { if (RestServiceDataKeys.SERVICE_ITEMS.is(dataId)) { - return extractServices(); + return extractServices(); } return super.getData(dataId); diff --git a/src/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java similarity index 63% rename from src/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java rename to src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java index 96ad026..9fa1203 100644 --- a/src/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java +++ b/src/main/java/com/zhaow/restful/navigator/RestServicesNavigatorState.java @@ -4,8 +4,8 @@ import org.jdom.Element; public class RestServicesNavigatorState { - public boolean showPort = true; + public boolean showPort = true; - @Tag("treeState") - public Element treeState; + @Tag("treeState") + public Element treeState; } \ No newline at end of file diff --git a/src/java/com/zhaow/restful/popup/action/PopupChoiceAction.java b/src/main/java/com/zhaow/restful/popup/action/PopupChoiceAction.java similarity index 100% rename from src/java/com/zhaow/restful/popup/action/PopupChoiceAction.java rename to src/main/java/com/zhaow/restful/popup/action/PopupChoiceAction.java diff --git a/src/main/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java b/src/main/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java new file mode 100644 index 0000000..f00b442 --- /dev/null +++ b/src/main/java/com/zhaow/restful/statistics/RestfulToolkitFeaturesProvider.java @@ -0,0 +1,36 @@ +package com.zhaow.restful.statistics; + +//import com.intellij.remoteServer.util.CloudBundle; + +/** + * fixme: CloudBundle is removed in 2020.1 + */ +//public class RestfulToolkitFeaturesProvider extends ProductivityFeaturesProvider { +// public static final String CLOUDS_GROUP_ID = "clouds"; +// public static final String UPLOAD_SSH_KEY_FEATURE_ID = "upload.ssh.key"; +// +// @Override +// public FeatureDescriptor[] getFeatureDescriptors() { +// return new FeatureDescriptor[]{new FeatureDescriptor(UPLOAD_SSH_KEY_FEATURE_ID, +// CLOUDS_GROUP_ID, +// "UploadSshKey.html", +// CloudBundle.getText("upload.ssh.key.display.name"), +// 0, +// 0, +// Collections.emptySet(), +// 0, +// this)}; +// } +// +// @Override +// public GroupDescriptor[] getGroupDescriptors() { +// return new GroupDescriptor[]{ +// new GroupDescriptor(CLOUDS_GROUP_ID, CloudBundle.getText("group.display.name")) +// }; +// } +// +// @Override +// public ApplicabilityFilter[] getApplicabilityFilters() { +// return new ApplicabilityFilter[0]; +// } +//} \ No newline at end of file diff --git a/src/java/com/zhaow/utils/JsonUtils.java b/src/main/java/com/zhaow/utils/JsonUtils.java similarity index 65% rename from src/java/com/zhaow/utils/JsonUtils.java rename to src/main/java/com/zhaow/utils/JsonUtils.java index 9aee4f9..a98824d 100644 --- a/src/java/com/zhaow/utils/JsonUtils.java +++ b/src/main/java/com/zhaow/utils/JsonUtils.java @@ -26,21 +26,21 @@ public static String format(String str) { return json; } - private static boolean isGsonFormat(String targetStr,Class clazz) { + private static boolean isGsonFormat(String targetStr, Class clazz) { try { - new Gson().fromJson(targetStr,clazz); + new Gson().fromJson(targetStr, clazz); return true; - } catch(JsonSyntaxException ex) { + } catch (JsonSyntaxException ex) { return false; } } - public static boolean isValidJsonObject(String targetStr){ - return isGsonFormat(targetStr,JsonObject.class); + public static boolean isValidJsonObject(String targetStr) { + return isGsonFormat(targetStr, JsonObject.class); } - public static boolean isValidJsonArray(String targetStr){ - return isGsonFormat(targetStr,JsonArray.class); + public static boolean isValidJsonArray(String targetStr) { + return isGsonFormat(targetStr, JsonArray.class); } } \ No newline at end of file diff --git a/src/java/com/zhaow/utils/RestServiceDataKeys.java b/src/main/java/com/zhaow/utils/RestServiceDataKeys.java similarity index 57% rename from src/java/com/zhaow/utils/RestServiceDataKeys.java rename to src/main/java/com/zhaow/utils/RestServiceDataKeys.java index d0fcba2..6dc2bde 100644 --- a/src/java/com/zhaow/utils/RestServiceDataKeys.java +++ b/src/main/java/com/zhaow/utils/RestServiceDataKeys.java @@ -7,8 +7,8 @@ public class RestServiceDataKeys { - public static final DataKey> SERVICE_ITEMS = DataKey.create("SERVICE_ITEMS"); + public static final DataKey> SERVICE_ITEMS = DataKey.create("SERVICE_ITEMS"); - private RestServiceDataKeys() { - } + private RestServiceDataKeys() { + } } diff --git a/src/main/java/com/zhaow/utils/RestfulToolkitBundle.java b/src/main/java/com/zhaow/utils/RestfulToolkitBundle.java new file mode 100644 index 0000000..4b82bcc --- /dev/null +++ b/src/main/java/com/zhaow/utils/RestfulToolkitBundle.java @@ -0,0 +1,37 @@ +package com.zhaow.utils; + +import com.intellij.CommonBundle; +import org.jetbrains.annotations.NonNls; +import org.jetbrains.annotations.PropertyKey; + +import java.lang.ref.Reference; +import java.lang.ref.SoftReference; +import java.util.ResourceBundle; + +/** + * @author zhaow + */ +public class RestfulToolkitBundle { + + private static Reference ourBundle; + + @NonNls + private static final String BUNDLE = "RestfulToolkitBundle"; + + private RestfulToolkitBundle() { + + } + + public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { + return CommonBundle.message(getBundle(), key, params); + } + + private static ResourceBundle getBundle() { + ResourceBundle bundle = com.intellij.reference.SoftReference.dereference(ourBundle); + if (bundle == null) { + bundle = ResourceBundle.getBundle(BUNDLE); + ourBundle = new SoftReference<>(bundle); + } + return bundle; + } +} \ No newline at end of file diff --git a/src/java/com/zhaow/utils/ToolkitUtil.java b/src/main/java/com/zhaow/utils/ToolkitUtil.java similarity index 95% rename from src/java/com/zhaow/utils/ToolkitUtil.java rename to src/main/java/com/zhaow/utils/ToolkitUtil.java index da507af..2aeb2fd 100644 --- a/src/java/com/zhaow/utils/ToolkitUtil.java +++ b/src/main/java/com/zhaow/utils/ToolkitUtil.java @@ -59,8 +59,7 @@ public static boolean isNoBackgroundMode() { public static void runDumbAware(final Project project, final Runnable r) { if (DumbService.isDumbAware(r)) { r.run(); - } - else { + } else { DumbService.getInstance(project).runWhenSmart(DisposeAwareRunnable.create(r, project)); } } @@ -77,8 +76,7 @@ public static void invokeLater(Project p, Runnable r) { public static void invokeLater(final Project p, final ModalityState state, final Runnable r) { if (isNoBackgroundMode()) { r.run(); - } - else { + } else { ApplicationManager.getApplication().invokeLater(DisposeAwareRunnable.create(r, p), state); } } @@ -104,7 +102,6 @@ public static void runWriteAction(@NotNull Runnable action) { } - @NotNull public static String removeRedundancyMarkup(String pattern) { @@ -113,15 +110,15 @@ public static String removeRedundancyMarkup(String pattern) { "( " + "([a-zA-Z0-9]([a-zA-Z0-9\\\\-]{0,61}[a-zA-Z0-9])?\\\\.)+[a-zA-Z]{2,6} |" + // domain "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)" + // ip address - ")" ; + ")"; String localhost = "localhost"; if (pattern.contains(localhost)) { - pattern = pattern.replaceFirst(localhostRegex,""); + pattern = pattern.replaceFirst(localhostRegex, ""); } - if (pattern.contains("http:") || pattern.contains("https:") ) { // quick test if reg exp should be used - pattern = pattern.replaceFirst(hostAndPortRegex, ""); + if (pattern.contains("http:") || pattern.contains("https:")) { // quick test if reg exp should be used + pattern = pattern.replaceFirst(hostAndPortRegex, ""); } //TODO : resolve RequestMapping(params="method=someMethod") @@ -176,5 +173,4 @@ public static Map textToParamMap(String text) { } - } diff --git a/src/java/com/zhaow/utils/ToolkitUtil.java.bak b/src/main/java/com/zhaow/utils/ToolkitUtil.java.bak similarity index 100% rename from src/java/com/zhaow/utils/ToolkitUtil.java.bak rename to src/main/java/com/zhaow/utils/ToolkitUtil.java.bak diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml new file mode 100644 index 0000000..39d7035 --- /dev/null +++ b/src/main/resources/META-INF/plugin.xml @@ -0,0 +1,228 @@ + + com.zhaow.restful.toolkit + RestfulToolkit + 2.0.10 + zhaow + + A toolkit for RESTful services development. +
      +
    • 1.ONE STEP to navigate to service declaration. ( use: Ctrl + \ or Ctrl + Alt + N )
    • +
    • 2.Show RESTful services structure.
    • +
    • 3.A simple http request tool.
    • +
    • 4.Add some useful functions at request method, Generate&Copy Query Param, Generate&Copy URL, etc.
    • +
    • 5.Other functions: Convert to JSON; to java class,format json data ( Windows: Ctrl + Enter; Mac: Command + Enter ) .
    • +
    +

    support Spring framework (Spring MVC / Spring Boot) +

    support JAX-RS +

    support Java and Kotlin languages + +


    +

    一套 RESTful 服务开发辅助工具集。

    +
      +
    • 1.根据 URL 直接跳转到对应的方法定义 ( Ctrl \ or Ctrl Alt N );
    • +
    • 2.提供了一个 Services tree 的显示窗口;
    • +
    • 3.一个简单的 http 请求工具;
    • +
    • 4.在请求方法上添加了有用功能: 复制生成 URL;,复制方法参数...
    • +
    • 5.其他功能: java 类上添加 Convert to JSON 功能,格式化 json 数据 ( Windows: Ctrl + Enter; Mac: Command + Enter )。
    • +
    +

    支持 Spring 体系 (Spring MVC / Spring Boot) +

    支持 JAX-RS +

    支持 Java 和 Kotlin 语言。 + + ]]> + + 2.0.10 移除了 2020.1 版本不兼容的内容(只是简单注释掉,不知道是否移除了重要内容) 注意:2020.3移除了更多的东西 +

  • 2.0.5 Bug fixed, supported http request OPTIONS,TRACE,CONNECT methods.
  • +
  • 2.0.4 Fixed NullPointerException with Kotlin project.
    + Fixed IllegalArgumentException: No enum constant com.zhaow.restful.method.HttpMethod.HEAD
    + Supported Kotlin 1.2 level.
  • +
  • 2.0.3 Improvements in navigate service(url), auto pasted copied http url to from clipboard.
    + Bug fixed.
  • +
  • 2.0.2 Match mapped URLs for Controllers without @RequestMapping annotations;
    + Supported mapped URLs for Controllers extended supper Object with @RequestMapping annotations.
    + Added Popup Menus ( "Copy Full Url", "Jump to Source") for service nodes. +
  • +
  • 2.0.1 Fixed JSON generation issue with POJO contains array fields; +
  • +
  • 2.0 Add Kotlin language supported;
    + Fixed some bugs. +
  • +
  • 1.1 Supported JAX-RS;
    + Format JSON data , use "Command + Enter" on Mac + (增强 POJO 生成 json 功能,处理 List、Enum等类型,处理自关联场景);
    + Fixed some bugs.
    +
  • +
  • 1.0.9 Service url navigation: matched restful style request mappings (e.g.:"/product/{productId}");
    +
  • +
  • 1.0.8 Bug fixed
  • +
  • 1.0.7 Match more mapped URLs ; (识别更多映射)
    + Replaced icons;
    + Add "Convert to JSON (Compressed)" function to java class; +
  • +
  • 1.0.6 Compatible with IDEA 2016 (兼容 IDEA 2016)
  • +
  • 1.0.5 修复发送请求IDE卡死的问题.
  • +
  • 1.0.4 Format Date type (格式化 Date 类型)
  • +
  • 1.0.3 Small cleanup some code.
  • + ]]> + + + + + + + + com.intellij.modules.platform + com.intellij.properties + org.jetbrains.plugins.yaml + org.jetbrains.kotlin + + + + com.zhaow.restful.navigator.RestServicesNavigator + + + com.zhaow.restful.navigator.RestServiceProjectsManager + + + + com.zhaow.restful.navigator.RestServiceDetail + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    \ No newline at end of file diff --git a/src/main/resources/RestfulToolkitBundle.properties b/src/main/resources/RestfulToolkitBundle.properties new file mode 100644 index 0000000..f246f00 --- /dev/null +++ b/src/main/resources/RestfulToolkitBundle.properties @@ -0,0 +1,3 @@ +toolkit.name=RestfulToolkit +toolkit.scanning.projects=Scanning projects... +toolkit.navigator.nothing.to.display=No Services Found ,try use {0} to refresh services \ No newline at end of file diff --git a/resources/icons/method/d.png b/src/main/resources/icons/method/d.png similarity index 100% rename from resources/icons/method/d.png rename to src/main/resources/icons/method/d.png diff --git a/resources/icons/method/g.png b/src/main/resources/icons/method/g.png similarity index 100% rename from resources/icons/method/g.png rename to src/main/resources/icons/method/g.png diff --git a/resources/icons/method/p.png b/src/main/resources/icons/method/p.png similarity index 100% rename from resources/icons/method/p.png rename to src/main/resources/icons/method/p.png diff --git a/resources/icons/method/p2.png b/src/main/resources/icons/method/p2.png similarity index 100% rename from resources/icons/method/p2.png rename to src/main/resources/icons/method/p2.png diff --git a/resources/icons/method/p3.png b/src/main/resources/icons/method/p3.png similarity index 100% rename from resources/icons/method/p3.png rename to src/main/resources/icons/method/p3.png diff --git a/resources/icons/method/undefined.png b/src/main/resources/icons/method/undefined.png similarity index 100% rename from resources/icons/method/undefined.png rename to src/main/resources/icons/method/undefined.png diff --git a/resources/icons/service.png b/src/main/resources/icons/service.png similarity index 100% rename from resources/icons/service.png rename to src/main/resources/icons/service.png diff --git a/src/main/resources/tips/GotoService.html b/src/main/resources/tips/GotoService.html new file mode 100644 index 0000000..b3c932c --- /dev/null +++ b/src/main/resources/tips/GotoService.html @@ -0,0 +1,13 @@ + + + + + +

    + To navigate any rest service in the editor quickly, press &shortcut:GotoService; + (Navigate | Rest Service) + and start typing the url of the service. Choose the item from a drop-down list that appears.

    +

    +

    + + diff --git a/resources/tips/images/GotoService.png b/src/main/resources/tips/images/GotoService.png similarity index 100% rename from resources/tips/images/GotoService.png rename to src/main/resources/tips/images/GotoService.png diff --git a/resources/tips/images/SSHKeyUpload.png b/src/main/resources/tips/images/SSHKeyUpload.png similarity index 100% rename from resources/tips/images/SSHKeyUpload.png rename to src/main/resources/tips/images/SSHKeyUpload.png