proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/ShortcutUtil.java
ShortcutUtil
parseLink
class ShortcutUtil { private boolean isDirectory; private boolean isLocal; private String realFile; /** * Provides a quick test to see if this could be a valid link ! * If you try to instantiate a new WindowShortcut and the link is not valid, * Exceptions may be thrown and Exceptions are extremely slow to generate, * therefore any code needing to loop through several files should first check this. * * @param path * the potential link * * @return true if may be a link, false otherwise */ public static boolean isPotentialValidLink(final Path path) { if (!Files.exists(path)) return false; if (!IOUtil.getExtension(path).equals("lnk")) return false; final int minimumLength = 0x64; try (InputStream fis = Files.newInputStream(path)) { return fis.available() >= minimumLength && isMagicPresent(IOUtil.toByteArray(fis, 32)); } catch(Exception ex) { return false; } } /** * @param path * Path reference to shortcut. * * @throws IOException * If the path cannot be read. * @throws ParseException * If the link cannot be read. */ public ShortcutUtil(final Path path) throws IOException, ParseException { try(InputStream in = Files.newInputStream(path)) { parseLink(IOUtil.toByteArray(in)); } } /** * @return the name of the filesystem object pointed to by this shortcut */ public String getRealFilename() { return realFile; } /** * Tests if the shortcut points to a local resource. * * @return true if the 'local' bit is set in this shortcut, false otherwise */ public boolean isLocal() { return isLocal; } /** * Tests if the shortcut points to a directory. * * @return true if the 'directory' bit is set in this shortcut, false otherwise */ public boolean isDirectory() { return isDirectory; } private static boolean isMagicPresent(final byte[] link) { final int magic = 0x0000004C; final int magicOffset = 0x00; return link.length >= 32 && bytesToDword(link, magicOffset) == magic; } /** * Gobbles up link data by parsing it and storing info in member fields * * @param link * all the bytes from the .lnk file */ private void parseLink(final byte[] link) throws ParseException {<FILL_FUNCTION_BODY>} private static String getNullDelimitedString(final byte[] bytes, final int off) { // count bytes until the null character (0) int len = 0; while(bytes[off + len] != 0) len++; return new String(bytes, off, len); } /* * Convert two bytes into a short note, this is little endian because it's * for an Intel only OS. */ private static int bytesToWord(final byte[] bytes, final int off) { return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff); } private static int bytesToDword(final byte[] bytes, final int off) { return (bytesToWord(bytes, off + 2) << 16) | bytesToWord(bytes, off); } }
try { if(!isMagicPresent(link)) throw new ParseException("Invalid shortcut; magic is missing", 0); // get the flags byte final byte flags = link[0x14]; // get the file attributes byte final int fileAttsOffset = 0x18; final byte fileAtts = link[fileAttsOffset]; final byte isDirMask = (byte) 0x10; isDirectory = (fileAtts & isDirMask) > 0; // if the shell settings are present, skip them final int shellOffset = 0x4c; final byte hasShellMask = (byte) 0x01; int shellLen = 0; if((flags & hasShellMask) > 0) { // the plus 2 accounts for the length marker itself shellLen = bytesToWord(link, shellOffset) + 2; } // get to the file settings final int fileStart = 0x4c + shellLen; final int fileLocationInfoFlagOffsetOffset = 0x08; final int fileLocationInfoFlag = link[fileStart + fileLocationInfoFlagOffsetOffset]; isLocal = (fileLocationInfoFlag & 2) == 0; // get the local volume and local system values //final int localVolumeTable_offset_offset = 0x0C; final int basenameOffsetOffset = 0x10; final int networkVolumeTableOffsetOffset = 0x14; final int finalnameOffsetOffset = 0x18; final int finalnameOffset = link[fileStart + finalnameOffsetOffset] + fileStart; final String finalname = getNullDelimitedString(link, finalnameOffset); if(isLocal) { final int basenameOffset = link[fileStart + basenameOffsetOffset] + fileStart; final String basename = getNullDelimitedString(link, basenameOffset); realFile = basename + finalname; } else { final int networkVolumeTableOffset = link[fileStart + networkVolumeTableOffsetOffset] + fileStart; final int shareNameOffsetOffset = 0x08; final int shareNameOffset = link[networkVolumeTableOffset + shareNameOffsetOffset] + networkVolumeTableOffset; final String shareName = getNullDelimitedString(link, shareNameOffset); realFile = shareName + "\\" + finalname; } } catch(final ArrayIndexOutOfBoundsException e) { throw new ParseException("Could not be parsed, probably not a valid WindowsShortcut", 0); }
900
666
1,566
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/StringUtil.java
StringUtil
splitNewlineSkipEmpty
class StringUtil { /** * @param input * Some text containing newlines. * * @return Input split by newline. */ public static String[] splitNewline(String input) { return input.split("\\r\\n|\\n"); } /** * @param input * Some text containing newlines. * * @return Input split by newline. * Empty lines <i>(Containing only the newline split)</i> are omitted. */ public static String[] splitNewlineSkipEmpty(String input) {<FILL_FUNCTION_BODY>} /** * Replace the last match of some text in the given string. * * @param string * Text containing items to replace. * @param toReplace * Pattern to match. * @param replacement * Text to replace pattern with. * * @return Modified string. */ public static String replaceLast(String string, String toReplace, String replacement) { int i = string.lastIndexOf(toReplace); if (i > -1) return string.substring(0, i) + replacement + string.substring(i + toReplace.length()); return string; } /** * Creates a string incrementing in numerical value. * Example: a, b, c, ... z, aa, ab ... * * @param alphabet * The alphabet to pull from. * @param index * Name index. * * @return Generated String */ public static String generateName(String alphabet, int index) { // String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char[] charz = alphabet.toCharArray(); int alphabetLength = charz.length; int m = 8; final char[] array = new char[m]; int n = m - 1; while (index > charz.length - 1) { int k = Math.abs(-(index % alphabetLength)); array[n--] = charz[k]; index /= alphabetLength; index -= 1; } array[n] = charz[index]; return new String(array, n, m - n); } /** * @param level * Level of indent. * @param indent * Indent format. * * @return Indented string. */ public static String indent(int level, String indent) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) sb.append(indent); return sb.toString(); } /** * @param str * Original string. * @param maxLength * Maximum length. * * @return String, cutting off anything past the maximum length if necessary. */ public static String limit(String str, int maxLength) { if (str.length() > maxLength) return str.substring(0, maxLength); return str; } /** * Convert an enum to a string. * * @param value * Enum value. * @param <E> * Type of enum. * * @return Case modified name of enum. */ public static <E extends Enum<?>> String toString(E value) { return value.name().substring(0, 1).toUpperCase() + value.name().substring(1).toLowerCase(); } /** * @param pattern * Pattern to look for. * @param text * Text to check. * * @return Number of times the given pattern appears in the text. */ public static int count(String pattern, String text) { int count = 0; while (text.contains(pattern)) { text = text.replaceFirst(pattern, ""); count++; } return count; } }
String[] split = input.split("[\\r\\n]+"); // If the first line of the file is a newline split will still have // one blank entry at the start. if (split[0].isEmpty()) return Arrays.copyOfRange(split, 1, split.length); return split;
1,050
83
1,133
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/ThreadUtil.java
ThreadUtil
runSupplyConsumer
class ThreadUtil { private static final ScheduledExecutorService scheduledService = Executors.newScheduledThreadPool(threadCount(), new ThreadFactoryBuilder() .setNameFormat("Recaf Scheduler Thread #%d") .setDaemon(true).build()); private static final ExecutorService service = Executors.newWorkStealingPool(threadCount()); /** * @param action * Runnable to start in new thread. * * @return Thread future. */ public static Future<?> run(Runnable action) { return service.submit(action); } /** * @param action * Task to start in new thread. * @param <T> * Type of task return value. * * @return Thread future. */ @SuppressWarnings("unchecked") public static <T> Future<T> run(Task<T> action) { return (Future<T>) service.submit(action); } /** * @param updateInterval * Time in milliseconds between each execution. * @param action * Runnable to start in new thread. * * @return Scheduled future. */ public static ScheduledFuture<?> runRepeated(long updateInterval, Runnable action) { return scheduledService.scheduleAtFixedRate(action, 0, updateInterval, TimeUnit.MILLISECONDS); } /** * @param time * Delay to wait in milliseconds. * @param action * Runnable to start in new thread. * * @return Scheduled future. */ public static Future<?> runDelayed(long time, Runnable action) { return scheduledService.schedule(action, time, TimeUnit.MILLISECONDS); } /** * Run a given action with a timeout. * * @param time * Timeout in milliseconds. * @param action * Runnable to execute. * * @return {@code true} */ public static boolean timeout(int time, Runnable action) { try { Future<?> future = run(action); future.get(time, TimeUnit.MILLISECONDS); return true; } catch(TimeoutException e) { // Expected: Timeout return false; } catch(Throwable t) { // Other error return true; } } /** * @param supplier * Value generator, run on a non-jfx thread. * @param consumer * JavaFx consumer thread, takes the supplied value. * @param <T> * Type of value. */ public static <T> void runSupplyConsumer(Supplier<T> supplier, Consumer<T> consumer) { runSupplyConsumer(supplier, Long.MAX_VALUE, null, consumer, null); } /** * @param supplier * Value generator, run on a non-jfx thread. * @param supplierTimeout * Time to wait on the supplier generating a value before aborting the task. * @param timeoutAction * Action to run when timeout is reached. * @param consumer * JavaFx consumer thread, takes the supplied value. * @param handler * Error handling. * @param <T> * Type of value. */ public static <T> void runSupplyConsumer(Supplier<T> supplier, long supplierTimeout, Runnable timeoutAction, Consumer<T> consumer, Consumer<Throwable> handler) {<FILL_FUNCTION_BODY>} /** * @param time * Delay to wait in milliseconds. * @param consumer * JavaFx runnable action. * * @return Scheduled future. */ public static Future<?> runJfxDelayed(long time, Runnable consumer) { return scheduledService.schedule(() -> Platform.runLater(consumer), time, TimeUnit.MILLISECONDS); } /** * @param consumer * JavaFx runnable action. */ public static void checkJfxAndEnqueue(Runnable consumer) { if (!Platform.isFxApplicationThread()) { Platform.runLater(consumer); } else { consumer.run(); } } /** * Shutdowns executors. */ public static void shutdown() { trace("Shutting down thread executors"); service.shutdownNow(); scheduledService.shutdownNow(); } private static int threadCount() { return Runtime.getRuntime().availableProcessors(); } }
new Thread(() -> { try { // Attempt to compute value within given time Future<T> future = service.submit(supplier::get); T value = future.get(supplierTimeout, TimeUnit.MILLISECONDS); // Execute action with value Platform.runLater(() -> consumer.accept(value)); } catch(CancellationException | InterruptedException | TimeoutException r) { // Timed out if (timeoutAction != null) timeoutAction.run(); } catch(ExecutionException e) { // Supplier encountered an error // - Actual cause is wrapped twice Throwable cause = e.getCause().getCause(); if(handler != null) handler.accept(cause); } catch(Throwable t) { // Unknown error if(handler != null) handler.accept(t); } }).start();
1,233
246
1,479
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/TypeUtil.java
TypeUtil
sortToString
class TypeUtil { private static final Type[] PRIMITIVES = new Type[]{ Type.VOID_TYPE, Type.BOOLEAN_TYPE, Type.BYTE_TYPE, Type.CHAR_TYPE, Type.SHORT_TYPE, Type.INT_TYPE, Type.FLOAT_TYPE, Type.DOUBLE_TYPE, Type.LONG_TYPE }; /** * Cosntant for object type. */ public static final Type OBJECT_TYPE = Type.getObjectType("java/lang/Object"); /** * private sort denoting an object type, such as "com/Example" versus the * standard "Lcom/Example;". */ private static final int INTERNAL = 12; /** * @param desc * Type to check. * @return Type denotes a primitive type. */ public static boolean isPrimitiveDesc(String desc) { if(desc.length() != 1) { return false; } switch(desc.charAt(0)) { case 'Z': case 'C': case 'B': case 'S': case 'I': case 'F': case 'J': case 'D': return true; default: return false; } } /** * @param arg * Operand value of a NEWARRAY instruction. * * @return Array element type. */ public static Type newArrayArgToType(int arg) { switch(arg) { case 4: return Type.BOOLEAN_TYPE; case 5: return Type.CHAR_TYPE; case 6: return Type.FLOAT_TYPE; case 7: return Type.DOUBLE_TYPE; case 8: return Type.BYTE_TYPE; case 9: return Type.SHORT_TYPE; case 10: return Type.INT_TYPE; case 11: return Type.LONG_TYPE; default: break; } throw new IllegalArgumentException("Unexpected NEWARRAY arg: " + arg); } /** * @param type * Array element type. * * @return Operand value for a NEWARRAY instruction. */ public static int typeToNewArrayArg(Type type) { switch(type.getDescriptor().charAt(0)) { case 'Z': return 4; case 'C': return 5; case 'F': return 6; case 'D': return 7; case 'B': return 8; case 'S': return 9; case 'I': return 10; case 'J': return 11; default: break; } throw new IllegalArgumentException("Unexpected NEWARRAY type: " + type.getDescriptor()); } /** * @param desc * Text to check. * @return {@code true} when the descriptor is in method format, "(Ltype/args;)Lreturn;" */ public static boolean isMethodDesc(String desc) { // This assumes a lot, but hey, it serves our purposes. return desc.charAt(0) == '('; } /** * @param desc * Text to check. * @return {@code true} when the descriptor is in standard format, "Lcom/Example;". */ public static boolean isFieldDesc(String desc) { return desc.length() > 2 && desc.charAt(0) == 'L' && desc.charAt(desc.length() - 1) == ';'; } /** * @param desc * Text to check. * @return Type is object/internal format of "com/Example". */ public static boolean isInternal(String desc) { return !isMethodDesc(desc) && !isFieldDesc(desc); } /** * Convert a Type sort to a string representation. * * @param sort * Type sort value. * * @return Sort string value. */ public static String sortToString(int sort) {<FILL_FUNCTION_BODY>} /** * @param sort * Type sort<i>(kind)</i> * * @return Size of type. */ public static int sortToSize(int sort) { switch(sort) { case Type.LONG: case Type.DOUBLE: return 2; default: return 1; } } /** * @param type * Some array type. * * @return Array depth. */ public static int getArrayDepth(Type type) { if (type.getSort() == Type.ARRAY) return type.getDimensions(); return 0; } /** * @param desc * Some class name. * * @return {@code true} if it matches the class name of a primitive type. */ public static boolean isPrimitiveClassName(String desc) { for (Type prim : PRIMITIVES) if (prim.getClassName().equals(desc)) return true; return false; } /** * @param desc * Must be a primitive class name. See {@link #isPrimitiveClassName(String)}. * * @return Internal name. */ public static String classToPrimitive(String desc) { for (Type prim : PRIMITIVES) if (prim.getClassName().equals(desc)) return prim.getInternalName(); throw new IllegalArgumentException("Descriptor was not a primitive class name!"); } }
switch(sort) { case Type.VOID: return "VOID"; case Type.BOOLEAN: return "BOOLEAN"; case Type.CHAR: return "CHAR"; case Type.BYTE: return "BYTE"; case Type.SHORT: return "SHORT"; case Type.INT: return "INT"; case Type.FLOAT: return "FLOAT"; case Type.LONG: return "LONG"; case Type.DOUBLE: return "DOUBLE"; case Type.ARRAY: return "ARRAY"; case Type.OBJECT: return "OBJECT"; case Type.METHOD: return "METHOD"; case INTERNAL: return "INTERNAL"; default: return "UNKNOWN"; }
1,457
225
1,682
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/self/SelfReferenceUtil.java
SelfReferenceUtil
getFiles
class SelfReferenceUtil { private final File file; private final boolean isJar; private SelfReferenceUtil(File file) { this.file = file; this.isJar = file.getName().toLowerCase().endsWith(".jar"); } /** * @return File reference to self. */ public File getFile() { return file; } /** * @return File path to self. */ public String getPath() { return file.getAbsolutePath(); } /** * @return Is the current executable context a jar file. */ public boolean isJar() { return isJar; } /** * @return List of language files recognized. */ public List<Resource> getLangs() { return getFiles("translations/", ".json"); } /** * @return List of application-wide styles recognized. */ public List<Resource> getStyles() { return getFiles("style/ui-", ".css"); } /** * @return List of text-editor styles recognized. */ public List<Resource> getTextThemes() { return getFiles("style/text-", ".css"); } /** * @param prefix * File prefix to match. * @param suffix * File suffix to match <i>(such as a file extension)</i>. * @return List of matching files. */ private List<Resource> getFiles(String prefix, String suffix) {<FILL_FUNCTION_BODY>} /** * @return Recaf executable context. */ public static SelfReferenceUtil get() { try { CodeSource codeSource = Recaf.class.getProtectionDomain().getCodeSource(); File selfFile = new File(codeSource.getLocation().toURI().getPath()); return new SelfReferenceUtil(selfFile); } catch(URISyntaxException ex) { // This shouldn't happen since the location URL shouldn't be invalid. throw new IllegalStateException("Failed to resolve self reference", ex); } } }
List<Resource> list = new ArrayList<>(); if (isJar()) { // Read self as jar try (ZipFile file = new ZipFile(getFile())) { Enumeration<? extends ZipEntry> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // skip directories if (entry.isDirectory()) continue; String name = entry.getName(); if (prefix != null && !name.startsWith(prefix)) continue; if (suffix != null && !name.endsWith(suffix)) continue; list.add(Resource.internal(name)); } } catch (Exception ex) { error(ex, "Failed internal file (archive) lookup: {}", getFile()); } } else { // Read self as file directory Path dir = getFile().toPath(); try { Files.walk(dir).forEach(p -> { File file = dir.relativize(p).toFile(); String path = file.getPath().replace('\\', '/'); if (prefix != null && !path.startsWith(prefix)) return; if (suffix != null && !path.endsWith(suffix)) return; list.add(Resource.internal(path)); }); } catch(IOException ex) { error(ex, "Failed internal file (directory) lookup: {}", getFile()); } } return list;
530
399
929
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/struct/Expireable.java
Expireable
get
class Expireable<T> { private final Supplier<T> getter; private long threshold; private long lastGet; private T value; /** * Create an expirable value. * * @param threshold * Time until the current value is invalidated. * @param getter * Supplier function for the value. */ public Expireable(long threshold, Supplier<T> getter) { this.threshold = threshold; this.getter = getter; this.value = getter.get(); this.lastGet = System.currentTimeMillis(); } /** * @return Current value. */ public T get() {<FILL_FUNCTION_BODY>} }
if(System.currentTimeMillis() - lastGet > threshold) { value = getter.get(); lastGet = System.currentTimeMillis(); } return value;
191
52
243
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/struct/ListeningMap.java
ListeningMap
putAll
class ListeningMap<K, V> implements Map<K, V> { private final Set<BiConsumer<K, V>> putListeners = new HashSet<>(); private final Set<Consumer<Object>> removeListeners = new HashSet<>(); private Map<K, V> backing; /** * @param backing * The map to contain the actual data. */ public void setBacking(Map<K, V> backing) { this.backing = backing; } /** * @return {@code true} when the backing map is not null. */ public boolean isBacked() { return backing != null; } /** * @return Set of listeners that are fed the key and value of items putted items. */ public Set<BiConsumer<K, V>> getPutListeners() { return putListeners; } /** * @return Set of listeners that are fed keys or removed items. */ public Set<Consumer<Object>> getRemoveListeners() { return removeListeners; } @Override public V put(K key, V value) { putListeners.forEach(listener -> listener.accept(key, value)); return backing.put(key, value); } @Override public V remove(Object key) { removeListeners.forEach(listener -> listener.accept(key)); return backing.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) {<FILL_FUNCTION_BODY>} @Override public V get(Object key) { return backing.get(key); } @Override public int size() { return backing.size(); } @Override public boolean isEmpty() { return backing.isEmpty(); } @Override public boolean containsKey(Object key) { return backing.containsKey(key); } @Override public boolean containsValue(Object value) { return backing.containsValue(value); } @Override public void clear() { backing.clear(); } @Override public Set<K> keySet() { return backing.keySet(); } @Override public Collection<V> values() { return backing.values(); } @Override public Set<Entry<K, V>> entrySet() { return backing.entrySet(); } }
for(Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue());
596
40
636
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/util/struct/Pair.java
Pair
equals
class Pair<K, V> { private final K key; private final V value; /** * Constructs a pair. * * @param key * Left item. * @param value * Right item. */ public Pair(K key, V value) { this.key = key; this.value = value; } /** * @return Left item. */ public K getKey() { return key; } /** * @return Right item, or item associated with the {@link #getKey()}. */ public V getValue() { return value; } @Override public String toString() { return key + "=" + value; } @Override public int hashCode() { return Objects.hash(key, value); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} }
if(this == o) return true; if(o instanceof Pair) { Pair other = (Pair) o; if(key != null && !key.equals(other.key)) return false; if(value != null && !value.equals(other.value)) return false; return true; } return false;
229
90
319
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/workspace/FileSystemResourceLocation.java
FileSystemResourceLocation
equals
class FileSystemResourceLocation extends ResourceLocation { private final Path path; /** * Create the file system location. * * @param kind kind of the resource. * @param path file system path. */ public FileSystemResourceLocation(ResourceKind kind, Path path) { super(kind); this.path = path; } @Override public ResourceLocation normalize() { return new FileSystemResourceLocation(kind(), path.normalize()); } @Override public ResourceLocation concat(ResourceLocation other) { // We can only concat fs location or literal Path path = null; if (other instanceof FileSystemResourceLocation) { path = ((FileSystemResourceLocation) other).path; if (!this.path.getFileSystem().equals(path.getFileSystem())) { throw new IllegalStateException("File systems mismatch!"); } } else if (other instanceof LiteralResourceLocation) { path = Paths.get(((LiteralResourceLocation) other).getLiteral()); } if (path == null) { throw new IllegalArgumentException("Can only concat with file system paths or literals!"); } return new FileSystemResourceLocation(kind(), this.path.resolve(path)); } @Override public ResourceLocation toAbsolute() { return new FileSystemResourceLocation(kind(), path.toAbsolutePath()); } @Override public boolean isAbsolute() { return path.isAbsolute(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return path.hashCode(); } @Override public String toString() { return path.toString(); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FileSystemResourceLocation that = (FileSystemResourceLocation) o; return Objects.equals(path, that.path);
452
65
517
<methods>public void <init>(me.coley.recaf.workspace.ResourceKind) ,public abstract me.coley.recaf.workspace.ResourceLocation concat(me.coley.recaf.workspace.ResourceLocation) ,public abstract boolean equals(java.lang.Object) ,public abstract boolean isAbsolute() ,public me.coley.recaf.workspace.ResourceKind kind() ,public abstract me.coley.recaf.workspace.ResourceLocation normalize() ,public abstract me.coley.recaf.workspace.ResourceLocation toAbsolute() ,public abstract java.lang.String toString() <variables>private final non-sealed me.coley.recaf.workspace.ResourceKind kind
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/workspace/History.java
History
pop
class History { // TODO: For large inputs it would make sense to offload this to the file system. // - But only for large inputs. In-memory is much faster and should be the default. /** * Stack of changed content. */ private final Stack<byte[]> stack = new Stack<>(); /** * Stack of when the content was changed. */ private final Stack<Instant> times = new Stack<>(); /** * File map to update when the history is rolled back. */ private final ListeningMap<String, byte[]> map; /** * File being tracked. */ public final String name; /** * Flag for if bottom is reached. */ private boolean atInitial = true; /** * Constructs a history for an item of the given name in the given map. * * @param map * Map containing the item. * @param name * Item's key. */ public History(ListeningMap<String, byte[]> map, String name) { this.map = map; this.name = name; } /** * @return Size of history for the current file. */ public int size() { return stack.size(); } /** * @return {@code true} if the top of the stack is the initial state of the item. */ public boolean isAtInitial() { return atInitial; } /** * Wipe all items from the history. */ public void clear() { stack.clear(); times.clear(); } /** * Fetch the creation times of all save states. * * @return Array of timestamps of each tracked change. */ public Instant[] getFileTimes() { return times.toArray(new Instant[0]); } /** * @return Instant of most recent change. */ public Instant getMostRecentUpdate() { return times.peek(); } /** * Gets most recent change, deleting it in the process. * * @return Most recent version of the tracked file. */ public byte[] pop() {<FILL_FUNCTION_BODY>} /** * @return Most recent version of the tracked file. */ public byte[] peek() { return stack.peek(); } /** * Updates current value, pushing the latest value into the history * stack. * * @param modified * Changed value. */ public void push(byte[] modified) { stack.push(modified); times.push(Instant.now()); // Don't log the initial push if(stack.size() > 1) { info("Saved '{}' - {} total", name, stack.size()); atInitial = false; } } }
Instant time = times.pop(); byte[] content = stack.pop(); if (content != null) { map.put(name, content); // If the size is now 0, we just pop'd the initial state. // Since we ALWAYS want to keep the initial state we will push it back. if (size() == 0) { times.push(time); stack.push(content); atInitial = true; info("Reverted '{}' - initial state", name); } else { info("Reverted '{}' - {} total", name, stack.size()); } } else { throw new IllegalStateException("No history to revert to!"); } return content;
722
199
921
<no_super_class>
Col-E_Recaf
Recaf/src/main/java/me/coley/recaf/workspace/LiteralResourceLocation.java
LiteralResourceLocation
equals
class LiteralResourceLocation extends ResourceLocation { private final String literal; /** * No public constructions are allowed. */ private LiteralResourceLocation(ResourceKind kind, String literal) { super(kind); this.literal = literal; } @Override public ResourceLocation normalize() { return this; } @Override public ResourceLocation concat(ResourceLocation other) { if (!(other instanceof LiteralResourceLocation)) { throw new IllegalArgumentException("Cannot concat with non-literal location!"); } return new LiteralResourceLocation(kind(), literal + ((LiteralResourceLocation) other).literal); } @Override public ResourceLocation toAbsolute() { return this; } @Override public boolean isAbsolute() { return true; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return literal.hashCode(); } @Override public String toString() { return literal; } /** * @return backing literal. */ public String getLiteral() { return literal; } /** * @param kind kind of the location. * @param literal location literal. * @return new literal resource location. */ public static ResourceLocation ofKind(ResourceKind kind, String literal) { return new LiteralResourceLocation(kind, literal); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LiteralResourceLocation that = (LiteralResourceLocation) o; return Objects.equals(literal, that.literal);
389
66
455
<methods>public void <init>(me.coley.recaf.workspace.ResourceKind) ,public abstract me.coley.recaf.workspace.ResourceLocation concat(me.coley.recaf.workspace.ResourceLocation) ,public abstract boolean equals(java.lang.Object) ,public abstract boolean isAbsolute() ,public me.coley.recaf.workspace.ResourceKind kind() ,public abstract me.coley.recaf.workspace.ResourceLocation normalize() ,public abstract me.coley.recaf.workspace.ResourceLocation toAbsolute() ,public abstract java.lang.String toString() <variables>private final non-sealed me.coley.recaf.workspace.ResourceKind kind
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/RuoYiApplication.java
RuoYiApplication
main
class RuoYiApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// System.setProperty("spring.devtools.restart.enabled", "false"); SpringApplication.run(RuoYiApplication.class, args); System.out.println("(♥◠‿◠)ノ゙ 若依启动成功 ლ(´ڡ`ლ)゙ \n" + " .-------. ____ __ \n" + " | _ _ \\ \\ \\ / / \n" + " | ( ' ) | \\ _. / ' \n" + " |(_ o _) / _( )_ .' \n" + " | (_,_).' __ ___(_ o _)' \n" + " | |\\ \\ | || |(_,_)' \n" + " | | \\ `' /| `-' / \n" + " | | \\ / \\ / \n" + " ''-' `'-' `-..-' ");
41
284
325
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CaptchaController.java
CaptchaController
getCode
class CaptchaController { @Resource(name = "captchaProducer") private Producer captchaProducer; @Resource(name = "captchaProducerMath") private Producer captchaProducerMath; @Autowired private RedisCache redisCache; @Autowired private ISysConfigService configService; /** * 生成验证码 */ @GetMapping("/captchaImage") public AjaxResult getCode(HttpServletResponse response) throws IOException {<FILL_FUNCTION_BODY>} }
AjaxResult ajax = AjaxResult.success(); boolean captchaEnabled = configService.selectCaptchaEnabled(); ajax.put("captchaEnabled", captchaEnabled); if (!captchaEnabled) { return ajax; } // 保存验证码信息 String uuid = IdUtils.simpleUUID(); String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; String capStr = null, code = null; BufferedImage image = null; // 生成验证码 String captchaType = RuoYiConfig.getCaptchaType(); if ("math".equals(captchaType)) { String capText = captchaProducerMath.createText(); capStr = capText.substring(0, capText.lastIndexOf("@")); code = capText.substring(capText.lastIndexOf("@") + 1); image = captchaProducerMath.createImage(capStr); } else if ("char".equals(captchaType)) { capStr = code = captchaProducer.createText(); image = captchaProducer.createImage(capStr); } redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES); // 转换流信息写出 FastByteArrayOutputStream os = new FastByteArrayOutputStream(); try { ImageIO.write(image, "jpg", os); } catch (IOException e) { return AjaxResult.error(e.getMessage()); } ajax.put("uuid", uuid); ajax.put("img", Base64.encode(os.toByteArray())); return ajax;
169
501
670
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/common/CommonController.java
CommonController
uploadFile
class CommonController { private static final Logger log = LoggerFactory.getLogger(CommonController.class); @Autowired private ServerConfig serverConfig; private static final String FILE_DELIMETER = ","; /** * 通用下载请求 * * @param fileName 文件名称 * @param delete 是否删除 */ @GetMapping("/download") public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) { try { if (!FileUtils.checkAllowDownload(fileName)) { throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName)); } String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1); String filePath = RuoYiConfig.getDownloadPath() + fileName; response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); FileUtils.setAttachmentResponseHeader(response, realFileName); FileUtils.writeBytes(filePath, response.getOutputStream()); if (delete) { FileUtils.deleteFile(filePath); } } catch (Exception e) { log.error("下载文件失败", e); } } /** * 通用上传请求(单个) */ @PostMapping("/upload") public AjaxResult uploadFile(MultipartFile file) throws Exception {<FILL_FUNCTION_BODY>} /** * 通用上传请求(多个) */ @PostMapping("/uploads") public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception { try { // 上传文件路径 String filePath = RuoYiConfig.getUploadPath(); List<String> urls = new ArrayList<String>(); List<String> fileNames = new ArrayList<String>(); List<String> newFileNames = new ArrayList<String>(); List<String> originalFilenames = new ArrayList<String>(); for (MultipartFile file : files) { // 上传并返回新文件名称 String fileName = FileUploadUtils.upload(filePath, file); String url = serverConfig.getUrl() + fileName; urls.add(url); fileNames.add(fileName); newFileNames.add(FileUtils.getName(fileName)); originalFilenames.add(file.getOriginalFilename()); } AjaxResult ajax = AjaxResult.success(); ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER)); ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER)); ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER)); ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER)); return ajax; } catch (Exception e) { return AjaxResult.error(e.getMessage()); } } /** * 本地资源通用下载 */ @GetMapping("/download/resource") public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (!FileUtils.checkAllowDownload(resource)) { throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource)); } // 本地资源路径 String localPath = RuoYiConfig.getProfile(); // 数据库资源地址 String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX); // 下载名称 String downloadName = StringUtils.substringAfterLast(downloadPath, "/"); response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); FileUtils.setAttachmentResponseHeader(response, downloadName); FileUtils.writeBytes(downloadPath, response.getOutputStream()); } catch (Exception e) { log.error("下载文件失败", e); } } }
try { // 上传文件路径 String filePath = RuoYiConfig.getUploadPath(); // 上传并返回新文件名称 String fileName = FileUploadUtils.upload(filePath, file); String url = serverConfig.getUrl() + fileName; AjaxResult ajax = AjaxResult.success(); ajax.put("url", url); ajax.put("fileName", fileName); ajax.put("newFileName", FileUtils.getName(fileName)); ajax.put("originalFilename", file.getOriginalFilename()); return ajax; } catch (Exception e) { return AjaxResult.error(e.getMessage()); }
1,230
207
1,437
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/CacheController.java
CacheController
getInfo
class CacheController { @Autowired private RedisTemplate<String, String> redisTemplate; private final static List<SysCache> caches = new ArrayList<SysCache>(); { caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息")); caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息")); caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典")); caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码")); caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交")); caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理")); caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数")); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @GetMapping() public AjaxResult getInfo() throws Exception {<FILL_FUNCTION_BODY>} @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @GetMapping("/getNames") public AjaxResult cache() { return AjaxResult.success(caches); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @GetMapping("/getKeys/{cacheName}") public AjaxResult getCacheKeys(@PathVariable String cacheName) { Set<String> cacheKeys = redisTemplate.keys(cacheName + "*"); return AjaxResult.success(cacheKeys); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @GetMapping("/getValue/{cacheName}/{cacheKey}") public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) { String cacheValue = redisTemplate.opsForValue().get(cacheKey); SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue); return AjaxResult.success(sysCache); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @DeleteMapping("/clearCacheName/{cacheName}") public AjaxResult clearCacheName(@PathVariable String cacheName) { Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*"); redisTemplate.delete(cacheKeys); return AjaxResult.success(); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @DeleteMapping("/clearCacheKey/{cacheKey}") public AjaxResult clearCacheKey(@PathVariable String cacheKey) { redisTemplate.delete(cacheKey); return AjaxResult.success(); } @PreAuthorize("@ss.hasPermi('monitor:cache:list')") @DeleteMapping("/clearCacheAll") public AjaxResult clearCacheAll() { Collection<String> cacheKeys = redisTemplate.keys("*"); redisTemplate.delete(cacheKeys); return AjaxResult.success(); } }
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info()); Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats")); Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize()); Map<String, Object> result = new HashMap<>(3); result.put("info", info); result.put("dbSize", dbSize); List<Map<String, String>> pieList = new ArrayList<>(); commandStats.stringPropertyNames().forEach(key -> { Map<String, String> data = new HashMap<>(2); String property = commandStats.getProperty(key); data.put("name", StringUtils.removeStart(key, "cmdstat_")); data.put("value", StringUtils.substringBetween(property, "calls=", ",usec")); pieList.add(data); }); result.put("commandStats", pieList); return AjaxResult.success(result);
913
295
1,208
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysLogininforController.java
SysLogininforController
export
class SysLogininforController extends BaseController { @Autowired private ISysLogininforService logininforService; @Autowired private SysPasswordService passwordService; @PreAuthorize("@ss.hasPermi('monitor:logininfor:list')") @GetMapping("/list") public TableDataInfo list(SysLogininfor logininfor) { startPage(); List<SysLogininfor> list = logininforService.selectLogininforList(logininfor); return getDataTable(list); } @Log(title = "登录日志", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('monitor:logininfor:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysLogininfor logininfor) {<FILL_FUNCTION_BODY>} @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')") @Log(title = "登录日志", businessType = BusinessType.DELETE) @DeleteMapping("/{infoIds}") public AjaxResult remove(@PathVariable Long[] infoIds) { return toAjax(logininforService.deleteLogininforByIds(infoIds)); } @PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')") @Log(title = "登录日志", businessType = BusinessType.CLEAN) @DeleteMapping("/clean") public AjaxResult clean() { logininforService.cleanLogininfor(); return success(); } @PreAuthorize("@ss.hasPermi('monitor:logininfor:unlock')") @Log(title = "账户解锁", businessType = BusinessType.OTHER) @GetMapping("/unlock/{userName}") public AjaxResult unlock(@PathVariable("userName") String userName) { passwordService.clearLoginRecordCache(userName); return success(); } }
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor); ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class); util.exportExcel(response, list, "登录日志");
570
84
654
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysOperlogController.java
SysOperlogController
export
class SysOperlogController extends BaseController { @Autowired private ISysOperLogService operLogService; @PreAuthorize("@ss.hasPermi('monitor:operlog:list')") @GetMapping("/list") public TableDataInfo list(SysOperLog operLog) { startPage(); List<SysOperLog> list = operLogService.selectOperLogList(operLog); return getDataTable(list); } @Log(title = "操作日志", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('monitor:operlog:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysOperLog operLog) {<FILL_FUNCTION_BODY>} @Log(title = "操作日志", businessType = BusinessType.DELETE) @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')") @DeleteMapping("/{operIds}") public AjaxResult remove(@PathVariable Long[] operIds) { return toAjax(operLogService.deleteOperLogByIds(operIds)); } @Log(title = "操作日志", businessType = BusinessType.CLEAN) @PreAuthorize("@ss.hasPermi('monitor:operlog:remove')") @DeleteMapping("/clean") public AjaxResult clean() { operLogService.cleanOperLog(); return success(); } }
List<SysOperLog> list = operLogService.selectOperLogList(operLog); ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class); util.exportExcel(response, list, "操作日志");
420
76
496
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/monitor/SysUserOnlineController.java
SysUserOnlineController
list
class SysUserOnlineController extends BaseController { @Autowired private ISysUserOnlineService userOnlineService; @Autowired private RedisCache redisCache; @PreAuthorize("@ss.hasPermi('monitor:online:list')") @GetMapping("/list") public TableDataInfo list(String ipaddr, String userName) {<FILL_FUNCTION_BODY>} /** * 强退用户 */ @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')") @Log(title = "在线用户", businessType = BusinessType.FORCE) @DeleteMapping("/{tokenId}") public AjaxResult forceLogout(@PathVariable String tokenId) { redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId); return success(); } }
Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*"); List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>(); for (String key : keys) { LoginUser user = redisCache.getCacheObject(key); if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) { userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user)); } else if (StringUtils.isNotEmpty(ipaddr)) { userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user)); } else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) { userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user)); } else { userOnlineList.add(userOnlineService.loginUserToUserOnline(user)); } } Collections.reverse(userOnlineList); userOnlineList.removeAll(Collections.singleton(null)); return getDataTable(userOnlineList);
253
336
589
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysConfigController.java
SysConfigController
add
class SysConfigController extends BaseController { @Autowired private ISysConfigService configService; /** * 获取参数配置列表 */ @PreAuthorize("@ss.hasPermi('system:config:list')") @GetMapping("/list") public TableDataInfo list(SysConfig config) { startPage(); List<SysConfig> list = configService.selectConfigList(config); return getDataTable(list); } @Log(title = "参数管理", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:config:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysConfig config) { List<SysConfig> list = configService.selectConfigList(config); ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class); util.exportExcel(response, list, "参数数据"); } /** * 根据参数编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('system:config:query')") @GetMapping(value = "/{configId}") public AjaxResult getInfo(@PathVariable Long configId) { return success(configService.selectConfigById(configId)); } /** * 根据参数键名查询参数值 */ @GetMapping(value = "/configKey/{configKey}") public AjaxResult getConfigKey(@PathVariable String configKey) { return success(configService.selectConfigByKey(configKey)); } /** * 新增参数配置 */ @PreAuthorize("@ss.hasPermi('system:config:add')") @Log(title = "参数管理", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysConfig config) {<FILL_FUNCTION_BODY>} /** * 修改参数配置 */ @PreAuthorize("@ss.hasPermi('system:config:edit')") @Log(title = "参数管理", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysConfig config) { if (!configService.checkConfigKeyUnique(config)) { return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); } config.setUpdateBy(getUsername()); return toAjax(configService.updateConfig(config)); } /** * 删除参数配置 */ @PreAuthorize("@ss.hasPermi('system:config:remove')") @Log(title = "参数管理", businessType = BusinessType.DELETE) @DeleteMapping("/{configIds}") public AjaxResult remove(@PathVariable Long[] configIds) { configService.deleteConfigByIds(configIds); return success(); } /** * 刷新参数缓存 */ @PreAuthorize("@ss.hasPermi('system:config:remove')") @Log(title = "参数管理", businessType = BusinessType.CLEAN) @DeleteMapping("/refreshCache") public AjaxResult refreshCache() { configService.resetConfigCache(); return success(); } }
if (!configService.checkConfigKeyUnique(config)) { return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); } config.setCreateBy(getUsername()); return toAjax(configService.insertConfig(config));
968
83
1,051
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDeptController.java
SysDeptController
excludeChild
class SysDeptController extends BaseController { @Autowired private ISysDeptService deptService; /** * 获取部门列表 */ @PreAuthorize("@ss.hasPermi('system:dept:list')") @GetMapping("/list") public AjaxResult list(SysDept dept) { List<SysDept> depts = deptService.selectDeptList(dept); return success(depts); } /** * 查询部门列表(排除节点) */ @PreAuthorize("@ss.hasPermi('system:dept:list')") @GetMapping("/list/exclude/{deptId}") public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {<FILL_FUNCTION_BODY>} /** * 根据部门编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('system:dept:query')") @GetMapping(value = "/{deptId}") public AjaxResult getInfo(@PathVariable Long deptId) { deptService.checkDeptDataScope(deptId); return success(deptService.selectDeptById(deptId)); } /** * 新增部门 */ @PreAuthorize("@ss.hasPermi('system:dept:add')") @Log(title = "部门管理", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysDept dept) { if (!deptService.checkDeptNameUnique(dept)) { return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); } dept.setCreateBy(getUsername()); return toAjax(deptService.insertDept(dept)); } /** * 修改部门 */ @PreAuthorize("@ss.hasPermi('system:dept:edit')") @Log(title = "部门管理", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysDept dept) { Long deptId = dept.getDeptId(); deptService.checkDeptDataScope(deptId); if (!deptService.checkDeptNameUnique(dept)) { return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); } else if (dept.getParentId().equals(deptId)) { return error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己"); } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) { return error("该部门包含未停用的子部门!"); } dept.setUpdateBy(getUsername()); return toAjax(deptService.updateDept(dept)); } /** * 删除部门 */ @PreAuthorize("@ss.hasPermi('system:dept:remove')") @Log(title = "部门管理", businessType = BusinessType.DELETE) @DeleteMapping("/{deptId}") public AjaxResult remove(@PathVariable Long deptId) { if (deptService.hasChildByDeptId(deptId)) { return warn("存在下级部门,不允许删除"); } if (deptService.checkDeptExistUser(deptId)) { return warn("部门存在用户,不允许删除"); } deptService.checkDeptDataScope(deptId); return toAjax(deptService.deleteDeptById(deptId)); } }
List<SysDept> depts = deptService.selectDeptList(new SysDept()); depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")); return success(depts);
1,133
98
1,231
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictDataController.java
SysDictDataController
dictType
class SysDictDataController extends BaseController { @Autowired private ISysDictDataService dictDataService; @Autowired private ISysDictTypeService dictTypeService; @PreAuthorize("@ss.hasPermi('system:dict:list')") @GetMapping("/list") public TableDataInfo list(SysDictData dictData) { startPage(); List<SysDictData> list = dictDataService.selectDictDataList(dictData); return getDataTable(list); } @Log(title = "字典数据", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:dict:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysDictData dictData) { List<SysDictData> list = dictDataService.selectDictDataList(dictData); ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class); util.exportExcel(response, list, "字典数据"); } /** * 查询字典数据详细 */ @PreAuthorize("@ss.hasPermi('system:dict:query')") @GetMapping(value = "/{dictCode}") public AjaxResult getInfo(@PathVariable Long dictCode) { return success(dictDataService.selectDictDataById(dictCode)); } /** * 根据字典类型查询字典数据信息 */ @GetMapping(value = "/type/{dictType}") public AjaxResult dictType(@PathVariable String dictType) {<FILL_FUNCTION_BODY>} /** * 新增字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:add')") @Log(title = "字典数据", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysDictData dict) { dict.setCreateBy(getUsername()); return toAjax(dictDataService.insertDictData(dict)); } /** * 修改保存字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:edit')") @Log(title = "字典数据", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysDictData dict) { dict.setUpdateBy(getUsername()); return toAjax(dictDataService.updateDictData(dict)); } /** * 删除字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:remove')") @Log(title = "字典类型", businessType = BusinessType.DELETE) @DeleteMapping("/{dictCodes}") public AjaxResult remove(@PathVariable Long[] dictCodes) { dictDataService.deleteDictDataByIds(dictCodes); return success(); } }
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType); if (StringUtils.isNull(data)) { data = new ArrayList<SysDictData>(); } return success(data);
882
75
957
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysDictTypeController.java
SysDictTypeController
export
class SysDictTypeController extends BaseController { @Autowired private ISysDictTypeService dictTypeService; @PreAuthorize("@ss.hasPermi('system:dict:list')") @GetMapping("/list") public TableDataInfo list(SysDictType dictType) { startPage(); List<SysDictType> list = dictTypeService.selectDictTypeList(dictType); return getDataTable(list); } @Log(title = "字典类型", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:dict:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysDictType dictType) {<FILL_FUNCTION_BODY>} /** * 查询字典类型详细 */ @PreAuthorize("@ss.hasPermi('system:dict:query')") @GetMapping(value = "/{dictId}") public AjaxResult getInfo(@PathVariable Long dictId) { return success(dictTypeService.selectDictTypeById(dictId)); } /** * 新增字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:add')") @Log(title = "字典类型", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysDictType dict) { if (!dictTypeService.checkDictTypeUnique(dict)) { return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); } dict.setCreateBy(getUsername()); return toAjax(dictTypeService.insertDictType(dict)); } /** * 修改字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:edit')") @Log(title = "字典类型", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysDictType dict) { if (!dictTypeService.checkDictTypeUnique(dict)) { return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); } dict.setUpdateBy(getUsername()); return toAjax(dictTypeService.updateDictType(dict)); } /** * 删除字典类型 */ @PreAuthorize("@ss.hasPermi('system:dict:remove')") @Log(title = "字典类型", businessType = BusinessType.DELETE) @DeleteMapping("/{dictIds}") public AjaxResult remove(@PathVariable Long[] dictIds) { dictTypeService.deleteDictTypeByIds(dictIds); return success(); } /** * 刷新字典缓存 */ @PreAuthorize("@ss.hasPermi('system:dict:remove')") @Log(title = "字典类型", businessType = BusinessType.CLEAN) @DeleteMapping("/refreshCache") public AjaxResult refreshCache() { dictTypeService.resetDictCache(); return success(); } /** * 获取字典选择框列表 */ @GetMapping("/optionselect") public AjaxResult optionselect() { List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll(); return success(dictTypes); } }
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType); ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class); util.exportExcel(response, list, "字典类型");
1,017
81
1,098
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java
SysLoginController
getInfo
class SysLoginController { @Autowired private SysLoginService loginService; @Autowired private ISysMenuService menuService; @Autowired private SysPermissionService permissionService; /** * 登录方法 * * @param loginBody 登录信息 * @return 结果 */ @PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); // 生成令牌 String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid()); ajax.put(Constants.TOKEN, token); return ajax; } /** * 获取用户信息 * * @return 用户信息 */ @GetMapping("getInfo") public AjaxResult getInfo() {<FILL_FUNCTION_BODY>} /** * 获取路由信息 * * @return 路由信息 */ @GetMapping("getRouters") public AjaxResult getRouters() { Long userId = SecurityUtils.getUserId(); List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId); return AjaxResult.success(menuService.buildMenus(menus)); } }
SysUser user = SecurityUtils.getLoginUser().getUser(); // 角色集合 Set<String> roles = permissionService.getRolePermission(user); // 权限集合 Set<String> permissions = permissionService.getMenuPermission(user); AjaxResult ajax = AjaxResult.success(); ajax.put("user", user); ajax.put("roles", roles); ajax.put("permissions", permissions); return ajax;
426
135
561
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysMenuController.java
SysMenuController
remove
class SysMenuController extends BaseController { @Autowired private ISysMenuService menuService; /** * 获取菜单列表 */ @PreAuthorize("@ss.hasPermi('system:menu:list')") @GetMapping("/list") public AjaxResult list(SysMenu menu) { List<SysMenu> menus = menuService.selectMenuList(menu, getUserId()); return success(menus); } /** * 根据菜单编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('system:menu:query')") @GetMapping(value = "/{menuId}") public AjaxResult getInfo(@PathVariable Long menuId) { return success(menuService.selectMenuById(menuId)); } /** * 获取菜单下拉树列表 */ @GetMapping("/treeselect") public AjaxResult treeselect(SysMenu menu) { List<SysMenu> menus = menuService.selectMenuList(menu, getUserId()); return success(menuService.buildMenuTreeSelect(menus)); } /** * 加载对应角色菜单列表树 */ @GetMapping(value = "/roleMenuTreeselect/{roleId}") public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) { List<SysMenu> menus = menuService.selectMenuList(getUserId()); AjaxResult ajax = AjaxResult.success(); ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId)); ajax.put("menus", menuService.buildMenuTreeSelect(menus)); return ajax; } /** * 新增菜单 */ @PreAuthorize("@ss.hasPermi('system:menu:add')") @Log(title = "菜单管理", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysMenu menu) { if (!menuService.checkMenuNameUnique(menu)) { return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { return error("新增菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); } menu.setCreateBy(getUsername()); return toAjax(menuService.insertMenu(menu)); } /** * 修改菜单 */ @PreAuthorize("@ss.hasPermi('system:menu:edit')") @Log(title = "菜单管理", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysMenu menu) { if (!menuService.checkMenuNameUnique(menu)) { return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.ishttp(menu.getPath())) { return error("修改菜单'" + menu.getMenuName() + "'失败,地址必须以http(s)://开头"); } else if (menu.getMenuId().equals(menu.getParentId())) { return error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己"); } menu.setUpdateBy(getUsername()); return toAjax(menuService.updateMenu(menu)); } /** * 删除菜单 */ @PreAuthorize("@ss.hasPermi('system:menu:remove')") @Log(title = "菜单管理", businessType = BusinessType.DELETE) @DeleteMapping("/{menuId}") public AjaxResult remove(@PathVariable("menuId") Long menuId) {<FILL_FUNCTION_BODY>} }
if (menuService.hasChildByMenuId(menuId)) { return warn("存在子菜单,不允许删除"); } if (menuService.checkMenuExistRole(menuId)) { return warn("菜单已分配,不允许删除"); } return toAjax(menuService.deleteMenuById(menuId));
1,178
104
1,282
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysPostController.java
SysPostController
edit
class SysPostController extends BaseController { @Autowired private ISysPostService postService; /** * 获取岗位列表 */ @PreAuthorize("@ss.hasPermi('system:post:list')") @GetMapping("/list") public TableDataInfo list(SysPost post) { startPage(); List<SysPost> list = postService.selectPostList(post); return getDataTable(list); } @Log(title = "岗位管理", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:post:export')") @PostMapping("/export") public void export(HttpServletResponse response, SysPost post) { List<SysPost> list = postService.selectPostList(post); ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class); util.exportExcel(response, list, "岗位数据"); } /** * 根据岗位编号获取详细信息 */ @PreAuthorize("@ss.hasPermi('system:post:query')") @GetMapping(value = "/{postId}") public AjaxResult getInfo(@PathVariable Long postId) { return success(postService.selectPostById(postId)); } /** * 新增岗位 */ @PreAuthorize("@ss.hasPermi('system:post:add')") @Log(title = "岗位管理", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysPost post) { if (!postService.checkPostNameUnique(post)) { return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在"); } else if (!postService.checkPostCodeUnique(post)) { return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } post.setCreateBy(getUsername()); return toAjax(postService.insertPost(post)); } /** * 修改岗位 */ @PreAuthorize("@ss.hasPermi('system:post:edit')") @Log(title = "岗位管理", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody SysPost post) {<FILL_FUNCTION_BODY>} /** * 删除岗位 */ @PreAuthorize("@ss.hasPermi('system:post:remove')") @Log(title = "岗位管理", businessType = BusinessType.DELETE) @DeleteMapping("/{postIds}") public AjaxResult remove(@PathVariable Long[] postIds) { return toAjax(postService.deletePostByIds(postIds)); } /** * 获取岗位选择框列表 */ @GetMapping("/optionselect") public AjaxResult optionselect() { List<SysPost> posts = postService.selectPostAll(); return success(posts); } }
if (!postService.checkPostNameUnique(post)) { return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在"); } else if (!postService.checkPostCodeUnique(post)) { return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } post.setUpdateBy(getUsername()); return toAjax(postService.updatePost(post));
898
136
1,034
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysProfileController.java
SysProfileController
updatePwd
class SysProfileController extends BaseController { @Autowired private ISysUserService userService; @Autowired private TokenService tokenService; /** * 个人信息 */ @GetMapping public AjaxResult profile() { LoginUser loginUser = getLoginUser(); SysUser user = loginUser.getUser(); AjaxResult ajax = AjaxResult.success(user); ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername())); ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername())); return ajax; } /** * 修改用户 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult updateProfile(@RequestBody SysUser user) { LoginUser loginUser = getLoginUser(); SysUser currentUser = loginUser.getUser(); currentUser.setNickName(user.getNickName()); currentUser.setEmail(user.getEmail()); currentUser.setPhonenumber(user.getPhonenumber()); currentUser.setSex(user.getSex()); if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(currentUser)) { return error("修改用户'" + loginUser.getUsername() + "'失败,手机号码已存在"); } if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser)) { return error("修改用户'" + loginUser.getUsername() + "'失败,邮箱账号已存在"); } if (userService.updateUserProfile(currentUser) > 0) { // 更新缓存用户信息 tokenService.setLoginUser(loginUser); return success(); } return error("修改个人信息异常,请联系管理员"); } /** * 重置密码 */ @Log(title = "个人信息", businessType = BusinessType.UPDATE) @PutMapping("/updatePwd") public AjaxResult updatePwd(String oldPassword, String newPassword) {<FILL_FUNCTION_BODY>} /** * 头像上传 */ @Log(title = "用户头像", businessType = BusinessType.UPDATE) @PostMapping("/avatar") public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception { if (!file.isEmpty()) { LoginUser loginUser = getLoginUser(); String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION); if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) { AjaxResult ajax = AjaxResult.success(); ajax.put("imgUrl", avatar); // 更新缓存用户头像 loginUser.getUser().setAvatar(avatar); tokenService.setLoginUser(loginUser); return ajax; } } return error("上传图片异常,请联系管理员"); } }
LoginUser loginUser = getLoginUser(); String userName = loginUser.getUsername(); String password = loginUser.getPassword(); if (!SecurityUtils.matchesPassword(oldPassword, password)) { return error("修改密码失败,旧密码错误"); } if (SecurityUtils.matchesPassword(newPassword, password)) { return error("新密码不能与旧密码相同"); } newPassword = SecurityUtils.encryptPassword(newPassword); if (userService.resetUserPwd(userName, newPassword) > 0) { // 更新缓存用户密码 loginUser.getUser().setPassword(newPassword); tokenService.setLoginUser(loginUser); return success(); } return error("修改密码异常,请联系管理员");
924
233
1,157
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysRegisterController.java
SysRegisterController
register
class SysRegisterController extends BaseController { @Autowired private SysRegisterService registerService; @Autowired private ISysConfigService configService; @PostMapping("/register") public AjaxResult register(@RequestBody RegisterBody user) {<FILL_FUNCTION_BODY>} }
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) { return error("当前系统没有开启注册功能!"); } String msg = registerService.register(user); return StringUtils.isEmpty(msg) ? success() : error(msg);
95
84
179
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/TestController.java
TestController
getUser
class TestController extends BaseController { private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>(); { users.put(1, new UserEntity(1, "admin", "admin123", "15888888888")); users.put(2, new UserEntity(2, "ry", "admin123", "15666666666")); } @ApiOperation("获取用户列表") @GetMapping("/list") public R<List<UserEntity>> userList() { List<UserEntity> userList = new ArrayList<UserEntity>(users.values()); return R.ok(userList); } @ApiOperation("获取用户详细") @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class) @GetMapping("/{userId}") public R<UserEntity> getUser(@PathVariable Integer userId) {<FILL_FUNCTION_BODY>} @ApiOperation("新增用户") @ApiImplicitParams({ @ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class), @ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class), @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class), @ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class) }) @PostMapping("/save") public R<String> save(UserEntity user) { if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) { return R.fail("用户ID不能为空"); } users.put(user.getUserId(), user); return R.ok(); } @ApiOperation("更新用户") @PutMapping("/update") public R<String> update(@RequestBody UserEntity user) { if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) { return R.fail("用户ID不能为空"); } if (users.isEmpty() || !users.containsKey(user.getUserId())) { return R.fail("用户不存在"); } users.remove(user.getUserId()); users.put(user.getUserId(), user); return R.ok(); } @ApiOperation("删除用户信息") @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class) @DeleteMapping("/{userId}") public R<String> delete(@PathVariable Integer userId) { if (!users.isEmpty() && users.containsKey(userId)) { users.remove(userId); return R.ok(); } else { return R.fail("用户不存在"); } } }
if (!users.isEmpty() && users.containsKey(userId)) { return R.ok(users.get(userId)); } else { return R.fail("用户不存在"); }
903
69
972
<methods>public non-sealed void <init>() ,public com.ruoyi.common.core.domain.AjaxResult error() ,public com.ruoyi.common.core.domain.AjaxResult error(java.lang.String) ,public java.lang.Long getDeptId() ,public com.ruoyi.common.core.domain.model.LoginUser getLoginUser() ,public java.lang.Long getUserId() ,public java.lang.String getUsername() ,public void initBinder(org.springframework.web.bind.WebDataBinder) ,public java.lang.String redirect(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success() ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.String) ,public com.ruoyi.common.core.domain.AjaxResult success(java.lang.Object) ,public com.ruoyi.common.core.domain.AjaxResult warn(java.lang.String) <variables>protected final org.slf4j.Logger logger
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-admin/src/main/java/com/ruoyi/web/core/config/SwaggerConfig.java
SwaggerConfig
securitySchemes
class SwaggerConfig { /** 系统基础配置 */ @Autowired private RuoYiConfig ruoyiConfig; /** 是否开启swagger */ @Value("${swagger.enabled}") private boolean enabled; /** 设置请求的统一前缀 */ @Value("${swagger.pathMapping}") private String pathMapping; /** * 创建API */ @Bean public Docket createRestApi() { return new Docket(DocumentationType.OAS_30) // 是否启用Swagger .enable(enabled) // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) .apiInfo(apiInfo()) // 设置哪些接口暴露给Swagger展示 .select() // 扫描所有有注解的api,用这种方式更灵活 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) // 扫描指定包中的swagger注解 // .apis(RequestHandlerSelectors.basePackage("com.ruoyi.project.tool.swagger")) // 扫描所有 .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() /* 设置安全模式,swagger可以设置访问token */ .securitySchemes(securitySchemes()) .securityContexts(securityContexts()) .pathMapping(pathMapping); } /** * 安全模式,这里指定token通过Authorization头请求头传递 */ private List<SecurityScheme> securitySchemes() {<FILL_FUNCTION_BODY>} /** * 安全上下文 */ private List<SecurityContext> securityContexts() { List<SecurityContext> securityContexts = new ArrayList<>(); securityContexts.add( SecurityContext.builder() .securityReferences(defaultAuth()) .operationSelector(o -> o.requestMappingPattern().matches("/.*")) .build()); return securityContexts; } /** * 默认的安全上引用 */ private List<SecurityReference> defaultAuth() { AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; List<SecurityReference> securityReferences = new ArrayList<>(); securityReferences.add(new SecurityReference("Authorization", authorizationScopes)); return securityReferences; } /** * 添加摘要信息 */ private ApiInfo apiInfo() { // 用ApiInfoBuilder进行定制 return new ApiInfoBuilder() // 设置标题 .title("标题:若依管理系统_接口文档") // 描述 .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...") // 作者信息 .contact(new Contact(ruoyiConfig.getName(), null, null)) // 版本 .version("版本号:" + ruoyiConfig.getVersion()) .build(); } }
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>(); apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue())); return apiKeyList;
921
62
983
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/config/serializer/SensitiveJsonSerializer.java
SensitiveJsonSerializer
createContextual
class SensitiveJsonSerializer extends JsonSerializer<String> implements ContextualSerializer { private DesensitizedType desensitizedType; @Override public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException { if (desensitization()) { gen.writeString(desensitizedType.desensitizer().apply(value)); } else { gen.writeString(value); } } @Override public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {<FILL_FUNCTION_BODY>} /** * 是否需要脱敏处理 */ private boolean desensitization() { try { LoginUser securityUser = SecurityUtils.getLoginUser(); // 管理员不脱敏 return !securityUser.getUser().isAdmin(); } catch (Exception e) { return true; } } }
Sensitive annotation = property.getAnnotation(Sensitive.class); if (Objects.nonNull(annotation) && Objects.equals(String.class, property.getType().getRawClass())) { this.desensitizedType = annotation.desensitizedType(); return this; } return prov.findValueSerializer(property.getType(), property);
263
94
357
<methods>public void <init>() ,public void acceptJsonFormatVisitor(com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper, com.fasterxml.jackson.databind.JavaType) throws com.fasterxml.jackson.databind.JsonMappingException,public JsonSerializer<?> getDelegatee() ,public Class<java.lang.String> handledType() ,public boolean isEmpty(java.lang.String) ,public boolean isEmpty(com.fasterxml.jackson.databind.SerializerProvider, java.lang.String) ,public boolean isUnwrappingSerializer() ,public Iterator<com.fasterxml.jackson.databind.ser.PropertyWriter> properties() ,public JsonSerializer<java.lang.String> replaceDelegatee(JsonSerializer<?>) ,public abstract void serialize(java.lang.String, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider) throws java.io.IOException,public void serializeWithType(java.lang.String, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider, com.fasterxml.jackson.databind.jsontype.TypeSerializer) throws java.io.IOException,public JsonSerializer<java.lang.String> unwrappingSerializer(com.fasterxml.jackson.databind.util.NameTransformer) ,public boolean usesObjectId() ,public JsonSerializer<?> withFilterId(java.lang.Object) <variables>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/controller/BaseController.java
BaseController
startOrderBy
class BaseController { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 将前台传递过来的日期格式的字符串,自动转化为Date类型 */ @InitBinder public void initBinder(WebDataBinder binder) { // Date 类型转换 binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { @Override public void setAsText(String text) { setValue(DateUtils.parseDate(text)); } }); } /** * 设置请求分页数据 */ protected void startPage() { PageUtils.startPage(); } /** * 设置请求排序数据 */ protected void startOrderBy() {<FILL_FUNCTION_BODY>} /** * 清理分页的线程变量 */ protected void clearPage() { PageUtils.clearPage(); } /** * 响应请求分页数据 */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected TableDataInfo getDataTable(List<?> list) { TableDataInfo rspData = new TableDataInfo(); rspData.setCode(HttpStatus.SUCCESS); rspData.setMsg("查询成功"); rspData.setRows(list); rspData.setTotal(new PageInfo(list).getTotal()); return rspData; } /** * 返回成功 */ public AjaxResult success() { return AjaxResult.success(); } /** * 返回失败消息 */ public AjaxResult error() { return AjaxResult.error(); } /** * 返回成功消息 */ public AjaxResult success(String message) { return AjaxResult.success(message); } /** * 返回成功消息 */ public AjaxResult success(Object data) { return AjaxResult.success(data); } /** * 返回失败消息 */ public AjaxResult error(String message) { return AjaxResult.error(message); } /** * 返回警告消息 */ public AjaxResult warn(String message) { return AjaxResult.warn(message); } /** * 响应返回结果 * * @param rows 影响行数 * @return 操作结果 */ protected AjaxResult toAjax(int rows) { return rows > 0 ? AjaxResult.success() : AjaxResult.error(); } /** * 响应返回结果 * * @param result 结果 * @return 操作结果 */ protected AjaxResult toAjax(boolean result) { return result ? success() : error(); } /** * 页面跳转 */ public String redirect(String url) { return StringUtils.format("redirect:{}", url); } /** * 获取用户缓存信息 */ public LoginUser getLoginUser() { return SecurityUtils.getLoginUser(); } /** * 获取登录用户id */ public Long getUserId() { return getLoginUser().getUserId(); } /** * 获取登录部门id */ public Long getDeptId() { return getLoginUser().getDeptId(); } /** * 获取登录用户名 */ public String getUsername() { return getLoginUser().getUsername(); } }
PageDomain pageDomain = TableSupport.buildPageRequest(); if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) { String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); PageHelper.orderBy(orderBy); }
1,172
80
1,252
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/BaseEntity.java
BaseEntity
getParams
class BaseEntity implements Serializable { private static final long serialVersionUID = 1L; /** 搜索值 */ @JsonIgnore private String searchValue; /** 创建者 */ private String createBy; /** 创建时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** 更新者 */ private String updateBy; /** 更新时间 */ @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; /** 备注 */ private String remark; /** 请求参数 */ @JsonInclude(JsonInclude.Include.NON_EMPTY) private Map<String, Object> params; public String getSearchValue() { return searchValue; } public void setSearchValue(String searchValue) { this.searchValue = searchValue; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getUpdateBy() { return updateBy; } public void setUpdateBy(String updateBy) { this.updateBy = updateBy; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Map<String, Object> getParams() {<FILL_FUNCTION_BODY>} public void setParams(Map<String, Object> params) { this.params = params; } }
if (params == null) { params = new HashMap<>(); } return params;
652
37
689
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/R.java
R
restResult
class R<T> implements Serializable { private static final long serialVersionUID = 1L; /** 成功 */ public static final int SUCCESS = HttpStatus.SUCCESS; /** 失败 */ public static final int FAIL = HttpStatus.ERROR; private int code; private String msg; private T data; public static <T> R<T> ok() { return restResult(null, SUCCESS, "操作成功"); } public static <T> R<T> ok(T data) { return restResult(data, SUCCESS, "操作成功"); } public static <T> R<T> ok(T data, String msg) { return restResult(data, SUCCESS, msg); } public static <T> R<T> fail() { return restResult(null, FAIL, "操作失败"); } public static <T> R<T> fail(String msg) { return restResult(null, FAIL, msg); } public static <T> R<T> fail(T data) { return restResult(data, FAIL, "操作失败"); } public static <T> R<T> fail(T data, String msg) { return restResult(data, FAIL, msg); } public static <T> R<T> fail(int code, String msg) { return restResult(null, code, msg); } private static <T> R<T> restResult(T data, int code, String msg) {<FILL_FUNCTION_BODY>} public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } public static <T> Boolean isError(R<T> ret) { return !isSuccess(ret); } public static <T> Boolean isSuccess(R<T> ret) { return R.SUCCESS == ret.getCode(); } }
R<T> apiResult = new R<>(); apiResult.setCode(code); apiResult.setData(data); apiResult.setMsg(msg); return apiResult;
635
52
687
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDept.java
SysDept
toString
class SysDept extends BaseEntity { private static final long serialVersionUID = 1L; /** 部门ID */ private Long deptId; /** 父部门ID */ private Long parentId; /** 祖级列表 */ private String ancestors; /** 部门名称 */ private String deptName; /** 显示顺序 */ private Integer orderNum; /** 负责人 */ private String leader; /** 联系电话 */ private String phone; /** 邮箱 */ private String email; /** 部门状态:0正常,1停用 */ private String status; /** 删除标志(0代表存在 2代表删除) */ private String delFlag; /** 父部门名称 */ private String parentName; /** 子部门 */ private List<SysDept> children = new ArrayList<SysDept>(); public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getAncestors() { return ancestors; } public void setAncestors(String ancestors) { this.ancestors = ancestors; } @NotBlank(message = "部门名称不能为空") @Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符") public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } @NotNull(message = "显示顺序不能为空") public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } public String getLeader() { return leader; } public void setLeader(String leader) { this.leader = leader; } @Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Email(message = "邮箱格式不正确") @Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDelFlag() { return delFlag; } public void setDelFlag(String delFlag) { this.delFlag = delFlag; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public List<SysDept> getChildren() { return children; } public void setChildren(List<SysDept> children) { this.children = children; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("deptId", getDeptId()) .append("parentId", getParentId()) .append("ancestors", getAncestors()) .append("deptName", getDeptName()) .append("orderNum", getOrderNum()) .append("leader", getLeader()) .append("phone", getPhone()) .append("email", getEmail()) .append("status", getStatus()) .append("delFlag", getDelFlag()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .toString();
1,175
217
1,392
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictData.java
SysDictData
toString
class SysDictData extends BaseEntity { private static final long serialVersionUID = 1L; /** 字典编码 */ @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) private Long dictCode; /** 字典排序 */ @Excel(name = "字典排序", cellType = ColumnType.NUMERIC) private Long dictSort; /** 字典标签 */ @Excel(name = "字典标签") private String dictLabel; /** 字典键值 */ @Excel(name = "字典键值") private String dictValue; /** 字典类型 */ @Excel(name = "字典类型") private String dictType; /** 样式属性(其他样式扩展) */ private String cssClass; /** 表格字典样式 */ private String listClass; /** 是否默认(Y是 N否) */ @Excel(name = "是否默认", readConverterExp = "Y=是,N=否") private String isDefault; /** 状态(0正常 1停用) */ @Excel(name = "状态", readConverterExp = "0=正常,1=停用") private String status; public Long getDictCode() { return dictCode; } public void setDictCode(Long dictCode) { this.dictCode = dictCode; } public Long getDictSort() { return dictSort; } public void setDictSort(Long dictSort) { this.dictSort = dictSort; } @NotBlank(message = "字典标签不能为空") @Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符") public String getDictLabel() { return dictLabel; } public void setDictLabel(String dictLabel) { this.dictLabel = dictLabel; } @NotBlank(message = "字典键值不能为空") @Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符") public String getDictValue() { return dictValue; } public void setDictValue(String dictValue) { this.dictValue = dictValue; } @NotBlank(message = "字典类型不能为空") @Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符") public String getDictType() { return dictType; } public void setDictType(String dictType) { this.dictType = dictType; } @Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符") public String getCssClass() { return cssClass; } public void setCssClass(String cssClass) { this.cssClass = cssClass; } public String getListClass() { return listClass; } public void setListClass(String listClass) { this.listClass = listClass; } public boolean getDefault() { return UserConstants.YES.equals(this.isDefault); } public String getIsDefault() { return isDefault; } public void setIsDefault(String isDefault) { this.isDefault = isDefault; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("dictCode", getDictCode()) .append("dictSort", getDictSort()) .append("dictLabel", getDictLabel()) .append("dictValue", getDictValue()) .append("dictType", getDictType()) .append("cssClass", getCssClass()) .append("listClass", getListClass()) .append("isDefault", getIsDefault()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
1,181
219
1,400
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysDictType.java
SysDictType
toString
class SysDictType extends BaseEntity { private static final long serialVersionUID = 1L; /** 字典主键 */ @Excel(name = "字典主键", cellType = ColumnType.NUMERIC) private Long dictId; /** 字典名称 */ @Excel(name = "字典名称") private String dictName; /** 字典类型 */ @Excel(name = "字典类型") private String dictType; /** 状态(0正常 1停用) */ @Excel(name = "状态", readConverterExp = "0=正常,1=停用") private String status; public Long getDictId() { return dictId; } public void setDictId(Long dictId) { this.dictId = dictId; } @NotBlank(message = "字典名称不能为空") @Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符") public String getDictName() { return dictName; } public void setDictName(String dictName) { this.dictName = dictName; } @NotBlank(message = "字典类型不能为空") @Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符") @Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)") public String getDictType() { return dictType; } public void setDictType(String dictType) { this.dictType = dictType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("dictId", getDictId()) .append("dictName", getDictName()) .append("dictType", getDictType()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
627
151
778
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysMenu.java
SysMenu
toString
class SysMenu extends BaseEntity { private static final long serialVersionUID = 1L; /** 菜单ID */ private Long menuId; /** 菜单名称 */ private String menuName; /** 父菜单名称 */ private String parentName; /** 父菜单ID */ private Long parentId; /** 显示顺序 */ private Integer orderNum; /** 路由地址 */ private String path; /** 组件路径 */ private String component; /** 路由参数 */ private String query; /** 是否为外链(0是 1否) */ private String isFrame; /** 是否缓存(0缓存 1不缓存) */ private String isCache; /** 类型(M目录 C菜单 F按钮) */ private String menuType; /** 显示状态(0显示 1隐藏) */ private String visible; /** 菜单状态(0正常 1停用) */ private String status; /** 权限字符串 */ private String perms; /** 菜单图标 */ private String icon; /** 子菜单 */ private List<SysMenu> children = new ArrayList<SysMenu>(); public Long getMenuId() { return menuId; } public void setMenuId(Long menuId) { this.menuId = menuId; } @NotBlank(message = "菜单名称不能为空") @Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符") public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } @NotNull(message = "显示顺序不能为空") public Integer getOrderNum() { return orderNum; } public void setOrderNum(Integer orderNum) { this.orderNum = orderNum; } @Size(min = 0, max = 200, message = "路由地址不能超过200个字符") public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Size(min = 0, max = 200, message = "组件路径不能超过255个字符") public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getIsFrame() { return isFrame; } public void setIsFrame(String isFrame) { this.isFrame = isFrame; } public String getIsCache() { return isCache; } public void setIsCache(String isCache) { this.isCache = isCache; } @NotBlank(message = "菜单类型不能为空") public String getMenuType() { return menuType; } public void setMenuType(String menuType) { this.menuType = menuType; } public String getVisible() { return visible; } public void setVisible(String visible) { this.visible = visible; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符") public String getPerms() { return perms; } public void setPerms(String perms) { this.perms = perms; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public List<SysMenu> getChildren() { return children; } public void setChildren(List<SysMenu> children) { this.children = children; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("menuId", getMenuId()) .append("menuName", getMenuName()) .append("parentId", getParentId()) .append("orderNum", getOrderNum()) .append("path", getPath()) .append("component", getComponent()) .append("isFrame", getIsFrame()) .append("IsCache", getIsCache()) .append("menuType", getMenuType()) .append("visible", getVisible()) .append("status ", getStatus()) .append("perms", getPerms()) .append("icon", getIcon()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
1,539
257
1,796
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/domain/entity/SysRole.java
SysRole
toString
class SysRole extends BaseEntity { private static final long serialVersionUID = 1L; /** 角色ID */ @Excel(name = "角色序号", cellType = ColumnType.NUMERIC) private Long roleId; /** 角色名称 */ @Excel(name = "角色名称") private String roleName; /** 角色权限 */ @Excel(name = "角色权限") private String roleKey; /** 角色排序 */ @Excel(name = "角色排序") private Integer roleSort; /** 数据范围(1:所有数据权限;2:自定义数据权限;3:本部门数据权限;4:本部门及以下数据权限;5:仅本人数据权限) */ @Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限") private String dataScope; /** 菜单树选择项是否关联显示( 0:父子不互相关联显示 1:父子互相关联显示) */ private boolean menuCheckStrictly; /** 部门树选择项是否关联显示(0:父子不互相关联显示 1:父子互相关联显示 ) */ private boolean deptCheckStrictly; /** 角色状态(0正常 1停用) */ @Excel(name = "角色状态", readConverterExp = "0=正常,1=停用") private String status; /** 删除标志(0代表存在 2代表删除) */ private String delFlag; /** 用户是否存在此角色标识 默认不存在 */ private boolean flag = false; /** 菜单组 */ private Long[] menuIds; /** 部门组(数据权限) */ private Long[] deptIds; /** 角色菜单权限 */ private Set<String> permissions; public SysRole() { } public SysRole(Long roleId) { this.roleId = roleId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public boolean isAdmin() { return isAdmin(this.roleId); } public static boolean isAdmin(Long roleId) { return roleId != null && 1L == roleId; } @NotBlank(message = "角色名称不能为空") @Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符") public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } @NotBlank(message = "权限字符不能为空") @Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符") public String getRoleKey() { return roleKey; } public void setRoleKey(String roleKey) { this.roleKey = roleKey; } @NotNull(message = "显示顺序不能为空") public Integer getRoleSort() { return roleSort; } public void setRoleSort(Integer roleSort) { this.roleSort = roleSort; } public String getDataScope() { return dataScope; } public void setDataScope(String dataScope) { this.dataScope = dataScope; } public boolean isMenuCheckStrictly() { return menuCheckStrictly; } public void setMenuCheckStrictly(boolean menuCheckStrictly) { this.menuCheckStrictly = menuCheckStrictly; } public boolean isDeptCheckStrictly() { return deptCheckStrictly; } public void setDeptCheckStrictly(boolean deptCheckStrictly) { this.deptCheckStrictly = deptCheckStrictly; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getDelFlag() { return delFlag; } public void setDelFlag(String delFlag) { this.delFlag = delFlag; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public Long[] getMenuIds() { return menuIds; } public void setMenuIds(Long[] menuIds) { this.menuIds = menuIds; } public Long[] getDeptIds() { return deptIds; } public void setDeptIds(Long[] deptIds) { this.deptIds = deptIds; } public Set<String> getPermissions() { return permissions; } public void setPermissions(Set<String> permissions) { this.permissions = permissions; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("roleId", getRoleId()) .append("roleName", getRoleName()) .append("roleKey", getRoleKey()) .append("roleSort", getRoleSort()) .append("dataScope", getDataScope()) .append("menuCheckStrictly", isMenuCheckStrictly()) .append("deptCheckStrictly", isDeptCheckStrictly()) .append("status", getStatus()) .append("delFlag", getDelFlag()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("remark", getRemark()) .toString();
1,679
227
1,906
<methods>public non-sealed void <init>() ,public java.lang.String getCreateBy() ,public java.util.Date getCreateTime() ,public Map<java.lang.String,java.lang.Object> getParams() ,public java.lang.String getRemark() ,public java.lang.String getSearchValue() ,public java.lang.String getUpdateBy() ,public java.util.Date getUpdateTime() ,public void setCreateBy(java.lang.String) ,public void setCreateTime(java.util.Date) ,public void setParams(Map<java.lang.String,java.lang.Object>) ,public void setRemark(java.lang.String) ,public void setSearchValue(java.lang.String) ,public void setUpdateBy(java.lang.String) ,public void setUpdateTime(java.util.Date) <variables>private java.lang.String createBy,private java.util.Date createTime,private Map<java.lang.String,java.lang.Object> params,private java.lang.String remark,private java.lang.String searchValue,private static final long serialVersionUID,private java.lang.String updateBy,private java.util.Date updateTime
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/page/PageDomain.java
PageDomain
setIsAsc
class PageDomain { /** 当前记录起始索引 */ private Integer pageNum; /** 每页显示记录数 */ private Integer pageSize; /** 排序列 */ private String orderByColumn; /** 排序的方向desc或者asc */ private String isAsc = "asc"; /** 分页参数合理化 */ private Boolean reasonable = true; public String getOrderBy() { if (StringUtils.isEmpty(orderByColumn)) { return ""; } return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public String getOrderByColumn() { return orderByColumn; } public void setOrderByColumn(String orderByColumn) { this.orderByColumn = orderByColumn; } public String getIsAsc() { return isAsc; } public void setIsAsc(String isAsc) {<FILL_FUNCTION_BODY>} public Boolean getReasonable() { if (StringUtils.isNull(reasonable)) { return Boolean.TRUE; } return reasonable; } public void setReasonable(Boolean reasonable) { this.reasonable = reasonable; } }
if (StringUtils.isNotEmpty(isAsc)) { // 兼容前端排序类型 if ("ascending".equals(isAsc)) { isAsc = "asc"; } else if ("descending".equals(isAsc)) { isAsc = "desc"; } this.isAsc = isAsc; }
447
104
551
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/page/TableSupport.java
TableSupport
getPageDomain
class TableSupport { /** * 当前记录起始索引 */ public static final String PAGE_NUM = "pageNum"; /** * 每页显示记录数 */ public static final String PAGE_SIZE = "pageSize"; /** * 排序列 */ public static final String ORDER_BY_COLUMN = "orderByColumn"; /** * 排序的方向 "desc" 或者 "asc". */ public static final String IS_ASC = "isAsc"; /** * 分页参数合理化 */ public static final String REASONABLE = "reasonable"; /** * 封装分页对象 */ public static PageDomain getPageDomain() {<FILL_FUNCTION_BODY>} public static PageDomain buildPageRequest() { return getPageDomain(); } }
PageDomain pageDomain = new PageDomain(); pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1)); pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10)); pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN)); pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC)); pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE)); return pageDomain;
275
152
427
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/text/CharsetKit.java
CharsetKit
convert
class CharsetKit { /** ISO-8859-1 */ public static final String ISO_8859_1 = "ISO-8859-1"; /** UTF-8 */ public static final String UTF_8 = "UTF-8"; /** GBK */ public static final String GBK = "GBK"; /** ISO-8859-1 */ public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); /** UTF-8 */ public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); /** GBK */ public static final Charset CHARSET_GBK = Charset.forName(GBK); /** * 转换为Charset对象 * * @param charset 字符集,为空则返回默认字符集 * @return Charset */ public static Charset charset(String charset) { return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); } /** * 转换字符串的字符集编码 * * @param source 字符串 * @param srcCharset 源字符集,默认ISO-8859-1 * @param destCharset 目标字符集,默认UTF-8 * @return 转换后的字符集 */ public static String convert(String source, String srcCharset, String destCharset) { return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); } /** * 转换字符串的字符集编码 * * @param source 字符串 * @param srcCharset 源字符集,默认ISO-8859-1 * @param destCharset 目标字符集,默认UTF-8 * @return 转换后的字符集 */ public static String convert(String source, Charset srcCharset, Charset destCharset) {<FILL_FUNCTION_BODY>} /** * @return 系统字符集编码 */ public static String systemCharset() { return Charset.defaultCharset().name(); } }
if (null == srcCharset) { srcCharset = StandardCharsets.ISO_8859_1; } if (null == destCharset) { destCharset = StandardCharsets.UTF_8; } if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) { return source; } return new String(source.getBytes(srcCharset), destCharset);
667
138
805
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/core/text/StrFormatter.java
StrFormatter
format
class StrFormatter { public static final String EMPTY_JSON = "{}"; public static final char C_BACKSLASH = '\\'; public static final char C_DELIM_START = '{'; public static final char C_DELIM_END = '}'; /** * 格式化字符串<br> * 此方法只是简单将占位符 {} 按照顺序替换为参数<br> * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br> * 例:<br> * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br> * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br> * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br> * * @param strPattern 字符串模板 * @param argArray 参数列表 * @return 结果 */ public static String format(final String strPattern, final Object... argArray) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray)) { return strPattern; } final int strPatternLength = strPattern.length(); // 初始化定义好的长度以获得更好的性能 StringBuilder sbuf = new StringBuilder(strPatternLength + 50); int handledPosition = 0; int delimIndex;// 占位符所在位置 for (int argIndex = 0; argIndex < argArray.length; argIndex++) { delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); if (delimIndex == -1) { if (handledPosition == 0) { return strPattern; } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 sbuf.append(strPattern, handledPosition, strPatternLength); return sbuf.toString(); } } else { if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) { if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) { // 转义符之前还有一个转义符,占位符依旧有效 sbuf.append(strPattern, handledPosition, delimIndex - 1); sbuf.append(Convert.utf8Str(argArray[argIndex])); handledPosition = delimIndex + 2; } else { // 占位符被转义 argIndex--; sbuf.append(strPattern, handledPosition, delimIndex - 1); sbuf.append(C_DELIM_START); handledPosition = delimIndex + 1; } } else { // 正常占位符 sbuf.append(strPattern, handledPosition, delimIndex); sbuf.append(Convert.utf8Str(argArray[argIndex])); handledPosition = delimIndex + 2; } } } // 加入最后一个占位符后所有的字符 sbuf.append(strPattern, handledPosition, strPattern.length()); return sbuf.toString();
358
640
998
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/exception/base/BaseException.java
BaseException
getMessage
class BaseException extends RuntimeException { private static final long serialVersionUID = 1L; /** * 所属模块 */ private String module; /** * 错误码 */ private String code; /** * 错误码对应的参数 */ private Object[] args; /** * 错误消息 */ private String defaultMessage; public BaseException(String module, String code, Object[] args, String defaultMessage) { this.module = module; this.code = code; this.args = args; this.defaultMessage = defaultMessage; } public BaseException(String module, String code, Object[] args) { this(module, code, args, null); } public BaseException(String module, String defaultMessage) { this(module, null, null, defaultMessage); } public BaseException(String code, Object[] args) { this(null, code, args, null); } public BaseException(String defaultMessage) { this(null, null, null, defaultMessage); } @Override public String getMessage() {<FILL_FUNCTION_BODY>} public String getModule() { return module; } public String getCode() { return code; } public Object[] getArgs() { return args; } public String getDefaultMessage() { return defaultMessage; } }
String message = null; if (!StringUtils.isEmpty(code)) { message = MessageUtils.message(code, args); } if (message == null) { message = defaultMessage; } return message;
480
77
557
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/exception/file/FileUploadException.java
FileUploadException
printStackTrace
class FileUploadException extends Exception { private static final long serialVersionUID = 1L; private final Throwable cause; public FileUploadException() { this(null, null); } public FileUploadException(final String msg) { this(msg, null); } public FileUploadException(String msg, Throwable cause) { super(msg); this.cause = cause; } @Override public void printStackTrace(PrintStream stream) { super.printStackTrace(stream); if (cause != null) { stream.println("Caused by:"); cause.printStackTrace(stream); } } @Override public void printStackTrace(PrintWriter writer) {<FILL_FUNCTION_BODY>} @Override public Throwable getCause() { return cause; } }
super.printStackTrace(writer); if (cause != null) { writer.println("Caused by:"); cause.printStackTrace(writer); }
246
49
295
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/filter/PropertyPreExcludeFilter.java
PropertyPreExcludeFilter
addExcludes
class PropertyPreExcludeFilter extends SimplePropertyPreFilter { public PropertyPreExcludeFilter() { } public PropertyPreExcludeFilter addExcludes(String... filters) {<FILL_FUNCTION_BODY>} }
for (int i = 0; i < filters.length; i++) { this.getExcludes().add(filters[i]); } return this;
71
53
124
<methods>public transient void <init>(java.lang.String[]) ,public transient void <init>(Class<?>, java.lang.String[]) ,public Class<?> getClazz() ,public Set<java.lang.String> getExcludes() ,public Set<java.lang.String> getIncludes() ,public int getMaxLevel() ,public boolean process(com.alibaba.fastjson2.JSONWriter, java.lang.Object, java.lang.String) ,public void setMaxLevel(int) <variables>private final Class<?> clazz,private final Set<java.lang.String> excludes,private final Set<java.lang.String> includes,private int maxLevel
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatableFilter.java
RepeatableFilter
doFilter
class RepeatableFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @Override public void destroy() { } }
ServletRequest requestWrapper = null; if (request instanceof HttpServletRequest && StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) { requestWrapper = new RepeatedlyRequestWrapper((HttpServletRequest) request, response); } if (null == requestWrapper) { chain.doFilter(request, response); } else { chain.doFilter(requestWrapper, response); }
122
140
262
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/filter/RepeatedlyRequestWrapper.java
RepeatedlyRequestWrapper
getInputStream
class RepeatedlyRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException { super(request); request.setCharacterEncoding(Constants.UTF8); response.setCharacterEncoding(Constants.UTF8); body = HttpHelper.getBodyString(request).getBytes(Constants.UTF8); } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException {<FILL_FUNCTION_BODY>} }
final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } @Override public int available() throws IOException { return body.length; } @Override public boolean isFinished() { return false; } @Override public boolean isReady() { return false; } @Override public void setReadListener(ReadListener readListener) { } };
199
191
390
<methods>public void <init>(javax.servlet.http.HttpServletRequest) ,public boolean authenticate(javax.servlet.http.HttpServletResponse) throws java.io.IOException, javax.servlet.ServletException,public java.lang.String changeSessionId() ,public java.lang.String getAuthType() ,public java.lang.String getContextPath() ,public javax.servlet.http.Cookie[] getCookies() ,public long getDateHeader(java.lang.String) ,public java.lang.String getHeader(java.lang.String) ,public Enumeration<java.lang.String> getHeaderNames() ,public Enumeration<java.lang.String> getHeaders(java.lang.String) ,public javax.servlet.http.HttpServletMapping getHttpServletMapping() ,public int getIntHeader(java.lang.String) ,public java.lang.String getMethod() ,public javax.servlet.http.Part getPart(java.lang.String) throws java.io.IOException, javax.servlet.ServletException,public Collection<javax.servlet.http.Part> getParts() throws java.io.IOException, javax.servlet.ServletException,public java.lang.String getPathInfo() ,public java.lang.String getPathTranslated() ,public java.lang.String getQueryString() ,public java.lang.String getRemoteUser() ,public java.lang.String getRequestURI() ,public java.lang.StringBuffer getRequestURL() ,public java.lang.String getRequestedSessionId() ,public java.lang.String getServletPath() ,public javax.servlet.http.HttpSession getSession() ,public javax.servlet.http.HttpSession getSession(boolean) ,public Map<java.lang.String,java.lang.String> getTrailerFields() ,public java.security.Principal getUserPrincipal() ,public boolean isRequestedSessionIdFromCookie() ,public boolean isRequestedSessionIdFromURL() ,public boolean isRequestedSessionIdFromUrl() ,public boolean isRequestedSessionIdValid() ,public boolean isTrailerFieldsReady() ,public boolean isUserInRole(java.lang.String) ,public void login(java.lang.String, java.lang.String) throws javax.servlet.ServletException,public void logout() throws javax.servlet.ServletException,public javax.servlet.http.PushBuilder newPushBuilder() ,public T upgrade(Class<T>) throws java.io.IOException, javax.servlet.ServletException<variables>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/filter/XssFilter.java
XssFilter
init
class XssFilter implements Filter { /** * 排除链接 */ public List<String> excludes = new ArrayList<>(); @Override public void init(FilterConfig filterConfig) throws ServletException {<FILL_FUNCTION_BODY>} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; if (handleExcludeURL(req, resp)) { chain.doFilter(request, response); return; } XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { String url = request.getServletPath(); String method = request.getMethod(); // GET DELETE 不过滤 if (method == null || HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method)) { return true; } return StringUtils.matches(url, excludes); } @Override public void destroy() { } }
String tempExcludes = filterConfig.getInitParameter("excludes"); if (StringUtils.isNotEmpty(tempExcludes)) { String[] url = tempExcludes.split(","); for (int i = 0; url != null && i < url.length; i++) { excludes.add(url[i]); } }
386
105
491
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/filter/XssHttpServletRequestWrapper.java
XssHttpServletRequestWrapper
getParameterValues
class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { /** * @param request */ public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } @Override public String[] getParameterValues(String name) {<FILL_FUNCTION_BODY>} @Override public ServletInputStream getInputStream() throws IOException { // 非json类型,直接返回 if (!isJsonRequest()) { return super.getInputStream(); } // 为空,直接返回 String json = IOUtils.toString(super.getInputStream(), "utf-8"); if (StringUtils.isEmpty(json)) { return super.getInputStream(); } // xss过滤 json = EscapeUtil.clean(json).trim(); byte[] jsonBytes = json.getBytes("utf-8"); final ByteArrayInputStream bis = new ByteArrayInputStream(jsonBytes); return new ServletInputStream() { @Override public boolean isFinished() { return true; } @Override public boolean isReady() { return true; } @Override public int available() throws IOException { return jsonBytes.length; } @Override public void setReadListener(ReadListener readListener) { } @Override public int read() throws IOException { return bis.read(); } }; } /** * 是否是Json请求 * * @param request */ public boolean isJsonRequest() { String header = super.getHeader(HttpHeaders.CONTENT_TYPE); return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE); } }
String[] values = super.getParameterValues(name); if (values != null) { int length = values.length; String[] escapesValues = new String[length]; for (int i = 0; i < length; i++) { // 防xss攻击和过滤前后空格 escapesValues[i] = EscapeUtil.clean(values[i]).trim(); } return escapesValues; } return super.getParameterValues(name);
549
145
694
<methods>public void <init>(javax.servlet.http.HttpServletRequest) ,public boolean authenticate(javax.servlet.http.HttpServletResponse) throws java.io.IOException, javax.servlet.ServletException,public java.lang.String changeSessionId() ,public java.lang.String getAuthType() ,public java.lang.String getContextPath() ,public javax.servlet.http.Cookie[] getCookies() ,public long getDateHeader(java.lang.String) ,public java.lang.String getHeader(java.lang.String) ,public Enumeration<java.lang.String> getHeaderNames() ,public Enumeration<java.lang.String> getHeaders(java.lang.String) ,public javax.servlet.http.HttpServletMapping getHttpServletMapping() ,public int getIntHeader(java.lang.String) ,public java.lang.String getMethod() ,public javax.servlet.http.Part getPart(java.lang.String) throws java.io.IOException, javax.servlet.ServletException,public Collection<javax.servlet.http.Part> getParts() throws java.io.IOException, javax.servlet.ServletException,public java.lang.String getPathInfo() ,public java.lang.String getPathTranslated() ,public java.lang.String getQueryString() ,public java.lang.String getRemoteUser() ,public java.lang.String getRequestURI() ,public java.lang.StringBuffer getRequestURL() ,public java.lang.String getRequestedSessionId() ,public java.lang.String getServletPath() ,public javax.servlet.http.HttpSession getSession() ,public javax.servlet.http.HttpSession getSession(boolean) ,public Map<java.lang.String,java.lang.String> getTrailerFields() ,public java.security.Principal getUserPrincipal() ,public boolean isRequestedSessionIdFromCookie() ,public boolean isRequestedSessionIdFromURL() ,public boolean isRequestedSessionIdFromUrl() ,public boolean isRequestedSessionIdValid() ,public boolean isTrailerFieldsReady() ,public boolean isUserInRole(java.lang.String) ,public void login(java.lang.String, java.lang.String) throws javax.servlet.ServletException,public void logout() throws javax.servlet.ServletException,public javax.servlet.http.PushBuilder newPushBuilder() ,public T upgrade(Class<T>) throws java.io.IOException, javax.servlet.ServletException<variables>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/Arith.java
Arith
div
class Arith { /** 默认除法运算精度 */ private static final int DEF_DIV_SCALE = 10; /** 这个类不能实例化 */ private Arith() { } /** * 提供精确的加法运算。 * @param v1 被加数 * @param v2 加数 * @return 两个参数的和 */ public static double add(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } /** * 提供精确的减法运算。 * @param v1 被减数 * @param v2 减数 * @return 两个参数的差 */ public static double sub(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.subtract(b2).doubleValue(); } /** * 提供精确的乘法运算。 * @param v1 被乘数 * @param v2 乘数 * @return 两个参数的积 */ public static double mul(double v1, double v2) { BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.multiply(b2).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 * 小数点以后10位,以后的数字四舍五入。 * @param v1 被除数 * @param v2 除数 * @return 两个参数的商 */ public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 * 定精度,以后的数字四舍五入。 * @param v1 被除数 * @param v2 除数 * @param scale 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) {<FILL_FUNCTION_BODY>} /** * 提供精确的小数位四舍五入处理。 * @param v 需要四舍五入的数字 * @param scale 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = BigDecimal.ONE; return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue(); } }
if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); if (b1.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO.doubleValue(); } return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
886
145
1,031
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/DateUtils.java
DateUtils
dateTime
class DateUtils extends org.apache.commons.lang3.time.DateUtils { public static String YYYY = "yyyy"; public static String YYYY_MM = "yyyy-MM"; public static String YYYY_MM_DD = "yyyy-MM-dd"; public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 获取当前Date型日期 * * @return Date() 当前日期 */ public static Date getNowDate() { return new Date(); } /** * 获取当前日期, 默认格式为yyyy-MM-dd * * @return String */ public static String getDate() { return dateTimeNow(YYYY_MM_DD); } public static final String getTime() { return dateTimeNow(YYYY_MM_DD_HH_MM_SS); } public static final String dateTimeNow() { return dateTimeNow(YYYYMMDDHHMMSS); } public static final String dateTimeNow(final String format) { return parseDateToStr(format, new Date()); } public static final String dateTime(final Date date) { return parseDateToStr(YYYY_MM_DD, date); } public static final String parseDateToStr(final String format, final Date date) { return new SimpleDateFormat(format).format(date); } public static final Date dateTime(final String format, final String ts) {<FILL_FUNCTION_BODY>} /** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date now = new Date(); return DateFormatUtils.format(now, "yyyy/MM/dd"); } /** * 日期路径 即年/月/日 如20180808 */ public static final String dateTime() { Date now = new Date(); return DateFormatUtils.format(now, "yyyyMMdd"); } /** * 日期型字符串转化为日期 格式 */ public static Date parseDate(Object str) { if (str == null) { return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取服务器启动时间 */ public static Date getServerStartDate() { long time = ManagementFactory.getRuntimeMXBean().getStartTime(); return new Date(time); } /** * 计算相差天数 */ public static int differentDaysByMillisecond(Date date1, Date date2) { return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24))); } /** * 计算时间差 * * @param endDate 最后时间 * @param startTime 开始时间 * @return 时间差(天/小时/分钟) */ public static String timeDistance(Date endDate, Date startTime) { long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - startTime.getTime(); // 计算差多少天 long day = diff / nd; // 计算差多少小时 long hour = diff % nd / nh; // 计算差多少分钟 long min = diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; return day + "天" + hour + "小时" + min + "分钟"; } /** * 增加 LocalDateTime ==> Date */ public static Date toDate(LocalDateTime temporalAccessor) { ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } /** * 增加 LocalDate ==> Date */ public static Date toDate(LocalDate temporalAccessor) { LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0)); ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault()); return Date.from(zdt.toInstant()); } }
try { return new SimpleDateFormat(format).parse(ts); } catch (ParseException e) { throw new RuntimeException(e); }
1,615
58
1,673
<methods>public void <init>() ,public static java.util.Date addDays(java.util.Date, int) ,public static java.util.Date addHours(java.util.Date, int) ,public static java.util.Date addMilliseconds(java.util.Date, int) ,public static java.util.Date addMinutes(java.util.Date, int) ,public static java.util.Date addMonths(java.util.Date, int) ,public static java.util.Date addSeconds(java.util.Date, int) ,public static java.util.Date addWeeks(java.util.Date, int) ,public static java.util.Date addYears(java.util.Date, int) ,public static java.util.Date ceiling(java.util.Date, int) ,public static java.util.Calendar ceiling(java.util.Calendar, int) ,public static java.util.Date ceiling(java.lang.Object, int) ,public static long getFragmentInDays(java.util.Date, int) ,public static long getFragmentInDays(java.util.Calendar, int) ,public static long getFragmentInHours(java.util.Date, int) ,public static long getFragmentInHours(java.util.Calendar, int) ,public static long getFragmentInMilliseconds(java.util.Date, int) ,public static long getFragmentInMilliseconds(java.util.Calendar, int) ,public static long getFragmentInMinutes(java.util.Date, int) ,public static long getFragmentInMinutes(java.util.Calendar, int) ,public static long getFragmentInSeconds(java.util.Date, int) ,public static long getFragmentInSeconds(java.util.Calendar, int) ,public static boolean isSameDay(java.util.Date, java.util.Date) ,public static boolean isSameDay(java.util.Calendar, java.util.Calendar) ,public static boolean isSameInstant(java.util.Date, java.util.Date) ,public static boolean isSameInstant(java.util.Calendar, java.util.Calendar) ,public static boolean isSameLocalTime(java.util.Calendar, java.util.Calendar) ,public static Iterator<java.util.Calendar> iterator(java.util.Date, int) ,public static Iterator<java.util.Calendar> iterator(java.util.Calendar, int) ,public static Iterator<?> iterator(java.lang.Object, int) ,public static transient java.util.Date parseDate(java.lang.String, java.lang.String[]) throws java.text.ParseException,public static transient java.util.Date parseDate(java.lang.String, java.util.Locale, java.lang.String[]) throws java.text.ParseException,public static transient java.util.Date parseDateStrictly(java.lang.String, java.lang.String[]) throws java.text.ParseException,public static transient java.util.Date parseDateStrictly(java.lang.String, java.util.Locale, java.lang.String[]) throws java.text.ParseException,public static java.util.Date round(java.util.Date, int) ,public static java.util.Calendar round(java.util.Calendar, int) ,public static java.util.Date round(java.lang.Object, int) ,public static java.util.Date setDays(java.util.Date, int) ,public static java.util.Date setHours(java.util.Date, int) ,public static java.util.Date setMilliseconds(java.util.Date, int) ,public static java.util.Date setMinutes(java.util.Date, int) ,public static java.util.Date setMonths(java.util.Date, int) ,public static java.util.Date setSeconds(java.util.Date, int) ,public static java.util.Date setYears(java.util.Date, int) ,public static java.util.Calendar toCalendar(java.util.Date) ,public static java.util.Calendar toCalendar(java.util.Date, java.util.TimeZone) ,public static java.util.Date truncate(java.util.Date, int) ,public static java.util.Calendar truncate(java.util.Calendar, int) ,public static java.util.Date truncate(java.lang.Object, int) ,public static int truncatedCompareTo(java.util.Calendar, java.util.Calendar, int) ,public static int truncatedCompareTo(java.util.Date, java.util.Date, int) ,public static boolean truncatedEquals(java.util.Calendar, java.util.Calendar, int) ,public static boolean truncatedEquals(java.util.Date, java.util.Date, int) <variables>public static final long MILLIS_PER_DAY,public static final long MILLIS_PER_HOUR,public static final long MILLIS_PER_MINUTE,public static final long MILLIS_PER_SECOND,public static final int RANGE_MONTH_MONDAY,public static final int RANGE_MONTH_SUNDAY,public static final int RANGE_WEEK_CENTER,public static final int RANGE_WEEK_MONDAY,public static final int RANGE_WEEK_RELATIVE,public static final int RANGE_WEEK_SUNDAY,public static final int SEMI_MONTH,private static final int[][] fields
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/DesensitizedUtil.java
DesensitizedUtil
carLicense
class DesensitizedUtil { /** * 密码的全部字符都用*代替,比如:****** * * @param password 密码 * @return 脱敏后的密码 */ public static String password(String password) { if (StringUtils.isBlank(password)) { return StringUtils.EMPTY; } return StringUtils.repeat('*', password.length()); } /** * 车牌中间用*代替,如果是错误的车牌,不处理 * * @param carLicense 完整的车牌号 * @return 脱敏后的车牌 */ public static String carLicense(String carLicense) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isBlank(carLicense)) { return StringUtils.EMPTY; } // 普通车牌 if (carLicense.length() == 7) { carLicense = StringUtils.hide(carLicense, 3, 6); } else if (carLicense.length() == 8) { // 新能源车牌 carLicense = StringUtils.hide(carLicense, 3, 7); } return carLicense;
199
128
327
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/DictUtils.java
DictUtils
getDictValue
class DictUtils { /** * 分隔符 */ public static final String SEPARATOR = ","; /** * 设置字典缓存 * * @param key 参数键 * @param dictDatas 字典数据列表 */ public static void setDictCache(String key, List<SysDictData> dictDatas) { SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), dictDatas); } /** * 获取字典缓存 * * @param key 参数键 * @return dictDatas 字典数据列表 */ public static List<SysDictData> getDictCache(String key) { JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key)); if (StringUtils.isNotNull(arrayCache)) { return arrayCache.toList(SysDictData.class); } return null; } /** * 根据字典类型和字典值获取字典标签 * * @param dictType 字典类型 * @param dictValue 字典值 * @return 字典标签 */ public static String getDictLabel(String dictType, String dictValue) { return getDictLabel(dictType, dictValue, SEPARATOR); } /** * 根据字典类型和字典标签获取字典值 * * @param dictType 字典类型 * @param dictLabel 字典标签 * @return 字典值 */ public static String getDictValue(String dictType, String dictLabel) { return getDictValue(dictType, dictLabel, SEPARATOR); } /** * 根据字典类型和字典值获取字典标签 * * @param dictType 字典类型 * @param dictValue 字典值 * @param separator 分隔符 * @return 字典标签 */ public static String getDictLabel(String dictType, String dictValue, String separator) { StringBuilder propertyString = new StringBuilder(); List<SysDictData> datas = getDictCache(dictType); if (StringUtils.isNotNull(datas)) { if (StringUtils.containsAny(separator, dictValue)) { for (SysDictData dict : datas) { for (String value : dictValue.split(separator)) { if (value.equals(dict.getDictValue())) { propertyString.append(dict.getDictLabel()).append(separator); break; } } } } else { for (SysDictData dict : datas) { if (dictValue.equals(dict.getDictValue())) { return dict.getDictLabel(); } } } } return StringUtils.stripEnd(propertyString.toString(), separator); } /** * 根据字典类型和字典标签获取字典值 * * @param dictType 字典类型 * @param dictLabel 字典标签 * @param separator 分隔符 * @return 字典值 */ public static String getDictValue(String dictType, String dictLabel, String separator) {<FILL_FUNCTION_BODY>} /** * 删除指定字典缓存 * * @param key 字典键 */ public static void removeDictCache(String key) { SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key)); } /** * 清空字典缓存 */ public static void clearDictCache() { Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.SYS_DICT_KEY + "*"); SpringUtils.getBean(RedisCache.class).deleteObject(keys); } /** * 设置cache key * * @param configKey 参数键 * @return 缓存键key */ public static String getCacheKey(String configKey) { return CacheConstants.SYS_DICT_KEY + configKey; } }
StringBuilder propertyString = new StringBuilder(); List<SysDictData> datas = getDictCache(dictType); if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) { for (SysDictData dict : datas) { for (String label : dictLabel.split(separator)) { if (label.equals(dict.getDictLabel())) { propertyString.append(dict.getDictValue()).append(separator); break; } } } } else { for (SysDictData dict : datas) { if (dictLabel.equals(dict.getDictLabel())) { return dict.getDictValue(); } } } return StringUtils.stripEnd(propertyString.toString(), separator);
1,299
258
1,557
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/ExceptionUtil.java
ExceptionUtil
getRootErrorMessage
class ExceptionUtil { /** * 获取exception的详细错误信息。 */ public static String getExceptionMessage(Throwable e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw, true)); return sw.toString(); } public static String getRootErrorMessage(Exception e) {<FILL_FUNCTION_BODY>} }
Throwable root = ExceptionUtils.getRootCause(e); root = (root == null ? e : root); if (root == null) { return ""; } String msg = root.getMessage(); if (msg == null) { return "null"; } return StringUtils.defaultString(msg);
120
104
224
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/LogUtils.java
LogUtils
getBlock
class LogUtils { public static String getBlock(Object msg) {<FILL_FUNCTION_BODY>} }
if (msg == null) { msg = ""; } return "[" + msg.toString() + "]";
38
42
80
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/PageUtils.java
PageUtils
startPage
class PageUtils extends PageHelper { /** * 设置请求分页数据 */ public static void startPage() {<FILL_FUNCTION_BODY>} /** * 清理分页的线程变量 */ public static void clearPage() { PageHelper.clearPage(); } }
PageDomain pageDomain = TableSupport.buildPageRequest(); Integer pageNum = pageDomain.getPageNum(); Integer pageSize = pageDomain.getPageSize(); String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy()); Boolean reasonable = pageDomain.getReasonable(); PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
90
100
190
<methods>public void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public org.apache.ibatis.mapping.BoundSql doBoundSql(com.github.pagehelper.BoundSqlInterceptor.Type, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>private com.github.pagehelper.page.PageAutoDialect autoDialect,private com.github.pagehelper.page.PageBoundSqlInterceptors pageBoundSqlInterceptors,private com.github.pagehelper.page.PageParams pageParams
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/SecurityUtils.java
SecurityUtils
getLoginUser
class SecurityUtils { /** * 用户ID **/ public static Long getUserId() { try { return getLoginUser().getUserId(); } catch (Exception e) { throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED); } } /** * 获取部门ID **/ public static Long getDeptId() { try { return getLoginUser().getDeptId(); } catch (Exception e) { throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED); } } /** * 获取用户账户 **/ public static String getUsername() { try { return getLoginUser().getUsername(); } catch (Exception e) { throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED); } } /** * 获取用户 **/ public static LoginUser getLoginUser() {<FILL_FUNCTION_BODY>} /** * 获取Authentication */ public static Authentication getAuthentication() { return SecurityContextHolder.getContext().getAuthentication(); } /** * 生成BCryptPasswordEncoder密码 * * @param password 密码 * @return 加密字符串 */ public static String encryptPassword(String password) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); return passwordEncoder.encode(password); } /** * 判断密码是否相同 * * @param rawPassword 真实密码 * @param encodedPassword 加密后字符 * @return 结果 */ public static boolean matchesPassword(String rawPassword, String encodedPassword) { BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); return passwordEncoder.matches(rawPassword, encodedPassword); } /** * 是否为管理员 * * @param userId 用户ID * @return 结果 */ public static boolean isAdmin(Long userId) { return userId != null && 1L == userId; } /** * 验证用户是否具备某权限 * * @param permission 权限字符串 * @return 用户是否具备某权限 */ public static boolean hasPermi(String permission) { return hasPermi(getLoginUser().getPermissions(), permission); } /** * 判断是否包含权限 * * @param authorities 权限列表 * @param permission 权限字符串 * @return 用户是否具备某权限 */ public static boolean hasPermi(Collection<String> authorities, String permission) { return authorities.stream().filter(StringUtils::hasText) .anyMatch(x -> Constants.ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, permission)); } /** * 验证用户是否拥有某个角色 * * @param role 角色标识 * @return 用户是否具备某角色 */ public static boolean hasRole(String role) { List<SysRole> roleList = getLoginUser().getUser().getRoles(); Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet()); return hasRole(roles, role); } /** * 判断是否包含角色 * * @param roles 角色列表 * @param role 角色 * @return 用户是否具备某角色权限 */ public static boolean hasRole(Collection<String> roles, String role) { return roles.stream().filter(StringUtils::hasText) .anyMatch(x -> Constants.SUPER_ADMIN.equals(x) || PatternMatchUtils.simpleMatch(x, role)); } }
try { return (LoginUser) getAuthentication().getPrincipal(); } catch (Exception e) { throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED); }
1,219
70
1,289
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/ServletUtils.java
ServletUtils
isAjaxRequest
class ServletUtils { /** * 获取String参数 */ public static String getParameter(String name) { return getRequest().getParameter(name); } /** * 获取String参数 */ public static String getParameter(String name, String defaultValue) { return Convert.toStr(getRequest().getParameter(name), defaultValue); } /** * 获取Integer参数 */ public static Integer getParameterToInt(String name) { return Convert.toInt(getRequest().getParameter(name)); } /** * 获取Integer参数 */ public static Integer getParameterToInt(String name, Integer defaultValue) { return Convert.toInt(getRequest().getParameter(name), defaultValue); } /** * 获取Boolean参数 */ public static Boolean getParameterToBool(String name) { return Convert.toBool(getRequest().getParameter(name)); } /** * 获取Boolean参数 */ public static Boolean getParameterToBool(String name, Boolean defaultValue) { return Convert.toBool(getRequest().getParameter(name), defaultValue); } /** * 获得所有请求参数 * * @param request 请求对象{@link ServletRequest} * @return Map */ public static Map<String, String[]> getParams(ServletRequest request) { final Map<String, String[]> map = request.getParameterMap(); return Collections.unmodifiableMap(map); } /** * 获得所有请求参数 * * @param request 请求对象{@link ServletRequest} * @return Map */ public static Map<String, String> getParamMap(ServletRequest request) { Map<String, String> params = new HashMap<>(); for (Map.Entry<String, String[]> entry : getParams(request).entrySet()) { params.put(entry.getKey(), StringUtils.join(entry.getValue(), ",")); } return params; } /** * 获取request */ public static HttpServletRequest getRequest() { return getRequestAttributes().getRequest(); } /** * 获取response */ public static HttpServletResponse getResponse() { return getRequestAttributes().getResponse(); } /** * 获取session */ public static HttpSession getSession() { return getRequest().getSession(); } public static ServletRequestAttributes getRequestAttributes() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); return (ServletRequestAttributes) attributes; } /** * 将字符串渲染到客户端 * * @param response 渲染对象 * @param string 待渲染的字符串 */ public static void renderString(HttpServletResponse response, String string) { try { response.setStatus(200); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); response.getWriter().print(string); } catch (IOException e) { e.printStackTrace(); } } /** * 是否是Ajax异步请求 * * @param request */ public static boolean isAjaxRequest(HttpServletRequest request) {<FILL_FUNCTION_BODY>} /** * 内容编码 * * @param str 内容 * @return 编码后的内容 */ public static String urlEncode(String str) { try { return URLEncoder.encode(str, Constants.UTF8); } catch (UnsupportedEncodingException e) { return StringUtils.EMPTY; } } /** * 内容解码 * * @param str 内容 * @return 解码后的内容 */ public static String urlDecode(String str) { try { return URLDecoder.decode(str, Constants.UTF8); } catch (UnsupportedEncodingException e) { return StringUtils.EMPTY; } } }
String accept = request.getHeader("accept"); if (accept != null && accept.contains("application/json")) { return true; } String xRequestedWith = request.getHeader("X-Requested-With"); if (xRequestedWith != null && xRequestedWith.contains("XMLHttpRequest")) { return true; } String uri = request.getRequestURI(); if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) { return true; } String ajax = request.getParameter("__ajax"); return StringUtils.inStringIgnoreCase(ajax, "json", "xml");
1,296
196
1,492
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/Threads.java
Threads
shutdownAndAwaitTermination
class Threads { private static final Logger logger = LoggerFactory.getLogger(Threads.class); /** * sleep等待,单位为毫秒 */ public static void sleep(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { return; } } /** * 停止线程池 * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务. * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数. * 如果仍然超時,則強制退出. * 另对在shutdown时线程本身被调用中断做了处理. */ public static void shutdownAndAwaitTermination(ExecutorService pool) {<FILL_FUNCTION_BODY>} /** * 打印线程异常信息 */ public static void printException(Runnable r, Throwable t) { if (t == null && r instanceof Future<?>) { try { Future<?> future = (Future<?>) r; if (future.isDone()) { future.get(); } } catch (CancellationException ce) { t = ce; } catch (ExecutionException ee) { t = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (t != null) { logger.error(t.getMessage(), t); } } }
if (pool != null && !pool.isShutdown()) { pool.shutdown(); try { if (!pool.awaitTermination(120, TimeUnit.SECONDS)) { pool.shutdownNow(); if (!pool.awaitTermination(120, TimeUnit.SECONDS)) { logger.info("Pool did not terminate"); } } } catch (InterruptedException ie) { pool.shutdownNow(); Thread.currentThread().interrupt(); } }
518
172
690
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanUtils.java
BeanUtils
getGetterMethods
class BeanUtils extends org.springframework.beans.BeanUtils { /** Bean方法名中属性名开始的下标 */ private static final int BEAN_METHOD_PROP_INDEX = 3; /** * 匹配getter方法的正则表达式 */ private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)"); /** * 匹配setter方法的正则表达式 */ private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)"); /** * Bean属性复制工具方法。 * * @param dest 目标对象 * @param src 源对象 */ public static void copyBeanProp(Object dest, Object src) { try { copyProperties(src, dest); } catch (Exception e) { e.printStackTrace(); } } /** * 获取对象的setter方法。 * * @param obj 对象 * @return 对象的setter方法列表 */ public static List<Method> getSetterMethods(Object obj) { // setter方法列表 List<Method> setterMethods = new ArrayList<Method>(); // 获取所有方法 Method[] methods = obj.getClass().getMethods(); // 查找setter方法 for (Method method : methods) { Matcher m = SET_PATTERN.matcher(method.getName()); if (m.matches() && (method.getParameterTypes().length == 1)) { setterMethods.add(method); } } // 返回setter方法列表 return setterMethods; } /** * 获取对象的getter方法。 * * @param obj 对象 * @return 对象的getter方法列表 */ public static List<Method> getGetterMethods(Object obj) {<FILL_FUNCTION_BODY>} /** * 检查Bean方法名中的属性名是否相等。<br> * 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。 * * @param m1 方法名1 * @param m2 方法名2 * @return 属性名一样返回true,否则返回false */ public static boolean isMethodPropEquals(String m1, String m2) { return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX)); } }
// getter方法列表 List<Method> getterMethods = new ArrayList<Method>(); // 获取所有方法 Method[] methods = obj.getClass().getMethods(); // 查找getter方法 for (Method method : methods) { Matcher m = GET_PATTERN.matcher(method.getName()); if (m.matches() && (method.getParameterTypes().length == 0)) { getterMethods.add(method); } } // 返回getter方法列表 return getterMethods;
773
162
935
<methods>public void <init>() ,public static void copyProperties(java.lang.Object, java.lang.Object) throws org.springframework.beans.BeansException,public static void copyProperties(java.lang.Object, java.lang.Object, Class<?>) throws org.springframework.beans.BeansException,public static transient void copyProperties(java.lang.Object, java.lang.Object, java.lang.String[]) throws org.springframework.beans.BeansException,public static transient java.lang.reflect.Method findDeclaredMethod(Class<?>, java.lang.String, Class<?>[]) ,public static java.lang.reflect.Method findDeclaredMethodWithMinimalParameters(Class<?>, java.lang.String) throws java.lang.IllegalArgumentException,public static java.beans.PropertyEditor findEditorByConvention(Class<?>) ,public static transient java.lang.reflect.Method findMethod(Class<?>, java.lang.String, Class<?>[]) ,public static java.lang.reflect.Method findMethodWithMinimalParameters(Class<?>, java.lang.String) throws java.lang.IllegalArgumentException,public static java.lang.reflect.Method findMethodWithMinimalParameters(java.lang.reflect.Method[], java.lang.String) throws java.lang.IllegalArgumentException,public static Constructor<T> findPrimaryConstructor(Class<T>) ,public static java.beans.PropertyDescriptor findPropertyForMethod(java.lang.reflect.Method) throws org.springframework.beans.BeansException,public static java.beans.PropertyDescriptor findPropertyForMethod(java.lang.reflect.Method, Class<?>) throws org.springframework.beans.BeansException,public static transient Class<?> findPropertyType(java.lang.String, Class<?>[]) ,public static java.lang.String[] getParameterNames(Constructor<?>) ,public static java.beans.PropertyDescriptor getPropertyDescriptor(Class<?>, java.lang.String) throws org.springframework.beans.BeansException,public static java.beans.PropertyDescriptor[] getPropertyDescriptors(Class<?>) throws org.springframework.beans.BeansException,public static Constructor<T> getResolvableConstructor(Class<T>) ,public static org.springframework.core.MethodParameter getWriteMethodParameter(java.beans.PropertyDescriptor) ,public static T instantiate(Class<T>) throws org.springframework.beans.BeanInstantiationException,public static T instantiateClass(Class<T>) throws org.springframework.beans.BeanInstantiationException,public static T instantiateClass(Class<?>, Class<T>) throws org.springframework.beans.BeanInstantiationException,public static transient T instantiateClass(Constructor<T>, java.lang.Object[]) throws org.springframework.beans.BeanInstantiationException,public static boolean isSimpleProperty(Class<?>) ,public static boolean isSimpleValueType(Class<?>) ,public static java.lang.reflect.Method resolveSignature(java.lang.String, Class<?>) <variables>private static final Map<Class<?>,java.lang.Object> DEFAULT_TYPE_VALUES,private static final org.springframework.core.ParameterNameDiscoverer parameterNameDiscoverer,private static final Set<Class<?>> unknownEditorTypes
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/bean/BeanValidators.java
BeanValidators
validateWithException
class BeanValidators { public static void validateWithException(Validator validator, Object object, Class<?>... groups) throws ConstraintViolationException {<FILL_FUNCTION_BODY>} }
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups); if (!constraintViolations.isEmpty()) { throw new ConstraintViolationException(constraintViolations); }
62
67
129
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileTypeUtils.java
FileTypeUtils
getFileType
class FileTypeUtils { /** * 获取文件类型 * <p> * 例如: ruoyi.txt, 返回: txt * * @param file 文件名 * @return 后缀(不含".") */ public static String getFileType(File file) { if (null == file) { return StringUtils.EMPTY; } return getFileType(file.getName()); } /** * 获取文件类型 * <p> * 例如: ruoyi.txt, 返回: txt * * @param fileName 文件名 * @return 后缀(不含".") */ public static String getFileType(String fileName) {<FILL_FUNCTION_BODY>} /** * 获取文件类型 * * @param photoByte 文件字节码 * @return 后缀(不含".") */ public static String getFileExtendName(byte[] photoByte) { String strFileExtendName = "JPG"; if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) { strFileExtendName = "GIF"; } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) { strFileExtendName = "JPG"; } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) { strFileExtendName = "BMP"; } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) { strFileExtendName = "PNG"; } return strFileExtendName; } }
int separatorIndex = fileName.lastIndexOf("."); if (separatorIndex < 0) { return ""; } return fileName.substring(separatorIndex + 1).toLowerCase();
627
64
691
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/FileUploadUtils.java
FileUploadUtils
isAllowedExtension
class FileUploadUtils { /** * 默认大小 50M */ public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024; /** * 默认的文件名最大长度 100 */ public static final int DEFAULT_FILE_NAME_LENGTH = 100; /** * 默认上传的地址 */ private static String defaultBaseDir = RuoYiConfig.getProfile(); public static void setDefaultBaseDir(String defaultBaseDir) { FileUploadUtils.defaultBaseDir = defaultBaseDir; } public static String getDefaultBaseDir() { return defaultBaseDir; } /** * 以默认配置进行文件上传 * * @param file 上传的文件 * @return 文件名称 * @throws Exception */ public static final String upload(MultipartFile file) throws IOException { try { return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 根据文件路径上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @return 文件名称 * @throws IOException */ public static final String upload(String baseDir, MultipartFile file) throws IOException { try { return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION); } catch (Exception e) { throw new IOException(e.getMessage(), e); } } /** * 文件上传 * * @param baseDir 相对应用的基目录 * @param file 上传的文件 * @param allowedExtension 上传文件类型 * @return 返回上传成功的文件名 * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws FileNameLengthLimitExceededException 文件名太长 * @throws IOException 比如读写文件出错时 * @throws InvalidExtensionException 文件校验异常 */ public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException { int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length(); if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) { throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH); } assertAllowed(file, allowedExtension); String fileName = extractFilename(file); String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath(); file.transferTo(Paths.get(absPath)); return getPathFileName(baseDir, fileName); } /** * 编码文件名 */ public static final String extractFilename(MultipartFile file) { return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(), FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file)); } public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException { File desc = new File(uploadDir + File.separator + fileName); if (!desc.exists()) { if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } } return desc; } public static final String getPathFileName(String uploadDir, String fileName) throws IOException { int dirLastIndex = RuoYiConfig.getProfile().length() + 1; String currentDir = StringUtils.substring(uploadDir, dirLastIndex); return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName; } /** * 文件大小校验 * * @param file 上传的文件 * @return * @throws FileSizeLimitExceededException 如果超出最大大小 * @throws InvalidExtensionException */ public static final void assertAllowed(MultipartFile file, String[] allowedExtension) throws FileSizeLimitExceededException, InvalidExtensionException { long size = file.getSize(); if (size > DEFAULT_MAX_SIZE) { throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024); } String fileName = file.getOriginalFilename(); String extension = getExtension(file); if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) { if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) { throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) { throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) { throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension, fileName); } else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION) { throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension, fileName); } else { throw new InvalidExtensionException(allowedExtension, extension, fileName); } } } /** * 判断MIME类型是否是允许的MIME类型 * * @param extension * @param allowedExtension * @return */ public static final boolean isAllowedExtension(String extension, String[] allowedExtension) {<FILL_FUNCTION_BODY>} /** * 获取文件名的后缀 * * @param file 表单文件 * @return 后缀名 */ public static final String getExtension(MultipartFile file) { String extension = FilenameUtils.getExtension(file.getOriginalFilename()); if (StringUtils.isEmpty(extension)) { extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType())); } return extension; } }
for (String str : allowedExtension) { if (str.equalsIgnoreCase(extension)) { return true; } } return false;
1,918
56
1,974
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/ImageUtils.java
ImageUtils
readFile
class ImageUtils { private static final Logger log = LoggerFactory.getLogger(ImageUtils.class); public static byte[] getImage(String imagePath) { InputStream is = getFile(imagePath); try { return IOUtils.toByteArray(is); } catch (Exception e) { log.error("图片加载异常 {}", e); return null; } finally { IOUtils.closeQuietly(is); } } public static InputStream getFile(String imagePath) { try { byte[] result = readFile(imagePath); result = Arrays.copyOf(result, result.length); return new ByteArrayInputStream(result); } catch (Exception e) { log.error("获取图片异常 {}", e); } return null; } /** * 读取文件为字节数据 * * @param url 地址 * @return 字节数据 */ public static byte[] readFile(String url) {<FILL_FUNCTION_BODY>} }
InputStream in = null; try { if (url.startsWith("http")) { // 网络地址 URL urlObj = new URL(url); URLConnection urlConnection = urlObj.openConnection(); urlConnection.setConnectTimeout(30 * 1000); urlConnection.setReadTimeout(60 * 1000); urlConnection.setDoInput(true); in = urlConnection.getInputStream(); } else { // 本机地址 String localPath = RuoYiConfig.getProfile(); String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX); in = new FileInputStream(downloadPath); } return IOUtils.toByteArray(in); } catch (Exception e) { log.error("获取文件路径异常 {}", e); return null; } finally { IOUtils.closeQuietly(in); }
344
293
637
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/file/MimeTypeUtils.java
MimeTypeUtils
getExtension
class MimeTypeUtils { public static final String IMAGE_PNG = "image/png"; public static final String IMAGE_JPG = "image/jpg"; public static final String IMAGE_JPEG = "image/jpeg"; public static final String IMAGE_BMP = "image/bmp"; public static final String IMAGE_GIF = "image/gif"; public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" }; public static final String[] FLASH_EXTENSION = { "swf", "flv" }; public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb" }; public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" }; public static final String[] DEFAULT_ALLOWED_EXTENSION = { // 图片 "bmp", "gif", "jpg", "jpeg", "png", // word excel powerpoint "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", // 压缩文件 "rar", "zip", "gz", "bz2", // 视频格式 "mp4", "avi", "rmvb", // pdf "pdf" }; public static String getExtension(String prefix) {<FILL_FUNCTION_BODY>} }
switch (prefix) { case IMAGE_PNG: return "png"; case IMAGE_JPG: return "jpg"; case IMAGE_JPEG: return "jpeg"; case IMAGE_BMP: return "bmp"; case IMAGE_GIF: return "gif"; default: return ""; }
461
117
578
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/html/EscapeUtil.java
EscapeUtil
encode
class EscapeUtil { public static final String RE_HTML_MARK = "(<[^<]*?>)|(<[\\s]*?/[^<]*?>)|(<[^<]*?/[\\s]*?>)"; private static final char[][] TEXT = new char[64][]; static { for (int i = 0; i < 64; i++) { TEXT[i] = new char[] { (char) i }; } // special HTML characters TEXT['\''] = "&#039;".toCharArray(); // 单引号 TEXT['"'] = "&#34;".toCharArray(); // 双引号 TEXT['&'] = "&#38;".toCharArray(); // &符 TEXT['<'] = "&#60;".toCharArray(); // 小于号 TEXT['>'] = "&#62;".toCharArray(); // 大于号 } /** * 转义文本中的HTML字符为安全的字符 * * @param text 被转义的文本 * @return 转义后的文本 */ public static String escape(String text) { return encode(text); } /** * 还原被转义的HTML特殊字符 * * @param content 包含转义符的HTML内容 * @return 转换后的字符串 */ public static String unescape(String content) { return decode(content); } /** * 清除所有HTML标签,但是不删除标签内的内容 * * @param content 文本 * @return 清除标签后的文本 */ public static String clean(String content) { return new HTMLFilter().filter(content); } /** * Escape编码 * * @param text 被编码的文本 * @return 编码后的字符 */ private static String encode(String text) {<FILL_FUNCTION_BODY>} /** * Escape解码 * * @param content 被转义的内容 * @return 解码后的字符串 */ public static String decode(String content) { if (StringUtils.isEmpty(content)) { return content; } StringBuilder tmp = new StringBuilder(content.length()); int lastPos = 0, pos = 0; char ch; while (lastPos < content.length()) { pos = content.indexOf("%", lastPos); if (pos == lastPos) { if (content.charAt(pos + 1) == 'u') { ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16); tmp.append(ch); lastPos = pos + 6; } else { ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16); tmp.append(ch); lastPos = pos + 3; } } else { if (pos == -1) { tmp.append(content.substring(lastPos)); lastPos = content.length(); } else { tmp.append(content.substring(lastPos, pos)); lastPos = pos; } } } return tmp.toString(); } public static void main(String[] args) { String html = "<script>alert(1);</script>"; String escape = EscapeUtil.escape(html); // String html = "<scr<script>ipt>alert(\"XSS\")</scr<script>ipt>"; // String html = "<123"; // String html = "123>"; System.out.println("clean: " + EscapeUtil.clean(html)); System.out.println("escape: " + escape); System.out.println("unescape: " + EscapeUtil.unescape(escape)); } }
if (StringUtils.isEmpty(text)) { return StringUtils.EMPTY; } final StringBuilder tmp = new StringBuilder(text.length() * 6); char c; for (int i = 0; i < text.length(); i++) { c = text.charAt(i); if (c < 256) { tmp.append("%"); if (c < 16) { tmp.append("0"); } tmp.append(Integer.toString(c, 16)); } else { tmp.append("%u"); if (c <= 0xfff) { // issue#I49JU8@Gitee tmp.append("0"); } tmp.append(Integer.toString(c, 16)); } } return tmp.toString();
1,207
263
1,470
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/http/HttpHelper.java
HttpHelper
getBodyString
class HttpHelper { private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class); public static String getBodyString(ServletRequest request) {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try (InputStream inputStream = request.getInputStream()) { reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { LOGGER.warn("getBodyString出现问题!"); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LOGGER.error(ExceptionUtils.getMessage(e)); } } } return sb.toString();
65
232
297
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/ip/AddressUtils.java
AddressUtils
getRealAddressByIP
class AddressUtils { private static final Logger log = LoggerFactory.getLogger(AddressUtils.class); // IP地址查询 public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"; // 未知地址 public static final String UNKNOWN = "XX XX"; public static String getRealAddressByIP(String ip) {<FILL_FUNCTION_BODY>} }
// 内网不查询 if (IpUtils.internalIp(ip)) { return "内网IP"; } if (RuoYiConfig.isAddressEnabled()) { try { String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&json=true", Constants.GBK); if (StringUtils.isEmpty(rspStr)) { log.error("获取地理位置异常 {}", ip); return UNKNOWN; } JSONObject obj = JSON.parseObject(rspStr); String region = obj.getString("pro"); String city = obj.getString("city"); return String.format("%s %s", region, city); } catch (Exception e) { log.error("获取地理位置异常 {}", ip); } } return UNKNOWN;
132
263
395
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/sign/Md5Utils.java
Md5Utils
md5
class Md5Utils { private static final Logger log = LoggerFactory.getLogger(Md5Utils.class); private static byte[] md5(String s) {<FILL_FUNCTION_BODY>} private static final String toHex(byte hash[]) { if (hash == null) { return null; } StringBuffer buf = new StringBuffer(hash.length * 2); int i; for (i = 0; i < hash.length; i++) { if ((hash[i] & 0xff) < 0x10) { buf.append("0"); } buf.append(Long.toString(hash[i] & 0xff, 16)); } return buf.toString(); } public static String hash(String s) { try { return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8); } catch (Exception e) { log.error("not supported charset...{}", e); return s; } } }
MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte[] messageDigest = algorithm.digest(); return messageDigest; } catch (Exception e) { log.error("MD5 Error...", e); } return null;
343
119
462
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/sql/SqlUtil.java
SqlUtil
escapeOrderBySql
class SqlUtil { /** * 定义常用的 sql关键字 */ public static String SQL_REGEX = "and |extractvalue|updatexml|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |+|user()"; /** * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序) */ public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; /** * 限制orderBy最大长度 */ private static final int ORDER_BY_MAX_LENGTH = 500; /** * 检查字符,防止注入绕过 */ public static String escapeOrderBySql(String value) {<FILL_FUNCTION_BODY>} /** * 验证 order by 语法是否符合规范 */ public static boolean isValidOrderBySql(String value) { return value.matches(SQL_PATTERN); } /** * SQL关键字检查 */ public static void filterKeyword(String value) { if (StringUtils.isEmpty(value)) { return; } String[] sqlKeywords = StringUtils.split(SQL_REGEX, "\\|"); for (String sqlKeyword : sqlKeywords) { if (StringUtils.indexOfIgnoreCase(value, sqlKeyword) > -1) { throw new UtilException("参数存在SQL注入风险"); } } } }
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { throw new UtilException("参数不符合规范,不能进行查询"); } if (StringUtils.length(value) > ORDER_BY_MAX_LENGTH) { throw new UtilException("参数已超过最大限制,不能进行查询"); } return value;
473
109
582
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/utils/uuid/Seq.java
Seq
getSeq
class Seq { // 通用序列类型 public static final String commSeqType = "COMMON"; // 上传序列类型 public static final String uploadSeqType = "UPLOAD"; // 通用接口序列数 private static AtomicInteger commSeq = new AtomicInteger(1); // 上传接口序列数 private static AtomicInteger uploadSeq = new AtomicInteger(1); // 机器标识 private static final String machineCode = "A"; /** * 获取通用序列号 * * @return 序列值 */ public static String getId() { return getId(commSeqType); } /** * 默认16位序列号 yyMMddHHmmss + 一位机器标识 + 3长度循环递增字符串 * * @return 序列值 */ public static String getId(String type) { AtomicInteger atomicInt = commSeq; if (uploadSeqType.equals(type)) { atomicInt = uploadSeq; } return getId(atomicInt, 3); } /** * 通用接口序列号 yyMMddHHmmss + 一位机器标识 + length长度循环递增字符串 * * @param atomicInt 序列数 * @param length 数值长度 * @return 序列值 */ public static String getId(AtomicInteger atomicInt, int length) { String result = DateUtils.dateTimeNow(); result += machineCode; result += getSeq(atomicInt, length); return result; } /** * 序列循环递增字符串[1, 10 的 (length)幂次方), 用0左补齐length位数 * * @return 序列值 */ private synchronized static String getSeq(AtomicInteger atomicInt, int length) {<FILL_FUNCTION_BODY>} }
// 先取值再+1 int value = atomicInt.getAndIncrement(); // 如果更新后值>=10 的 (length)幂次方则重置为1 int maxSeq = (int) Math.pow(10, length); if (atomicInt.get() >= maxSeq) { atomicInt.set(1); } // 转字符串,用0左补齐 return StringUtils.padl(value, length);
609
140
749
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-common/src/main/java/com/ruoyi/common/xss/XssValidator.java
XssValidator
containsHtml
class XssValidator implements ConstraintValidator<Xss, String> { private static final String HTML_PATTERN = "<(\\S*?)[^>]*>.*?|<.*? />"; @Override public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) { if (StringUtils.isBlank(value)) { return true; } return !containsHtml(value); } public static boolean containsHtml(String value) {<FILL_FUNCTION_BODY>} }
StringBuilder sHtml = new StringBuilder(); Pattern pattern = Pattern.compile(HTML_PATTERN); Matcher matcher = pattern.matcher(value); while (matcher.find()) { sHtml.append(matcher.group()); } return pattern.matcher(sHtml).matches();
157
95
252
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataScopeAspect.java
DataScopeAspect
dataScopeFilter
class DataScopeAspect { /** * 全部数据权限 */ public static final String DATA_SCOPE_ALL = "1"; /** * 自定数据权限 */ public static final String DATA_SCOPE_CUSTOM = "2"; /** * 部门数据权限 */ public static final String DATA_SCOPE_DEPT = "3"; /** * 部门及以下数据权限 */ public static final String DATA_SCOPE_DEPT_AND_CHILD = "4"; /** * 仅本人数据权限 */ public static final String DATA_SCOPE_SELF = "5"; /** * 数据权限过滤关键字 */ public static final String DATA_SCOPE = "dataScope"; @Before("@annotation(controllerDataScope)") public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable { clearDataScope(point); handleDataScope(point, controllerDataScope); } protected void handleDataScope(final JoinPoint joinPoint, DataScope controllerDataScope) { // 获取当前的用户 LoginUser loginUser = SecurityUtils.getLoginUser(); if (StringUtils.isNotNull(loginUser)) { SysUser currentUser = loginUser.getUser(); // 如果是超级管理员,则不过滤数据 if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin()) { String permission = StringUtils.defaultIfEmpty(controllerDataScope.permission(), PermissionContextHolder.getContext()); dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(), controllerDataScope.userAlias(), permission); } } } /** * 数据范围过滤 * * @param joinPoint 切点 * @param user 用户 * @param deptAlias 部门别名 * @param userAlias 用户别名 * @param permission 权限字符 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias, String permission) {<FILL_FUNCTION_BODY>} /** * 拼接权限sql前先清空params.dataScope参数防止注入 */ private void clearDataScope(final JoinPoint joinPoint) { Object params = joinPoint.getArgs()[0]; if (StringUtils.isNotNull(params) && params instanceof BaseEntity) { BaseEntity baseEntity = (BaseEntity) params; baseEntity.getParams().put(DATA_SCOPE, ""); } } }
StringBuilder sqlString = new StringBuilder(); List<String> conditions = new ArrayList<String>(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (!DATA_SCOPE_CUSTOM.equals(dataScope) && conditions.contains(dataScope)) { continue; } if (StringUtils.isNotEmpty(permission) && StringUtils.isNotEmpty(role.getPermissions()) && !StringUtils.containsAny(role.getPermissions(), Convert.toStrArray(permission))) { continue; } if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); conditions.add(dataScope); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId())); } else if (DATA_SCOPE_DEPT.equals(dataScope)) { sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", deptAlias, user.getDeptId(), user.getDeptId())); } else if (DATA_SCOPE_SELF.equals(dataScope)) { if (StringUtils.isNotBlank(userAlias)) { sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); } else { // 数据权限为仅本人且没有userAlias别名不查询任何数据 sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias)); } } conditions.add(dataScope); } // 多角色情况下,所有角色都不包含传递过来的权限字符,这个时候sqlString也会为空,所以要限制一下,不查询任何数据 if (StringUtils.isEmpty(conditions)) { sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias)); } if (StringUtils.isNotBlank(sqlString.toString())) { Object params = joinPoint.getArgs()[0]; if (StringUtils.isNotNull(params) && params instanceof BaseEntity) { BaseEntity baseEntity = (BaseEntity) params; baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); } }
783
856
1,639
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java
DataSourceAspect
around
class DataSourceAspect { protected Logger logger = LoggerFactory.getLogger(getClass()); @Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)" + "|| @within(com.ruoyi.common.annotation.DataSource)") public void dsPointCut() { } @Around("dsPointCut()") public Object around(ProceedingJoinPoint point) throws Throwable {<FILL_FUNCTION_BODY>} /** * 获取需要切换的数据源 */ public DataSource getDataSource(ProceedingJoinPoint point) { MethodSignature signature = (MethodSignature) point.getSignature(); DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class); if (Objects.nonNull(dataSource)) { return dataSource; } return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class); } }
DataSource dataSource = getDataSource(point); if (StringUtils.isNotNull(dataSource)) { DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name()); } try { return point.proceed(); } finally { // 销毁数据源 在执行方法之后 DynamicDataSourceContextHolder.clearDataSourceType(); }
286
128
414
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/RateLimiterAspect.java
RateLimiterAspect
doBefore
class RateLimiterAspect { private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class); private RedisTemplate<Object, Object> redisTemplate; private RedisScript<Long> limitScript; @Autowired public void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate) { this.redisTemplate = redisTemplate; } @Autowired public void setLimitScript(RedisScript<Long> limitScript) { this.limitScript = limitScript; } @Before("@annotation(rateLimiter)") public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable {<FILL_FUNCTION_BODY>} public String getCombineKey(RateLimiter rateLimiter, JoinPoint point) { StringBuffer stringBuffer = new StringBuffer(rateLimiter.key()); if (rateLimiter.limitType() == LimitType.IP) { stringBuffer.append(IpUtils.getIpAddr()).append("-"); } MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Class<?> targetClass = method.getDeclaringClass(); stringBuffer.append(targetClass.getName()).append("-").append(method.getName()); return stringBuffer.toString(); } }
int time = rateLimiter.time(); int count = rateLimiter.count(); String combineKey = getCombineKey(rateLimiter, point); List<Object> keys = Collections.singletonList(combineKey); try { Long number = redisTemplate.execute(limitScript, keys, count, time); if (StringUtils.isNull(number) || number.intValue() > count) { throw new ServiceException("访问过于频繁,请稍候再试"); } log.info("限制请求'{}',当前请求'{}',缓存key'{}'", count, number.intValue(), combineKey); } catch (ServiceException e) { throw e; } catch (Exception e) { throw new RuntimeException("服务器限流异常,请稍候再试"); }
407
247
654
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/CaptchaConfig.java
CaptchaConfig
getKaptchaBeanMath
class CaptchaConfig { @Bean(name = "captchaProducer") public DefaultKaptcha getKaptchaBean() { DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); // 是否有边框 默认为true 我们可以自己设置yes,no properties.setProperty(KAPTCHA_BORDER, "yes"); // 验证码文本字符颜色 默认为Color.BLACK properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black"); // 验证码图片宽度 默认为200 properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); // 验证码图片高度 默认为50 properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); // 验证码文本字符大小 默认为40 properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38"); // KAPTCHA_SESSION_KEY properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode"); // 验证码文本字符长度 默认为5 properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4"); // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha; } @Bean(name = "captchaProducerMath") public DefaultKaptcha getKaptchaBeanMath() {<FILL_FUNCTION_BODY>} }
DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); Properties properties = new Properties(); // 是否有边框 默认为true 我们可以自己设置yes,no properties.setProperty(KAPTCHA_BORDER, "yes"); // 边框颜色 默认为Color.BLACK properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90"); // 验证码文本字符颜色 默认为Color.BLACK properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue"); // 验证码图片宽度 默认为200 properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160"); // 验证码图片高度 默认为50 properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60"); // 验证码文本字符大小 默认为40 properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35"); // KAPTCHA_SESSION_KEY properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath"); // 验证码文本生成器 properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.ruoyi.framework.config.KaptchaTextCreator"); // 验证码文本字符间距 默认为2 properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3"); // 验证码文本字符长度 默认为5 properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6"); // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize) properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier"); // 验证码噪点颜色 默认为Color.BLACK properties.setProperty(KAPTCHA_NOISE_COLOR, "white"); // 干扰实现类 properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise"); // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy"); Config config = new Config(properties); defaultKaptcha.setConfig(config); return defaultKaptcha;
617
762
1,379
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/DruidConfig.java
DruidConfig
dataSource
class DruidConfig { @Bean @ConfigurationProperties("spring.datasource.druid.master") public DataSource masterDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean @ConfigurationProperties("spring.datasource.druid.slave") @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true") public DataSource slaveDataSource(DruidProperties druidProperties) { DruidDataSource dataSource = DruidDataSourceBuilder.create().build(); return druidProperties.dataSource(dataSource); } @Bean(name = "dynamicDataSource") @Primary public DynamicDataSource dataSource(DataSource masterDataSource) {<FILL_FUNCTION_BODY>} /** * 设置数据源 * * @param targetDataSources 备选数据源集合 * @param sourceName 数据源名称 * @param beanName bean名称 */ public void setDataSource(Map<Object, Object> targetDataSources, String sourceName, String beanName) { try { DataSource dataSource = SpringUtils.getBean(beanName); targetDataSources.put(sourceName, dataSource); } catch (Exception e) { } } /** * 去除监控页面底部的广告 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Bean @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true") public FilterRegistrationBean removeDruidFilterRegistrationBean(DruidStatProperties properties) { // 获取web监控页面的参数 DruidStatProperties.StatViewServlet config = properties.getStatViewServlet(); // 提取common.js的配置路径 String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*"; String commonJsPattern = pattern.replaceAll("\\*", "js/common.js"); final String filePath = "support/http/resources/js/common.js"; // 创建filter进行过滤 Filter filter = new Filter() { @Override public void init(javax.servlet.FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); // 重置缓冲区,响应头不会被重置 response.resetBuffer(); // 获取common.js String text = Utils.readFromResource(filePath); // 正则替换banner, 除去底部的广告信息 text = text.replaceAll("<a.*?banner\"></a><br/>", ""); text = text.replaceAll("powered.*?shrek.wang</a>", ""); response.getWriter().write(text); } @Override public void destroy() { } }; FilterRegistrationBean registrationBean = new FilterRegistrationBean(); registrationBean.setFilter(filter); registrationBean.addUrlPatterns(commonJsPattern); return registrationBean; } }
Map<Object, Object> targetDataSources = new HashMap<>(); targetDataSources.put(DataSourceType.MASTER.name(), masterDataSource); setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource"); return new DynamicDataSource(masterDataSource, targetDataSources);
991
92
1,083
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java
FastJson2JsonRedisSerializer
deserialize
class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(Constants.JSON_WHITELIST_STR); private Class<T> clazz; public FastJson2JsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); } @Override public T deserialize(byte[] bytes) throws SerializationException {<FILL_FUNCTION_BODY>} }
if (bytes == null || bytes.length <= 0) { return null; } String str = new String(bytes, DEFAULT_CHARSET); return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER);
267
74
341
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/FilterConfig.java
FilterConfig
xssFilterRegistration
class FilterConfig { @Value("${xss.excludes}") private String excludes; @Value("${xss.urlPatterns}") private String urlPatterns; @SuppressWarnings({ "rawtypes", "unchecked" }) @Bean @ConditionalOnProperty(value = "xss.enabled", havingValue = "true") public FilterRegistrationBean xssFilterRegistration() {<FILL_FUNCTION_BODY>} @SuppressWarnings({ "rawtypes", "unchecked" }) @Bean public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new RepeatableFilter()); registration.addUrlPatterns("/*"); registration.setName("repeatableFilter"); registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); return registration; } }
FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setDispatcherTypes(DispatcherType.REQUEST); registration.setFilter(new XssFilter()); registration.addUrlPatterns(StringUtils.split(urlPatterns, ",")); registration.setName("xssFilter"); registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE); Map<String, String> initParameters = new HashMap<String, String>(); initParameters.put("excludes", excludes); registration.setInitParameters(initParameters); return registration;
269
158
427
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/I18nConfig.java
I18nConfig
localeChangeInterceptor
class I18nConfig implements WebMvcConfigurer { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver slr = new SessionLocaleResolver(); // 默认语言 slr.setDefaultLocale(Constants.DEFAULT_LOCALE); return slr; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() {<FILL_FUNCTION_BODY>} @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } }
LocaleChangeInterceptor lci = new LocaleChangeInterceptor(); // 参数名 lci.setParamName("lang"); return lci;
159
45
204
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/KaptchaTextCreator.java
KaptchaTextCreator
getText
class KaptchaTextCreator extends DefaultTextCreator { private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(","); @Override public String getText() {<FILL_FUNCTION_BODY>} }
Integer result = 0; Random random = new Random(); int x = random.nextInt(10); int y = random.nextInt(10); StringBuilder suChinese = new StringBuilder(); int randomoperands = random.nextInt(3); if (randomoperands == 0) { result = x * y; suChinese.append(CNUMBERS[x]); suChinese.append("*"); suChinese.append(CNUMBERS[y]); } else if (randomoperands == 1) { if ((x != 0) && y % x == 0) { result = y / x; suChinese.append(CNUMBERS[y]); suChinese.append("/"); suChinese.append(CNUMBERS[x]); } else { result = x + y; suChinese.append(CNUMBERS[x]); suChinese.append("+"); suChinese.append(CNUMBERS[y]); } } else { if (x >= y) { result = x - y; suChinese.append(CNUMBERS[x]); suChinese.append("-"); suChinese.append(CNUMBERS[y]); } else { result = y - x; suChinese.append(CNUMBERS[y]); suChinese.append("-"); suChinese.append(CNUMBERS[x]); } } suChinese.append("=?@" + result); return suChinese.toString();
84
429
513
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/MyBatisConfig.java
MyBatisConfig
setTypeAliasesPackage
class MyBatisConfig { @Autowired private Environment env; static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; public static String setTypeAliasesPackage(String typeAliasesPackage) {<FILL_FUNCTION_BODY>} public Resource[] resolveMapperLocations(String[] mapperLocations) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); List<Resource> resources = new ArrayList<Resource>(); if (mapperLocations != null) { for (String mapperLocation : mapperLocations) { try { Resource[] mappers = resourceResolver.getResources(mapperLocation); resources.addAll(Arrays.asList(mappers)); } catch (IOException e) { // ignore } } } return resources.toArray(new Resource[resources.size()]); } @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); String mapperLocations = env.getProperty("mybatis.mapperLocations"); String configLocation = env.getProperty("mybatis.configLocation"); typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage); VFS.addImplClass(SpringBootVFS.class); final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setTypeAliasesPackage(typeAliasesPackage); sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ","))); sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); return sessionFactory.getObject(); } }
ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); List<String> allResult = new ArrayList<String>(); try { for (String aliasesPackage : typeAliasesPackage.split(",")) { List<String> result = new ArrayList<String>(); aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; Resource[] resources = resolver.getResources(aliasesPackage); if (resources != null && resources.length > 0) { MetadataReader metadataReader = null; for (Resource resource : resources) { if (resource.isReadable()) { metadataReader = metadataReaderFactory.getMetadataReader(resource); try { result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } if (result.size() > 0) { HashSet<String> hashResult = new HashSet<String>(result); allResult.addAll(hashResult); } } if (allResult.size() > 0) { typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); } else { throw new RuntimeException("mybatis typeAliasesPackage 路径扫描错误,参数typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); } } catch (IOException e) { e.printStackTrace(); } return typeAliasesPackage;
522
532
1,054
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/RedisConfig.java
RedisConfig
redisTemplate
class RedisConfig extends CachingConfigurerSupport { @Bean @SuppressWarnings(value = { "unchecked", "rawtypes" }) public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {<FILL_FUNCTION_BODY>} @Bean public DefaultRedisScript<Long> limitScript() { DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(); redisScript.setScriptText(limitScriptText()); redisScript.setResultType(Long.class); return redisScript; } /** * 限流脚本 */ private String limitScriptText() { return "local key = KEYS[1]\n" + "local count = tonumber(ARGV[1])\n" + "local time = tonumber(ARGV[2])\n" + "local current = redis.call('get', key);\n" + "if current and tonumber(current) > count then\n" + " return tonumber(current);\n" + "end\n" + "current = redis.call('incr', key)\n" + "if tonumber(current) == 1 then\n" + " redis.call('expire', key, time)\n" + "end\n" + "return tonumber(current);"; } }
RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class); // 使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.setValueSerializer(serializer); // Hash的key也采用StringRedisSerializer的序列化方式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(serializer); template.afterPropertiesSet(); return template;
401
182
583
<methods>public void <init>() ,public org.springframework.cache.CacheManager cacheManager() ,public org.springframework.cache.interceptor.CacheResolver cacheResolver() ,public org.springframework.cache.interceptor.CacheErrorHandler errorHandler() ,public org.springframework.cache.interceptor.KeyGenerator keyGenerator() <variables>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ResourcesConfig.java
ResourcesConfig
corsFilter
class ResourcesConfig implements WebMvcConfigurer { @Autowired private RepeatSubmitInterceptor repeatSubmitInterceptor; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** 本地文件上传路径 */ registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**") .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/"); /** swagger配置 */ registry.addResourceHandler("/swagger-ui/**") .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/") .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic());; } /** * 自定义拦截规则 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**"); } /** * 跨域配置 */ @Bean public CorsFilter corsFilter() {<FILL_FUNCTION_BODY>} }
CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); // 设置访问源地址 config.addAllowedOriginPattern("*"); // 设置访问源请求头 config.addAllowedHeader("*"); // 设置访问源请求方法 config.addAllowedMethod("*"); // 有效期 1800秒 config.setMaxAge(1800L); // 添加映射路径,拦截一切请求 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); // 返回新的CorsFilter return new CorsFilter(source);
342
200
542
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
SecurityConfig
configure
class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 自定义用户认证逻辑 */ @Autowired private UserDetailsService userDetailsService; /** * 认证失败处理类 */ @Autowired private AuthenticationEntryPointImpl unauthorizedHandler; /** * 退出处理类 */ @Autowired private LogoutSuccessHandlerImpl logoutSuccessHandler; /** * token认证过滤器 */ @Autowired private JwtAuthenticationTokenFilter authenticationTokenFilter; /** * 跨域过滤器 */ @Autowired private CorsFilter corsFilter; /** * 允许匿名访问的地址 */ @Autowired private PermitAllUrlProperties permitAllUrl; /** * 解决 无法直接注入 AuthenticationManager * * @return * @throws Exception */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * anyRequest | 匹配所有请求路径 * access | SpringEl表达式结果为true时可以访问 * anonymous | 匿名可以访问 * denyAll | 用户不能访问 * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录) * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问 * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问 * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问 * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问 * hasRole | 如果有参数,参数表示角色,则其角色可以访问 * permitAll | 用户可以任意访问 * rememberMe | 允许通过remember-me登录的用户访问 * authenticated | 用户登录后可访问 */ @Override protected void configure(HttpSecurity httpSecurity) throws Exception {<FILL_FUNCTION_BODY>} /** * 强散列哈希加密实现 */ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } /** * 身份认证接口 */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } }
// 注解标记允许匿名访问的url ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests(); permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll()); httpSecurity // CSRF禁用,因为不使用session .csrf().disable() // 禁用HTTP响应标头 .headers().cacheControl().disable().and() // 认证失败处理类 .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // 基于token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() // 过滤请求 .authorizeRequests() // 对于登录login 注册register 验证码captchaImage 允许匿名访问 .antMatchers("/login", "/register", "/captchaImage").permitAll() // 静态资源,可匿名访问 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated() .and() .headers().frameOptions().disable(); // 添加Logout filter httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); // 添加JWT filter httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // 添加CORS filter httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class); httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
796
531
1,327
<methods>public org.springframework.security.authentication.AuthenticationManager authenticationManagerBean() throws java.lang.Exception,public void configure(org.springframework.security.config.annotation.web.builders.WebSecurity) throws java.lang.Exception,public void init(org.springframework.security.config.annotation.web.builders.WebSecurity) throws java.lang.Exception,public void setApplicationContext(org.springframework.context.ApplicationContext) ,public void setAuthenticationConfiguration(org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration) ,public void setContentNegotationStrategy(org.springframework.web.accept.ContentNegotiationStrategy) ,public void setObjectPostProcessor(ObjectPostProcessor<java.lang.Object>) ,public void setTrustResolver(org.springframework.security.authentication.AuthenticationTrustResolver) ,public org.springframework.security.core.userdetails.UserDetailsService userDetailsServiceBean() throws java.lang.Exception<variables>private org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder authenticationBuilder,private org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration authenticationConfiguration,private org.springframework.security.authentication.AuthenticationManager authenticationManager,private boolean authenticationManagerInitialized,private org.springframework.web.accept.ContentNegotiationStrategy contentNegotiationStrategy,private org.springframework.context.ApplicationContext context,private boolean disableDefaults,private boolean disableLocalConfigureAuthenticationBldr,private org.springframework.security.config.annotation.web.builders.HttpSecurity http,private org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder localConfigureAuthenticationBldr,private final org.apache.commons.logging.Log logger,private ObjectPostProcessor<java.lang.Object> objectPostProcessor,private org.springframework.security.authentication.AuthenticationTrustResolver trustResolver
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ServerConfig.java
ServerConfig
getDomain
class ServerConfig { /** * 获取完整的请求路径,包括:域名,端口,上下文访问路径 * * @return 服务地址 */ public String getUrl() { HttpServletRequest request = ServletUtils.getRequest(); return getDomain(request); } public static String getDomain(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
StringBuffer url = request.getRequestURL(); String contextPath = request.getServletContext().getContextPath(); return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
131
66
197
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/ThreadPoolConfig.java
ThreadPoolConfig
threadPoolTaskExecutor
class ThreadPoolConfig { // 核心线程池大小 private int corePoolSize = 50; // 最大可创建的线程数 private int maxPoolSize = 200; // 队列最大长度 private int queueCapacity = 1000; // 线程池维护线程所允许的空闲时间 private int keepAliveSeconds = 300; @Bean(name = "threadPoolTaskExecutor") public ThreadPoolTaskExecutor threadPoolTaskExecutor() {<FILL_FUNCTION_BODY>} /** * 执行周期性或定时任务 */ @Bean(name = "scheduledExecutorService") protected ScheduledExecutorService scheduledExecutorService() { return new ScheduledThreadPoolExecutor(corePoolSize, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build(), new ThreadPoolExecutor.CallerRunsPolicy()) { @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); Threads.printException(r, t); } }; } }
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setMaxPoolSize(maxPoolSize); executor.setCorePoolSize(corePoolSize); executor.setQueueCapacity(queueCapacity); executor.setKeepAliveSeconds(keepAliveSeconds); // 线程池对拒绝任务(无线程可用)的处理策略 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); return executor;
344
135
479
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/DruidProperties.java
DruidProperties
dataSource
class DruidProperties { @Value("${spring.datasource.druid.initialSize}") private int initialSize; @Value("${spring.datasource.druid.minIdle}") private int minIdle; @Value("${spring.datasource.druid.maxActive}") private int maxActive; @Value("${spring.datasource.druid.maxWait}") private int maxWait; @Value("${spring.datasource.druid.connectTimeout}") private int connectTimeout; @Value("${spring.datasource.druid.socketTimeout}") private int socketTimeout; @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}") private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}") private int minEvictableIdleTimeMillis; @Value("${spring.datasource.druid.maxEvictableIdleTimeMillis}") private int maxEvictableIdleTimeMillis; @Value("${spring.datasource.druid.validationQuery}") private String validationQuery; @Value("${spring.datasource.druid.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.datasource.druid.testOnBorrow}") private boolean testOnBorrow; @Value("${spring.datasource.druid.testOnReturn}") private boolean testOnReturn; public DruidDataSource dataSource(DruidDataSource datasource) {<FILL_FUNCTION_BODY>} }
/** 配置初始化大小、最小、最大 */ datasource.setInitialSize(initialSize); datasource.setMaxActive(maxActive); datasource.setMinIdle(minIdle); /** 配置获取连接等待超时的时间 */ datasource.setMaxWait(maxWait); /** 配置驱动连接超时时间,检测数据库建立连接的超时时间,单位是毫秒 */ datasource.setConnectTimeout(connectTimeout); /** 配置网络超时时间,等待数据库操作完成的网络超时时间,单位是毫秒 */ datasource.setSocketTimeout(socketTimeout); /** 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 */ datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); /** 配置一个连接在池中最小、最大生存的时间,单位是毫秒 */ datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); datasource.setMaxEvictableIdleTimeMillis(maxEvictableIdleTimeMillis); /** * 用来检测连接是否有效的sql,要求是一个查询语句,常用select 'x'。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。 */ datasource.setValidationQuery(validationQuery); /** 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 */ datasource.setTestWhileIdle(testWhileIdle); /** 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */ datasource.setTestOnBorrow(testOnBorrow); /** 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 */ datasource.setTestOnReturn(testOnReturn); return datasource;
518
540
1,058
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/config/properties/PermitAllUrlProperties.java
PermitAllUrlProperties
afterPropertiesSet
class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware { private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}"); private ApplicationContext applicationContext; private List<String> urls = new ArrayList<>(); public String ASTERISK = "*"; @Override public void afterPropertiesSet() {<FILL_FUNCTION_BODY>} @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.applicationContext = context; } public List<String> getUrls() { return urls; } public void setUrls(List<String> urls) { this.urls = urls; } }
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class); Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods(); map.keySet().forEach(info -> { HandlerMethod handlerMethod = map.get(info); // 获取方法上边的注解 替代path variable 为 * Anonymous method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Anonymous.class); Optional.ofNullable(method).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns()) .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)))); // 获取类上边的注解, 替代path variable 为 * Anonymous controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Anonymous.class); Optional.ofNullable(controller).ifPresent(anonymous -> Objects.requireNonNull(info.getPatternsCondition().getPatterns()) .forEach(url -> urls.add(RegExUtils.replaceAll(url, PATTERN, ASTERISK)))); });
229
312
541
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/RepeatSubmitInterceptor.java
RepeatSubmitInterceptor
preHandle
class RepeatSubmitInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {<FILL_FUNCTION_BODY>} /** * 验证是否重复提交由子类实现具体的防重复提交的规则 * * @param request 请求信息 * @param annotation 防重复注解参数 * @return 结果 * @throws Exception */ public abstract boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation); }
if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class); if (annotation != null) { if (this.isRepeatSubmit(request, annotation)) { AjaxResult ajaxResult = AjaxResult.error(annotation.message()); ServletUtils.renderString(response, JSON.toJSONString(ajaxResult)); return false; } } return true; } else { return true; }
166
185
351
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/interceptor/impl/SameUrlDataInterceptor.java
SameUrlDataInterceptor
isRepeatSubmit
class SameUrlDataInterceptor extends RepeatSubmitInterceptor { public final String REPEAT_PARAMS = "repeatParams"; public final String REPEAT_TIME = "repeatTime"; // 令牌自定义标识 @Value("${token.header}") private String header; @Autowired private RedisCache redisCache; @SuppressWarnings("unchecked") @Override public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) {<FILL_FUNCTION_BODY>} /** * 判断参数是否相同 */ private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) { String nowParams = (String) nowMap.get(REPEAT_PARAMS); String preParams = (String) preMap.get(REPEAT_PARAMS); return nowParams.equals(preParams); } /** * 判断两次间隔时间 */ private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval) { long time1 = (Long) nowMap.get(REPEAT_TIME); long time2 = (Long) preMap.get(REPEAT_TIME); if ((time1 - time2) < interval) { return true; } return false; } }
String nowParams = ""; if (request instanceof RepeatedlyRequestWrapper) { RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request; nowParams = HttpHelper.getBodyString(repeatedlyRequest); } // body参数为空,获取Parameter的数据 if (StringUtils.isEmpty(nowParams)) { nowParams = JSON.toJSONString(request.getParameterMap()); } Map<String, Object> nowDataMap = new HashMap<String, Object>(); nowDataMap.put(REPEAT_PARAMS, nowParams); nowDataMap.put(REPEAT_TIME, System.currentTimeMillis()); // 请求地址(作为存放cache的key值) String url = request.getRequestURI(); // 唯一值(没有消息头则使用请求地址) String submitKey = StringUtils.trimToEmpty(request.getHeader(header)); // 唯一标识(指定key + url + 消息头) String cacheRepeatKey = CacheConstants.REPEAT_SUBMIT_KEY + url + submitKey; Object sessionObj = redisCache.getCacheObject(cacheRepeatKey); if (sessionObj != null) { Map<String, Object> sessionMap = (Map<String, Object>) sessionObj; if (sessionMap.containsKey(url)) { Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url); if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) { return true; } } } Map<String, Object> cacheMap = new HashMap<String, Object>(); cacheMap.put(url, nowDataMap); redisCache.setCacheObject(cacheRepeatKey, cacheMap, annotation.interval(), TimeUnit.MILLISECONDS); return false;
411
547
958
<methods>public non-sealed void <init>() ,public abstract boolean isRepeatSubmit(javax.servlet.http.HttpServletRequest, com.ruoyi.common.annotation.RepeatSubmit) ,public boolean preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) throws java.lang.Exception<variables>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/ShutdownManager.java
ShutdownManager
shutdownAsyncManager
class ShutdownManager { private static final Logger logger = LoggerFactory.getLogger("sys-user"); @PreDestroy public void destroy() { shutdownAsyncManager(); } /** * 停止异步执行任务 */ private void shutdownAsyncManager() {<FILL_FUNCTION_BODY>} }
try { logger.info("====关闭后台任务任务线程池===="); AsyncManager.me().shutdown(); } catch (Exception e) { logger.error(e.getMessage(), e); }
108
76
184
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/manager/factory/AsyncFactory.java
AsyncFactory
run
class AsyncFactory { private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user"); /** * 记录登录信息 * * @param username 用户名 * @param status 状态 * @param message 消息 * @param args 列表 * @return 任务task */ public static TimerTask recordLogininfor(final String username, final String status, final String message, final Object... args) { final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); final String ip = IpUtils.getIpAddr(); return new TimerTask() { @Override public void run() {<FILL_FUNCTION_BODY>} }; } /** * 操作日志记录 * * @param operLog 操作日志信息 * @return 任务task */ public static TimerTask recordOper(final SysOperLog operLog) { return new TimerTask() { @Override public void run() { // 远程查询操作地点 operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp())); SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog); } }; } }
String address = AddressUtils.getRealAddressByIP(ip); StringBuilder s = new StringBuilder(); s.append(LogUtils.getBlock(ip)); s.append(address); s.append(LogUtils.getBlock(username)); s.append(LogUtils.getBlock(status)); s.append(LogUtils.getBlock(message)); // 打印信息到日志 sys_user_logger.info(s.toString(), args); // 获取客户端操作系统 String os = userAgent.getOperatingSystem().getName(); // 获取客户端浏览器 String browser = userAgent.getBrowser().getName(); // 封装对象 SysLogininfor logininfor = new SysLogininfor(); logininfor.setUserName(username); logininfor.setIpaddr(ip); logininfor.setLoginLocation(address); logininfor.setBrowser(browser); logininfor.setOs(os); logininfor.setMsg(message); // 日志状态 if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) { logininfor.setStatus(Constants.SUCCESS); } else if (Constants.LOGIN_FAIL.equals(status)) { logininfor.setStatus(Constants.FAIL); } // 插入数据 SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
411
429
840
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/security/filter/JwtAuthenticationTokenFilter.java
JwtAuthenticationTokenFilter
doFilterInternal
class JwtAuthenticationTokenFilter extends OncePerRequestFilter { @Autowired private TokenService tokenService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {<FILL_FUNCTION_BODY>} }
LoginUser loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) { tokenService.verifyToken(loginUser); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()); authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(authenticationToken); } chain.doFilter(request, response);
90
148
238
<methods>public void <init>() ,public final void doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) throws javax.servlet.ServletException, java.io.IOException<variables>public static final java.lang.String ALREADY_FILTERED_SUFFIX
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/AuthenticationEntryPointImpl.java
AuthenticationEntryPointImpl
commence
class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable { private static final long serialVersionUID = -8970718410437077606L; @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {<FILL_FUNCTION_BODY>} }
int code = HttpStatus.UNAUTHORIZED; String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI()); ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
104
81
185
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/security/handle/LogoutSuccessHandlerImpl.java
LogoutSuccessHandlerImpl
onLogoutSuccess
class LogoutSuccessHandlerImpl implements LogoutSuccessHandler { @Autowired private TokenService tokenService; /** * 退出处理 * * @return */ @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {<FILL_FUNCTION_BODY>} }
LoginUser loginUser = tokenService.getLoginUser(request); if (StringUtils.isNotNull(loginUser)) { String userName = loginUser.getUsername(); // 删除用户缓存记录 tokenService.delLoginUser(loginUser.getToken()); // 记录用户退出日志 AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success"))); } ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.success(MessageUtils.message("user.logout.success"))));
118
174
292
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java
GlobalExceptionHandler
handleRuntimeException
class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 权限校验异常 */ @ExceptionHandler(AccessDeniedException.class) public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage()); return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权"); } /** * 请求方式不支持 */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod()); return AjaxResult.error(e.getMessage()); } /** * 业务异常 */ @ExceptionHandler(ServiceException.class) public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) { log.error(e.getMessage(), e); Integer code = e.getCode(); return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage()); } /** * 请求路径中缺少必需的路径变量 */ @ExceptionHandler(MissingPathVariableException.class) public AjaxResult handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e); return AjaxResult.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName())); } /** * 请求参数类型不匹配 */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) public AjaxResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e); return AjaxResult.error(String.format("请求参数类型不匹配,参数[%s]要求类型为:'%s',但输入值为:'%s'", e.getName(), e.getRequiredType().getName(), e.getValue())); } /** * 拦截未知的运行时异常 */ @ExceptionHandler(RuntimeException.class) public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {<FILL_FUNCTION_BODY>} /** * 系统异常 */ @ExceptionHandler(Exception.class) public AjaxResult handleException(Exception e, HttpServletRequest request) { String requestURI = request.getRequestURI(); log.error("请求地址'{}',发生系统异常.", requestURI, e); return AjaxResult.error(e.getMessage()); } /** * 自定义验证异常 */ @ExceptionHandler(BindException.class) public AjaxResult handleBindException(BindException e) { log.error(e.getMessage(), e); String message = e.getAllErrors().get(0).getDefaultMessage(); return AjaxResult.error(message); } /** * 自定义验证异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error(e.getMessage(), e); String message = e.getBindingResult().getFieldError().getDefaultMessage(); return AjaxResult.error(message); } /** * 演示模式异常 */ @ExceptionHandler(DemoModeException.class) public AjaxResult handleDemoModeException(DemoModeException e) { return AjaxResult.error("演示模式,不允许操作"); } }
String requestURI = request.getRequestURI(); log.error("请求地址'{}',发生未知异常.", requestURI, e); return AjaxResult.error(e.getMessage());
1,214
53
1,267
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/PermissionService.java
PermissionService
hasRole
class PermissionService { /** * 验证用户是否具备某权限 * * @param permission 权限字符串 * @return 用户是否具备某权限 */ public boolean hasPermi(String permission) { if (StringUtils.isEmpty(permission)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) { return false; } PermissionContextHolder.setContext(permission); return hasPermissions(loginUser.getPermissions(), permission); } /** * 验证用户是否不具备某权限,与 hasPermi逻辑相反 * * @param permission 权限字符串 * @return 用户是否不具备某权限 */ public boolean lacksPermi(String permission) { return hasPermi(permission) != true; } /** * 验证用户是否具有以下任意一个权限 * * @param permissions 以 PERMISSION_DELIMETER 为分隔符的权限列表 * @return 用户是否具有以下任意一个权限 */ public boolean hasAnyPermi(String permissions) { if (StringUtils.isEmpty(permissions)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getPermissions())) { return false; } PermissionContextHolder.setContext(permissions); Set<String> authorities = loginUser.getPermissions(); for (String permission : permissions.split(Constants.PERMISSION_DELIMETER)) { if (permission != null && hasPermissions(authorities, permission)) { return true; } } return false; } /** * 判断用户是否拥有某个角色 * * @param role 角色字符串 * @return 用户是否具备某角色 */ public boolean hasRole(String role) {<FILL_FUNCTION_BODY>} /** * 验证用户是否不具备某角色,与 isRole逻辑相反。 * * @param role 角色名称 * @return 用户是否不具备某角色 */ public boolean lacksRole(String role) { return hasRole(role) != true; } /** * 验证用户是否具有以下任意一个角色 * * @param roles 以 ROLE_NAMES_DELIMETER 为分隔符的角色列表 * @return 用户是否具有以下任意一个角色 */ public boolean hasAnyRoles(String roles) { if (StringUtils.isEmpty(roles)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) { return false; } for (String role : roles.split(Constants.ROLE_DELIMETER)) { if (hasRole(role)) { return true; } } return false; } /** * 判断是否包含权限 * * @param permissions 权限列表 * @param permission 权限字符串 * @return 用户是否具备某权限 */ private boolean hasPermissions(Set<String> permissions, String permission) { return permissions.contains(Constants.ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission)); } }
if (StringUtils.isEmpty(role)) { return false; } LoginUser loginUser = SecurityUtils.getLoginUser(); if (StringUtils.isNull(loginUser) || CollectionUtils.isEmpty(loginUser.getUser().getRoles())) { return false; } for (SysRole sysRole : loginUser.getUser().getRoles()) { String roleKey = sysRole.getRoleKey(); if (Constants.SUPER_ADMIN.equals(roleKey) || roleKey.equals(StringUtils.trim(role))) { return true; } } return false;
1,100
184
1,284
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysLoginService.java
SysLoginService
login
class SysLoginService { @Autowired private TokenService tokenService; @Resource private AuthenticationManager authenticationManager; @Autowired private RedisCache redisCache; @Autowired private ISysUserService userService; @Autowired private ISysConfigService configService; /** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) {<FILL_FUNCTION_BODY>} /** * 校验验证码 * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public void validateCaptcha(String username, String code, String uuid) { boolean captchaEnabled = configService.selectCaptchaEnabled(); if (captchaEnabled) { String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, ""); String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); if (captcha == null) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"))); throw new CaptchaExpireException(); } if (!code.equalsIgnoreCase(captcha)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); throw new CaptchaException(); } } } /** * 登录前置校验 * @param username 用户名 * @param password 用户密码 */ public void loginPreCheck(String username, String password) { // 用户名或密码为空 错误 if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"))); throw new UserNotExistsException(); } // 密码如果不在指定范围内 错误 if (password.length() < UserConstants.PASSWORD_MIN_LENGTH || password.length() > UserConstants.PASSWORD_MAX_LENGTH) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } // 用户名不在指定范围内 错误 if (username.length() < UserConstants.USERNAME_MIN_LENGTH || username.length() > UserConstants.USERNAME_MAX_LENGTH) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } // IP黑名单校验 String blackStr = configService.selectConfigByKey("sys.login.blackIPList"); if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked"))); throw new BlackListException(); } } /** * 记录登录信息 * * @param userId 用户ID */ public void recordLoginInfo(Long userId) { SysUser sysUser = new SysUser(); sysUser.setUserId(userId); sysUser.setLoginIp(IpUtils.getIpAddr()); sysUser.setLoginDate(DateUtils.getNowDate()); userService.updateUserProfile(sysUser); } }
// 验证码校验 validateCaptcha(username, code, uuid); // 登录前置校验 loginPreCheck(username, password); // 用户验证 Authentication authentication = null; try { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); AuthenticationContextHolder.setContext(authenticationToken); // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername authentication = authenticationManager.authenticate(authenticationToken); } catch (Exception e) { if (e instanceof BadCredentialsException) { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); throw new UserPasswordNotMatchException(); } else { AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); throw new ServiceException(e.getMessage()); } } finally { AuthenticationContextHolder.clearContext(); } AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); LoginUser loginUser = (LoginUser) authentication.getPrincipal(); recordLoginInfo(loginUser.getUserId()); // 生成token return tokenService.createToken(loginUser);
1,198
422
1,620
<no_super_class>
yangzongzhuan_RuoYi-Vue
RuoYi-Vue/ruoyi-framework/src/main/java/com/ruoyi/framework/web/service/SysPasswordService.java
SysPasswordService
validate
class SysPasswordService { @Autowired private RedisCache redisCache; @Value(value = "${user.password.maxRetryCount}") private int maxRetryCount; @Value(value = "${user.password.lockTime}") private int lockTime; /** * 登录账户密码错误次数缓存键名 * * @param username 用户名 * @return 缓存键key */ private String getCacheKey(String username) { return CacheConstants.PWD_ERR_CNT_KEY + username; } public void validate(SysUser user) {<FILL_FUNCTION_BODY>} public boolean matches(SysUser user, String rawPassword) { return SecurityUtils.matchesPassword(rawPassword, user.getPassword()); } public void clearLoginRecordCache(String loginName) { if (redisCache.hasKey(getCacheKey(loginName))) { redisCache.deleteObject(getCacheKey(loginName)); } } }
Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext(); String username = usernamePasswordAuthenticationToken.getName(); String password = usernamePasswordAuthenticationToken.getCredentials().toString(); Integer retryCount = redisCache.getCacheObject(getCacheKey(username)); if (retryCount == null) { retryCount = 0; } if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) { throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime); } if (!matches(user, password)) { retryCount = retryCount + 1; redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES); throw new UserPasswordNotMatchException(); } else { clearLoginRecordCache(username); }
327
259
586
<no_super_class>