prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) { ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField
= ShareReflectUtil.findField(classLoader, "libPath");
final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class); final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.8140774965286255 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.7925599813461304 }, { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.7790336608886719 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.7756566405296326 }, { "filename": "app/src/main/java/com/example/nativecpp/MainActivity.java", "retrieved_chunk": " File file = new File(path + \"libfingerCore.so\");\n Log.e(\"darren:\", \"info===:\"+ file.exists()+\":\"+ file.canRead());\n DynamicSo.loadStaticSo(file, path);\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n // Example of a call to a native method\n TextView tv = binding.sampleText;\n tv.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {", "score": 0.7686238884925842 } ]
java
= ShareReflectUtil.findField(classLoader, "libPath");
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Dynamic64Structure extends Elf.DynamicStructure { public Dynamic64Structure(final ElfParser parser, final Elf.Header header, long baseOffset, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); baseOffset = baseOffset + (index * 16); tag
= parser.readLong(buffer, baseOffset);
val = parser.readLong(buffer, baseOffset + 0x8); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic64Structure.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic32Structure.java", "retrieved_chunk": " public Dynamic32Structure(final ElfParser parser, final Elf.Header header,\n long baseOffset, final int index) throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n baseOffset = baseOffset + (index * 8);\n tag = parser.readWord(buffer, baseOffset);\n val = parser.readWord(buffer, baseOffset + 0x4);\n }\n}", "score": 0.9482716917991638 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic32Structure.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.example.lib_sillyboy.elf;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\npublic class Dynamic32Structure extends Elf.DynamicStructure {", "score": 0.8925207853317261 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program64Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic64Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.8923209309577942 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.8882466554641724 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.885453462600708 } ]
java
= parser.readLong(buffer, baseOffset);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Dynamic32Structure extends Elf.DynamicStructure { public Dynamic32Structure(final ElfParser parser, final Elf.Header header, long baseOffset, final int index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); baseOffset = baseOffset + (index * 8); tag = parser.readWord(buffer, baseOffset);
val = parser.readWord(buffer, baseOffset + 0x4);
} }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic32Structure.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic64Structure.java", "retrieved_chunk": " public Dynamic64Structure(final ElfParser parser, final Elf.Header header,\n long baseOffset, final int index) throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n baseOffset = baseOffset + (index * 16);\n tag = parser.readLong(buffer, baseOffset);\n val = parser.readLong(buffer, baseOffset + 0x8);\n }\n}", "score": 0.9564992785453796 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.8946746587753296 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Dynamic64Structure.java", "retrieved_chunk": " * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage com.example.lib_sillyboy.elf;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\npublic class Dynamic64Structure extends Elf.DynamicStructure {", "score": 0.8936138153076172 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.8880497217178345 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program32Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic32Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.8879873752593994 } ]
java
val = parser.readWord(buffer, baseOffset + 0x4);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf32Header extends Elf.Header { private final ElfParser parser; public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff
= parser.readWord(buffer, 0x1C);
shoff = parser.readWord(buffer, 0x20); phentsize = parser.readHalf(buffer, 0x2A); phnum = parser.readHalf(buffer, 0x2C); shentsize = parser.readHalf(buffer, 0x2E); shnum = parser.readHalf(buffer, 0x30); shstrndx = parser.readHalf(buffer, 0x32); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section32Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program32Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic32Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9694004058837891 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.9243742227554321 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.9234535694122314 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.916750967502594 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java", "retrieved_chunk": " // Read in ELF identification to determine file class and endianness\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n if (readWord(buffer, 0) != MAGIC) {\n throw new IllegalArgumentException(\"Invalid ELF Magic!\");\n }\n final short fileClass = readByte(buffer, 0x4);\n final boolean bigEndian = (readByte(buffer, 0x5) == Header.ELFDATA2MSB);\n if (fileClass == Header.ELFCLASS32) {\n return new Elf32Header(bigEndian, this);", "score": 0.915269136428833 } ]
java
= parser.readWord(buffer, 0x1C);
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) { ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField = ShareReflectUtil.findField(classLoader, "libPath"); final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class); final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs);
final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class);
final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.7931971549987793 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.7887458801269531 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.777901291847229 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java", "retrieved_chunk": " break;\n }\n }\n if (dynamicSectionOff == 0) {\n // No dynamic linking info, nothing to load\n return Collections.unmodifiableList(dependencies);\n }\n int i = 0;\n final List<Long> neededOffsets = new ArrayList<Long>();\n long vStringTableOff = 0;", "score": 0.7707968950271606 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.7684131860733032 } ]
java
final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class);
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) { ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField = ShareReflectUtil.findField(classLoader, "libPath"); final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field
libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements");
final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class); final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.7824685573577881 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.7807601094245911 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.7646149396896362 }, { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.760391116142273 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java", "retrieved_chunk": " * @param instance the instance whose field is to be modified.\n * @param fieldName the field to modify.\n * @param extraElements elements to append at the end of the array.\n */\n public static void expandFieldArray(Object instance, String fieldName, Object[] extraElements)\n throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n Field jlrField = findField(instance, fieldName);\n Object[] original = (Object[]) jlrField.get(instance);\n Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(), original.length + extraElements.length);\n // NOTE: changed to copy extraElements first, for patch load first", "score": 0.7584655284881592 } ]
java
libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements");
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) {
ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder);
return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField = ShareReflectUtil.findField(classLoader, "libPath"); final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class); final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.847984790802002 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.8216736912727356 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.810254693031311 }, { "filename": "app/src/main/java/com/example/nativecpp/MainActivity.java", "retrieved_chunk": " File file = new File(path + \"libfingerCore.so\");\n Log.e(\"darren:\", \"info===:\"+ file.exists()+\":\"+ file.canRead());\n DynamicSo.loadStaticSo(file, path);\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n // Example of a call to a native method\n TextView tv = binding.sampleText;\n tv.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {", "score": 0.8079433441162109 }, { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.8077865242958069 } ]
java
ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf32Header extends Elf.Header { private final ElfParser parser; public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readWord(buffer, 0x1C); shoff =
parser.readWord(buffer, 0x20);
phentsize = parser.readHalf(buffer, 0x2A); phnum = parser.readHalf(buffer, 0x2C); shentsize = parser.readHalf(buffer, 0x2E); shnum = parser.readHalf(buffer, 0x30); shstrndx = parser.readHalf(buffer, 0x32); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section32Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program32Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic32Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9854620695114136 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.9199123978614807 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.9195820093154907 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9161998629570007 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.912200391292572 } ]
java
parser.readWord(buffer, 0x20);
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) { ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField = ShareReflectUtil.findField(classLoader, "libPath"); final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field
pathListField = ShareReflectUtil.findField(classLoader, "pathList");
final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class); final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.8162583708763123 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.7917079329490662 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.7896983623504639 }, { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.7763681411743164 }, { "filename": "app/src/main/java/com/example/nativecpp/MainActivity.java", "retrieved_chunk": " File file = new File(path + \"libfingerCore.so\");\n Log.e(\"darren:\", \"info===:\"+ file.exists()+\":\"+ file.canRead());\n DynamicSo.loadStaticSo(file, path);\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n // Example of a call to a native method\n TextView tv = binding.sampleText;\n tv.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {", "score": 0.7600260972976685 } ]
java
pathListField = ShareReflectUtil.findField(classLoader, "pathList");
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.tinker; import android.os.Build; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class TinkerLoadLibrary { private static final String TAG = "Tinker.LoadLibrary"; public static void installNativeLibraryPath(ClassLoader classLoader, File folder) throws Throwable { if (folder == null || !folder.exists()) { ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); return; } // android o sdk_int 26 // for android o preview sdk_int 25 if ((Build.VERSION.SDK_INT == 25 && Build.VERSION.PREVIEW_SDK_INT != 0) || Build.VERSION.SDK_INT > 25) { try { V25.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v23 // some preview N version may go here ShareTinkerLog.e(TAG, "installNativeLibraryPath, v25 fail, sdk: %d, error: %s, try to fallback to V23", Build.VERSION.SDK_INT, throwable.getMessage()); V23.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 23) { try { V23.install(classLoader, folder); } catch (Throwable throwable) { // install fail, try to treat it as v14 ShareTinkerLog.e(TAG, "installNativeLibraryPath, v23 fail, sdk: %d, error: %s, try to fallback to V14", Build.VERSION.SDK_INT, throwable.getMessage()); V14.install(classLoader, folder); } } else if (Build.VERSION.SDK_INT >= 14) { V14.install(classLoader, folder); } else { V4.install(classLoader, folder); } } private static final class V4 { private static void install(ClassLoader classLoader, File folder) throws Throwable { String addPath = folder.getPath(); Field pathField = ShareReflectUtil.findField(classLoader, "libPath"); final String origLibPaths = (String) pathField.get(classLoader); final String[] origLibPathSplit = origLibPaths.split(":"); final StringBuilder newLibPaths = new StringBuilder(addPath); for (String origLibPath : origLibPathSplit) { if (origLibPath == null || addPath.equals(origLibPath)) { continue; } newLibPaths.append(':').append(origLibPath); } pathField.set(classLoader, newLibPaths.toString()); final Field libraryPathElementsFiled = ShareReflectUtil.findField(classLoader, "libraryPathElements"); final List<String> libraryPathElements = (List<String>) libraryPathElementsFiled.get(classLoader); final Iterator<String> libPathElementIt = libraryPathElements.iterator(); while (libPathElementIt.hasNext()) { final String libPath = libPathElementIt.next(); if (addPath.equals(libPath)) { libPathElementIt.remove(); break; } } libraryPathElements.add(0, addPath); libraryPathElementsFiled.set(classLoader, libraryPathElements); } } private static final class V14 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibDirField = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); final File[] origNativeLibDirs = (File[]) nativeLibDirField.get(dexPathList); final List<File> newNativeLibDirList = new ArrayList<>(origNativeLibDirs.length + 1); newNativeLibDirList.add(folder); for (File origNativeLibDir : origNativeLibDirs) { if (!folder.equals(origNativeLibDir)) { newNativeLibDirList.add(origNativeLibDir); } } nativeLibDirField.set(dexPathList, newNativeLibDirList.toArray(new File[0])); } } private static final class V23 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method
makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class);
final ArrayList<IOException> suppressedExceptions = new ArrayList<>(); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs, null, suppressedExceptions); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } private static final class V25 { private static void install(ClassLoader classLoader, File folder) throws Throwable { final Field pathListField = ShareReflectUtil.findField(classLoader, "pathList"); final Object dexPathList = pathListField.get(classLoader); final Field nativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "nativeLibraryDirectories"); List<File> origLibDirs = (List<File>) nativeLibraryDirectories.get(dexPathList); if (origLibDirs == null) { origLibDirs = new ArrayList<>(2); } final Iterator<File> libDirIt = origLibDirs.iterator(); while (libDirIt.hasNext()) { final File libDir = libDirIt.next(); if (folder.equals(libDir)) { libDirIt.remove(); break; } } origLibDirs.add(0, folder); final Field systemNativeLibraryDirectories = ShareReflectUtil.findField(dexPathList, "systemNativeLibraryDirectories"); List<File> origSystemLibDirs = (List<File>) systemNativeLibraryDirectories.get(dexPathList); if (origSystemLibDirs == null) { origSystemLibDirs = new ArrayList<>(2); } final List<File> newLibDirs = new ArrayList<>(origLibDirs.size() + origSystemLibDirs.size() + 1); newLibDirs.addAll(origLibDirs); newLibDirs.addAll(origSystemLibDirs); final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class); final Object[] elements = (Object[]) makeElements.invoke(dexPathList, newLibDirs); final Field nativeLibraryPathElements = ShareReflectUtil.findField(dexPathList, "nativeLibraryPathElements"); nativeLibraryPathElements.set(dexPathList, elements); } } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/TinkerLoadLibrary.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java", "retrieved_chunk": " String tmpDir =\"/data/data/com.example.nativecpp/\";\n Log.e(\"darren:\", \"file===:\"+ tmpDir);\n // 在合适的时候将自定义路径插入so检索路径\n DynamicSo.insertPathToNativeSystem(this,new File(tmpDir));\n }\n}", "score": 0.8014297485351562 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " }\n // 先把依赖项加载完,再加载本身\n System.loadLibrary(soFIle.getName().substring(3, soFIle.getName().length() - 3));\n }\n public static void insertPathToNativeSystem(Context context,File file){\n try {\n TinkerLoadLibrary.installNativeLibraryPath(context.getClassLoader(), file);\n } catch (Throwable e) {\n e.printStackTrace();\n }", "score": 0.7953884601593018 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " // 把本来lib前缀和.so后缀去掉即可\n String dependencySo = dependency.substring(3, dependency.length() - 3);\n //在application已经注入了路径DynamicSo.insertPathToNativeSystem(this,file) 所以采用系统的加载就行\n System.loadLibrary(dependencySo);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n } catch (IOException ignored) {", "score": 0.7885522246360779 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": "package com.example.lib_sillyboy;\nimport android.content.Context;\nimport com.example.lib_sillyboy.elf.ElfParser;\nimport com.example.lib_sillyboy.tinker.TinkerLoadLibrary;\nimport java.io.File;\nimport java.io.IOException;\nimport java.util.List;\npublic class DynamicSo {\n public static void loadStaticSo(File soFIle, String path) {\n try {", "score": 0.773560643196106 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java", "retrieved_chunk": " //如果nativecpp3->nativecpptwo->nativecpp 则先加载 DynamicSo.loadStaticSo(nativecpptwo),此时nativecpp作为nativecpptwo的直接依赖被加载了\n //不能直接加载nativecpp3,导致加载直接依赖nativetwo的时候nativecpp没加载导致错误。 这个可以优化,比如递归\n for (final String dependency : dependencies) {\n try {\n File file = new File(path + dependency);\n if (file.exists()) {\n //递归查找\n loadStaticSo(file, path);\n } else {\n // so文件不存在这个文件夹,代表是ndk中的so,如liblog.so,则直接加载", "score": 0.7701318264007568 } ]
java
makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", List.class, File.class, List.class);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf32Header extends Elf.Header { private final ElfParser parser; public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readWord(buffer, 0x1C); shoff = parser.readWord(buffer, 0x20); phentsize
= parser.readHalf(buffer, 0x2A);
phnum = parser.readHalf(buffer, 0x2C); shentsize = parser.readHalf(buffer, 0x2E); shnum = parser.readHalf(buffer, 0x30); shstrndx = parser.readHalf(buffer, 0x32); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section32Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program32Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic32Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9832334518432617 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.917479932308197 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9168698787689209 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.9165794849395752 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9134018421173096 } ]
java
= parser.readHalf(buffer, 0x2A);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf32Header extends Elf.Header { private final ElfParser parser; public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readWord(buffer, 0x1C); shoff = parser.readWord(buffer, 0x20); phentsize = parser.readHalf(buffer, 0x2A); phnum = parser.readHalf(buffer, 0x2C); shentsize
= parser.readHalf(buffer, 0x2E);
shnum = parser.readHalf(buffer, 0x30); shstrndx = parser.readHalf(buffer, 0x32); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section32Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program32Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic32Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9109535813331604 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf.java", "retrieved_chunk": " public static final int ELFCLASS64 = 2; // 64 Bit ELF\n public static final int ELFDATA2MSB = 2; // Big Endian, 2s complement\n public boolean bigEndian;\n public int type;\n public long phoff;\n public long shoff;\n public int phentsize;\n public int phnum;\n public int shentsize;\n public int shnum;", "score": 0.8829008936882019 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " phnum = parser.readHalf(buffer, 0x38);\n shentsize = parser.readHalf(buffer, 0x3A);\n shnum = parser.readHalf(buffer, 0x3C);\n shstrndx = parser.readHalf(buffer, 0x3E);\n }\n @Override\n public Elf.SectionHeader getSectionHeader(final int index) throws IOException {\n return new Section64Header(parser, this, index);\n }\n @Override", "score": 0.8765607476234436 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.8581050038337708 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.8578040599822998 } ]
java
= parser.readHalf(buffer, 0x2E);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf64Header extends Elf.Header { private final ElfParser parser; public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff =
parser.readLong(buffer, 0x20);
shoff = parser.readLong(buffer, 0x28); phentsize = parser.readHalf(buffer, 0x36); phnum = parser.readHalf(buffer, 0x38); shentsize = parser.readHalf(buffer, 0x3A); shnum = parser.readHalf(buffer, 0x3C); shstrndx = parser.readHalf(buffer, 0x3E); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section64Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program64Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic64Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9714606404304504 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.922340989112854 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9212898015975952 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.9081714153289795 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.8995897173881531 } ]
java
parser.readLong(buffer, 0x20);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program64Header extends Elf.ProgramHeader { public Program64Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset); offset = parser.readLong(buffer, baseOffset + 0x8); vaddr = parser.readLong(buffer, baseOffset + 0x10); memsz =
parser.readLong(buffer, baseOffset + 0x28);
} }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.980544924736023 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9296587109565735 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9208166599273682 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9155612587928772 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program64Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic64Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.9153581261634827 } ]
java
parser.readLong(buffer, baseOffset + 0x28);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Elf64Header extends Elf.Header { private final ElfParser parser; public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException { this.bigEndian = bigEndian; this.parser = parser; final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); type = parser.readHalf(buffer, 0x10); phoff = parser.readLong(buffer, 0x20); shoff = parser.readLong(buffer, 0x28); phentsize
= parser.readHalf(buffer, 0x36);
phnum = parser.readHalf(buffer, 0x38); shentsize = parser.readHalf(buffer, 0x3A); shnum = parser.readHalf(buffer, 0x3C); shstrndx = parser.readHalf(buffer, 0x3E); } @Override public Elf.SectionHeader getSectionHeader(final int index) throws IOException { return new Section64Header(parser, this, index); } @Override public Elf.ProgramHeader getProgramHeader(final long index) throws IOException { return new Program64Header(parser, this, index); } @Override public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index) throws IOException { return new Dynamic64Structure(parser, this, baseOffset, index); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9812479019165039 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9182237982749939 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9158303737640381 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.9051453471183777 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.8978440165519714 } ]
java
= parser.readHalf(buffer, 0x36);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program32Header extends Elf.ProgramHeader { public Program32Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset); offset = parser.readWord(buffer, baseOffset + 0x4); vaddr =
parser.readWord(buffer, baseOffset + 0x8);
memsz = parser.readWord(buffer, baseOffset + 0x14); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9649553298950195 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.9232059717178345 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program32Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic32Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.91524338722229 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9144258499145508 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9078754782676697 } ]
java
parser.readWord(buffer, baseOffset + 0x8);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program64Header extends Elf.ProgramHeader { public Program64Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset);
offset = parser.readLong(buffer, baseOffset + 0x8);
vaddr = parser.readLong(buffer, baseOffset + 0x10); memsz = parser.readLong(buffer, baseOffset + 0x28); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java", "retrieved_chunk": " public Program32Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readWord(buffer, baseOffset + 0x4);\n vaddr = parser.readWord(buffer, baseOffset + 0x8);\n memsz = parser.readWord(buffer, baseOffset + 0x14);\n }", "score": 0.9537926316261292 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9146791696548462 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program64Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic64Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.9108273386955261 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf64Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf64Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readLong(buffer, 0x20);\n shoff = parser.readLong(buffer, 0x28);\n phentsize = parser.readHalf(buffer, 0x36);", "score": 0.9108272790908813 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9028632044792175 } ]
java
offset = parser.readLong(buffer, baseOffset + 0x8);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program32Header extends Elf.ProgramHeader { public Program32Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset); offset = parser.readWord(buffer, baseOffset + 0x4); vaddr = parser.readWord(buffer, baseOffset + 0x8); memsz
= parser.readWord(buffer, baseOffset + 0x14);
} }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9793169498443604 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.92885822057724 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9228909611701965 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9188039898872375 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program32Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic32Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.9140551090240479 } ]
java
= parser.readWord(buffer, baseOffset + 0x14);
/** * Copyright 2015 - 2016 KeepSafe Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.lib_sillyboy.elf; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class Program32Header extends Elf.ProgramHeader { public Program32Header(final ElfParser parser, final Elf.Header header, final long index) throws IOException { final ByteBuffer buffer = ByteBuffer.allocate(4); buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN); final long baseOffset = header.phoff + (index * header.phentsize); type = parser.readWord(buffer, baseOffset);
offset = parser.readWord(buffer, baseOffset + 0x4);
vaddr = parser.readWord(buffer, baseOffset + 0x8); memsz = parser.readWord(buffer, baseOffset + 0x14); } }
lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program32Header.java
DarrenTianYe-android_dynamic_load_so-7a70027
[ { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Program64Header.java", "retrieved_chunk": " public Program64Header(final ElfParser parser, final Elf.Header header, final long index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n final long baseOffset = header.phoff + (index * header.phentsize);\n type = parser.readWord(buffer, baseOffset);\n offset = parser.readLong(buffer, baseOffset + 0x8);\n vaddr = parser.readLong(buffer, baseOffset + 0x10);\n memsz = parser.readLong(buffer, baseOffset + 0x28);\n }", "score": 0.9545437097549438 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section32Header.java", "retrieved_chunk": " public Section32Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x1C);\n }\n}", "score": 0.9173729419708252 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " private final ElfParser parser;\n public Elf32Header(final boolean bigEndian, final ElfParser parser) throws IOException {\n this.bigEndian = bigEndian;\n this.parser = parser;\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n type = parser.readHalf(buffer, 0x10);\n phoff = parser.readWord(buffer, 0x1C);\n shoff = parser.readWord(buffer, 0x20);\n phentsize = parser.readHalf(buffer, 0x2A);", "score": 0.9126269221305847 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Elf32Header.java", "retrieved_chunk": " public Elf.ProgramHeader getProgramHeader(final long index) throws IOException {\n return new Program32Header(parser, this, index);\n }\n @Override\n public Elf.DynamicStructure getDynamicStructure(final long baseOffset, final int index)\n throws IOException {\n return new Dynamic32Structure(parser, this, baseOffset, index);\n }\n}", "score": 0.9114043712615967 }, { "filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/Section64Header.java", "retrieved_chunk": " public Section64Header(final ElfParser parser, final Elf.Header header, final int index)\n throws IOException {\n final ByteBuffer buffer = ByteBuffer.allocate(8);\n buffer.order(header.bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);\n info = parser.readWord(buffer, header.shoff + (index * header.shentsize) + 0x2C);\n }\n}", "score": 0.9031469225883484 } ]
java
offset = parser.readWord(buffer, baseOffset + 0x4);
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal.config; import co.decodable.sdk.pipeline.StartupMode; import co.decodable.sdk.pipeline.util.Unmodifiable; import java.util.Map; import java.util.stream.Collectors; import org.apache.kafka.clients.consumer.ConsumerConfig; public class StreamConfig { /** Used by Flink to prefix all pass-through options for the Kafka producer/consumer. */ private static final String PROPERTIES_PREFIX = "properties."; private final String id; private final String name; private final String bootstrapServers; private final String topic; private final StartupMode startupMode; private final String transactionalIdPrefix; private final String deliveryGuarantee; @Unmodifiable private final Map<String, String> properties; public StreamConfig(String id, String name, Map<String, String> properties) { this.id = id; this.name = name; this.bootstrapServers = properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG); this.topic = properties.get("topic"); this.startupMode
= StartupMode.fromString(properties.get("scan.startup.mode"));
this.transactionalIdPrefix = properties.get("sink.transactional-id-prefix"); this.deliveryGuarantee = properties.get("sink.delivery-guarantee"); this.properties = properties.entrySet().stream() .filter(e -> e.getKey().startsWith("properties")) .collect( Collectors.toUnmodifiableMap(e -> e.getKey().substring(11), e -> e.getValue())); } public String id() { return id; } public String name() { return name; } public String bootstrapServers() { return bootstrapServers; } public String topic() { return topic; } public StartupMode startupMode() { return startupMode; } public String transactionalIdPrefix() { return transactionalIdPrefix; } public String deliveryGuarantee() { return deliveryGuarantee; } public Map<String, String> kafkaProperties() { return properties; } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;", "score": 0.8719317317008972 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.861961305141449 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " private final String topic;\n public StreamConfiguration(String name) {\n this.name = name;\n this.id = getRandomId();\n this.topic = \"stream-00000000-\" + id;\n }\n private static String getRandomId() {\n int digits = 8;\n return String.format(\"%0\" + digits + \"x\", new BigInteger(digits * 4, new SecureRandom()));\n }", "score": 0.8618478775024414 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8565462827682495 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " : DeliveryGuarantee.NONE)\n .setTransactionalIdPrefix(streamConfig.transactionalIdPrefix())\n .setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties()))\n .build();\n return new DecodableStreamSinkImpl<T>(delegate);\n }\n private static Properties toProperties(Map<String, String> map) {\n Properties p = new Properties();\n p.putAll(map);\n return p;", "score": 0.8494443297386169 } ]
java
= StartupMode.fromString(properties.get("scan.startup.mode"));
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableStreamSink; import co.decodable.sdk.pipeline.DecodableStreamSinkBuilder; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.internal.config.StreamConfig; import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.flink.api.common.serialization.SerializationSchema; import org.apache.flink.connector.base.DeliveryGuarantee; import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema; import org.apache.flink.connector.kafka.sink.KafkaSink; public class DecodableStreamSinkBuilderImpl<T> implements DecodableStreamSinkBuilder<T> { private String streamId; private String streamName; private SerializationSchema<T> serializationSchema; @Override public DecodableStreamSinkBuilder<T> withStreamName(String streamName) { this.streamName = streamName; return this; } @Override public DecodableStreamSinkBuilder<T> withStreamId(String streamId) { this.streamId = streamId; return this; } @Override public DecodableStreamSinkBuilder<T> withSerializationSchema( SerializationSchema<T> serializationSchema) { this.serializationSchema = serializationSchema; return this; } @Override public DecodableStreamSink<T> build() { Objects.requireNonNull(serializationSchema, "serializationSchema"); Map<String, String> environment = EnvironmentAccess.getEnvironment().getEnvironmentConfiguration(); StreamConfig streamConfig = new StreamConfigMapping(environment).determineConfig(streamName, streamId); KafkaSink<T> delegate = KafkaSink.<T>builder() .setBootstrapServers(streamConfig.bootstrapServers()) .setRecordSerializer( KafkaRecordSerializationSchema.builder() .setTopic(streamConfig.topic()) .setValueSerializationSchema(serializationSchema) .build()) .setDeliveryGuarantee( "exactly-once".equals(streamConfig.deliveryGuarantee()) ? DeliveryGuarantee.EXACTLY_ONCE : "at-least-once".equals(streamConfig.deliveryGuarantee()) ? DeliveryGuarantee.AT_LEAST_ONCE : DeliveryGuarantee.NONE) .setTransactionalIdPrefix
(streamConfig.transactionalIdPrefix()) .setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties())) .build();
return new DecodableStreamSinkImpl<T>(delegate); } private static Properties toProperties(Map<String, String> map) { Properties p = new Properties(); p.putAll(map); return p; } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8959875702857971 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java", "retrieved_chunk": " private final StartupMode startupMode;\n private final String transactionalIdPrefix;\n private final String deliveryGuarantee;\n @Unmodifiable private final Map<String, String> properties;\n public StreamConfig(String id, String name, Map<String, String> properties) {\n this.id = id;\n this.name = name;\n this.bootstrapServers =\n properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG);\n this.topic = properties.get(\"topic\");", "score": 0.8764960169792175 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8743661642074585 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " if (streamConfig.startupMode() != null) {\n builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode()));\n } else if (startupMode != null) {\n builder.setStartingOffsets(toOffsetsInitializer(startupMode));\n }\n KafkaSource<T> delegate = builder.build();\n return new DecodableStreamSourceImpl<T>(delegate);\n }\n private static Properties toProperties(Map<String, String> map) {\n Properties p = new Properties();", "score": 0.8464375138282776 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java", "retrieved_chunk": " var consumerProps = new Properties();\n consumerProps.put(\"bootstrap.servers\", bootstrapServers);\n consumerProps.put(\n \"key.deserializer\", \"org.apache.kafka.common.serialization.StringDeserializer\");\n consumerProps.put(\n \"value.deserializer\", \"org.apache.kafka.common.serialization.StringDeserializer\");\n consumerProps.put(\"auto.offset.reset\", \"earliest\");\n consumerProps.put(\"group.id\", \"my-group\");\n return consumerProps;\n }", "score": 0.8446065187454224 } ]
java
(streamConfig.transactionalIdPrefix()) .setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties())) .build();
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.testing; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.util.Incubating; import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; /** * Provides access to Decodable streams during testing as well as the ability to run custom Flink * jobs. */ @Incubating public class PipelineTestContext implements AutoCloseable { private static final System.Logger LOGGER = System.getLogger(PipelineTestContext.class.getName()); private final TestEnvironment testEnvironment; private final KafkaProducer<String, String> producer; private final Map<String, DecodableStreamImpl> streams; private final ExecutorService executorService; /** Creates a new testing context, using the given {@link TestEnvironment}. */ public PipelineTestContext(TestEnvironment testEnvironment) { EnvironmentAccess.setEnvironment(testEnvironment); this.testEnvironment = testEnvironment; this.producer = new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers())); this.streams = new HashMap<>(); this.executorService = Executors.newCachedThreadPool(); } private static Properties producerProperties(String bootstrapServers) { var props = new Properties(); props.put("bootstrap.servers", bootstrapServers); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); return props; } private static Properties consumerProperties(String bootstrapServers) { var consumerProps = new Properties(); consumerProps.put("bootstrap.servers", bootstrapServers); consumerProps.put( "key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put( "value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put("auto.offset.reset", "earliest"); consumerProps.put("group.id", "my-group"); return consumerProps; } /** Returns a stream for the given name. */ public DecodableStream<String> stream(String name) { KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers())); consumer
.subscribe(Collections.singleton(testEnvironment.topicFor(name)));
return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer)); } /** Asynchronously executes the given Flink job main method. */ public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args) throws Exception { executorService.submit( () -> { try { jobMainMethod.accept(args); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Job aborted"); } catch (Exception e) { LOGGER.log(Level.ERROR, "Job failed", e); } }); } @Override public void close() throws Exception { try { producer.close(); executorService.shutdownNow(); executorService.awaitTermination(100, TimeUnit.MILLISECONDS); for (DecodableStreamImpl stream : streams.values()) { stream.consumer.close(); } } catch (Exception e) { throw new RuntimeException("Couldn't close testing context", e); } finally { EnvironmentAccess.resetEnvironment(); } } /** * A {@link Consumer} variant which allows for declared checked exception types. * * @param <T> The consumed data type. */ @FunctionalInterface public interface ThrowingConsumer<T> { void accept(T t) throws Exception; } private class DecodableStreamImpl implements DecodableStream<String> { private final String streamName; private final KafkaConsumer<String, String> consumer; private final List<ConsumerRecord<String, String>> consumed; public DecodableStreamImpl(String streamName, KafkaConsumer<String, String> consumer) { this.streamName = streamName; this.consumer = consumer; this.consumed = new ArrayList<>(); } @Override public void add(StreamRecord<String> streamRecord) { Future<RecordMetadata> sent = producer.send( new ProducerRecord<>(testEnvironment.topicFor(streamName), streamRecord.value())); // wait for record to be ack-ed try { sent.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Couldn't send record", e); } } @Override public Future<StreamRecord<String>> takeOne() { return ((CompletableFuture<List<StreamRecord<String>>>) take(1)).thenApply(l -> l.get(0)); } @Override public Future<List<StreamRecord<String>>> take(int n) { return CompletableFuture.supplyAsync( () -> { while (consumed.size() < n) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(20)); for (ConsumerRecord<String, String> record : records) { consumed.add(record); } } List<StreamRecord<String>> result = consumed.subList(0, n).stream() .map(cr -> new StreamRecord<>(cr.value())) .collect(Collectors.toList()); consumed.subList(0, n).clear(); return result; }, executorService); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8597341179847717 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8581732511520386 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java", "retrieved_chunk": "import java.util.Map;\nimport java.util.stream.Collectors;\nimport org.apache.kafka.clients.consumer.ConsumerConfig;\npublic class StreamConfig {\n /** Used by Flink to prefix all pass-through options for the Kafka producer/consumer. */\n private static final String PROPERTIES_PREFIX = \"properties.\";\n private final String id;\n private final String name;\n private final String bootstrapServers;\n private final String topic;", "score": 0.8480117917060852 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;", "score": 0.8405638933181763 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java", "retrieved_chunk": " private final StartupMode startupMode;\n private final String transactionalIdPrefix;\n private final String deliveryGuarantee;\n @Unmodifiable private final Map<String, String> properties;\n public StreamConfig(String id, String name, Map<String, String> properties) {\n this.id = id;\n this.name = name;\n this.bootstrapServers =\n properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG);\n this.topic = properties.get(\"topic\");", "score": 0.8389418125152588 } ]
java
.subscribe(Collections.singleton(testEnvironment.topicFor(name)));
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableStreamSource; import co.decodable.sdk.pipeline.DecodableStreamSourceBuilder; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.StartupMode; import co.decodable.sdk.pipeline.internal.config.StreamConfig; import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.KafkaSourceBuilder; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; public class DecodableStreamSourceBuilderImpl<T> implements DecodableStreamSourceBuilder<T> { private String streamId; private String streamName; private StartupMode startupMode; private DeserializationSchema<T> deserializationSchema; @Override public DecodableStreamSourceBuilder<T> withStreamName(String streamName) { this.streamName = streamName; return this; } @Override public DecodableStreamSourceBuilder<T> withStreamId(String streamId) { this.streamId = streamId; return this; } @Override public DecodableStreamSourceBuilder<T> withStartupMode(StartupMode startupMode) { this.startupMode = startupMode; return this; } @Override public DecodableStreamSourceBuilder<T> withDeserializationSchema( DeserializationSchema<T> deserializationSchema) { this.deserializationSchema = deserializationSchema; return this; } @Override public DecodableStreamSource<T> build() { Objects.requireNonNull(deserializationSchema, "deserializationSchema"); Map<String, String> environment = EnvironmentAccess.getEnvironment().getEnvironmentConfiguration(); StreamConfig streamConfig = new StreamConfigMapping(environment).determineConfig(streamName, streamId); KafkaSourceBuilder<T> builder = KafkaSource.<T>builder() .setBootstrapServers(streamConfig.bootstrapServers()) .
setTopics(streamConfig.topic()) .setProperties(toProperties(streamConfig.kafkaProperties())) .setValueOnlyDeserializer(deserializationSchema);
if (streamConfig.startupMode() != null) { builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode())); } else if (startupMode != null) { builder.setStartingOffsets(toOffsetsInitializer(startupMode)); } KafkaSource<T> delegate = builder.build(); return new DecodableStreamSourceImpl<T>(delegate); } private static Properties toProperties(Map<String, String> map) { Properties p = new Properties(); p.putAll(map); return p; } private OffsetsInitializer toOffsetsInitializer(StartupMode startupMode) { switch (startupMode) { case EARLIEST_OFFSET: return OffsetsInitializer.earliest(); case LATEST_OFFSET: return OffsetsInitializer.latest(); default: throw new IllegalArgumentException("Unexpected startup mode: " + startupMode); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " @Override\n public DecodableStreamSink<T> build() {\n Objects.requireNonNull(serializationSchema, \"serializationSchema\");\n Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSink<T> delegate =\n KafkaSink.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())", "score": 0.901496946811676 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": "import co.decodable.sdk.pipeline.EnvironmentAccess;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfig;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfigMapping;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Properties;\nimport org.apache.flink.api.common.serialization.SerializationSchema;\nimport org.apache.flink.connector.base.DeliveryGuarantee;\nimport org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;\nimport org.apache.flink.connector.kafka.sink.KafkaSink;", "score": 0.8804693818092346 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;", "score": 0.8716205954551697 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " .setRecordSerializer(\n KafkaRecordSerializationSchema.builder()\n .setTopic(streamConfig.topic())\n .setValueSerializationSchema(serializationSchema)\n .build())\n .setDeliveryGuarantee(\n \"exactly-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.EXACTLY_ONCE\n : \"at-least-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.AT_LEAST_ONCE", "score": 0.8681045770645142 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8660378456115723 } ]
java
setTopics(streamConfig.topic()) .setProperties(toProperties(streamConfig.kafkaProperties())) .setValueOnlyDeserializer(deserializationSchema);
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableSourceSplit; import java.io.IOException; import org.apache.flink.connector.kafka.source.split.KafkaPartitionSplit; import org.apache.flink.core.io.SimpleVersionedSerializer; public class DelegatingSplitSerializer implements SimpleVersionedSerializer<DecodableSourceSplit> { private final SimpleVersionedSerializer<KafkaPartitionSplit> delegate; public DelegatingSplitSerializer(SimpleVersionedSerializer<KafkaPartitionSplit> delegate) { this.delegate = delegate; } @Override public int getVersion() { return delegate.getVersion(); } @Override public byte[] serialize(DecodableSourceSplit obj) throws IOException { return delegate.serialize(
((DecodableSourceSplitImpl) obj).getDelegate());
} @Override public DecodableSourceSplit deserialize(int version, byte[] serialized) throws IOException { return new DecodableSourceSplitImpl(delegate.deserialize(version, serialized)); } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingSplitSerializer.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingEnumeratorStateSerializer.java", "retrieved_chunk": " public int getVersion() {\n return delegate.getVersion();\n }\n @Override\n public byte[] serialize(DecodableSourceEnumeratorState obj) throws IOException {\n return delegate.serialize(((DecodableSourceEnumeratorStateImpl) obj).getDelegate());\n }\n @Override\n public DecodableSourceEnumeratorState deserialize(int version, byte[] serialized)\n throws IOException {", "score": 0.9300392270088196 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceImpl.java", "retrieved_chunk": " @Override\n public SimpleVersionedSerializer<DecodableSourceSplit> getSplitSerializer() {\n return new DelegatingSplitSerializer(delegate.getSplitSerializer());\n }\n @Override\n public SimpleVersionedSerializer<DecodableSourceEnumeratorState>\n getEnumeratorCheckpointSerializer() {\n return new DelegatingEnumeratorStateSerializer(delegate.getEnumeratorCheckpointSerializer());\n }\n @Override", "score": 0.877204179763794 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableSourceSplitImpl.java", "retrieved_chunk": "public class DecodableSourceSplitImpl implements DecodableSourceSplit {\n private final KafkaPartitionSplit delegate;\n public DecodableSourceSplitImpl(KafkaPartitionSplit delegate) {\n this.delegate = delegate;\n }\n @Override\n public String splitId() {\n return delegate.splitId();\n }\n public KafkaPartitionSplit getDelegate() {", "score": 0.8634548187255859 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceImpl.java", "retrieved_chunk": " private static final long serialVersionUID = 7762732921098678433L;\n private final KafkaSource<T> delegate;\n DecodableStreamSourceImpl(KafkaSource<T> delegate) {\n this.delegate = delegate;\n }\n @Override\n public Boundedness getBoundedness() {\n return delegate.getBoundedness();\n }\n @Override", "score": 0.8282331824302673 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkImpl.java", "retrieved_chunk": " return ((TwoPhaseCommittingSink) delegate).createCommitter();\n }\n @Override\n public SimpleVersionedSerializer<Object> getCommittableSerializer() {\n return ((TwoPhaseCommittingSink) delegate).getCommittableSerializer();\n }\n}", "score": 0.8262836337089539 } ]
java
((DecodableSourceSplitImpl) obj).getDelegate());
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.testing; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.util.Incubating; import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; /** * Provides access to Decodable streams during testing as well as the ability to run custom Flink * jobs. */ @Incubating public class PipelineTestContext implements AutoCloseable { private static final System.Logger LOGGER = System.getLogger(PipelineTestContext.class.getName()); private final TestEnvironment testEnvironment; private final KafkaProducer<String, String> producer; private final Map<String, DecodableStreamImpl> streams; private final ExecutorService executorService; /** Creates a new testing context, using the given {@link TestEnvironment}. */ public PipelineTestContext(TestEnvironment testEnvironment) { EnvironmentAccess.setEnvironment(testEnvironment); this.testEnvironment = testEnvironment; this.producer = new KafkaProducer<String, String>(
producerProperties(testEnvironment.bootstrapServers()));
this.streams = new HashMap<>(); this.executorService = Executors.newCachedThreadPool(); } private static Properties producerProperties(String bootstrapServers) { var props = new Properties(); props.put("bootstrap.servers", bootstrapServers); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); return props; } private static Properties consumerProperties(String bootstrapServers) { var consumerProps = new Properties(); consumerProps.put("bootstrap.servers", bootstrapServers); consumerProps.put( "key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put( "value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put("auto.offset.reset", "earliest"); consumerProps.put("group.id", "my-group"); return consumerProps; } /** Returns a stream for the given name. */ public DecodableStream<String> stream(String name) { KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers())); consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name))); return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer)); } /** Asynchronously executes the given Flink job main method. */ public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args) throws Exception { executorService.submit( () -> { try { jobMainMethod.accept(args); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Job aborted"); } catch (Exception e) { LOGGER.log(Level.ERROR, "Job failed", e); } }); } @Override public void close() throws Exception { try { producer.close(); executorService.shutdownNow(); executorService.awaitTermination(100, TimeUnit.MILLISECONDS); for (DecodableStreamImpl stream : streams.values()) { stream.consumer.close(); } } catch (Exception e) { throw new RuntimeException("Couldn't close testing context", e); } finally { EnvironmentAccess.resetEnvironment(); } } /** * A {@link Consumer} variant which allows for declared checked exception types. * * @param <T> The consumed data type. */ @FunctionalInterface public interface ThrowingConsumer<T> { void accept(T t) throws Exception; } private class DecodableStreamImpl implements DecodableStream<String> { private final String streamName; private final KafkaConsumer<String, String> consumer; private final List<ConsumerRecord<String, String>> consumed; public DecodableStreamImpl(String streamName, KafkaConsumer<String, String> consumer) { this.streamName = streamName; this.consumer = consumer; this.consumed = new ArrayList<>(); } @Override public void add(StreamRecord<String> streamRecord) { Future<RecordMetadata> sent = producer.send( new ProducerRecord<>(testEnvironment.topicFor(streamName), streamRecord.value())); // wait for record to be ack-ed try { sent.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Couldn't send record", e); } } @Override public Future<StreamRecord<String>> takeOne() { return ((CompletableFuture<List<StreamRecord<String>>>) take(1)).thenApply(l -> l.get(0)); } @Override public Future<List<StreamRecord<String>>> take(int n) { return CompletableFuture.supplyAsync( () -> { while (consumed.size() < n) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(20)); for (ConsumerRecord<String, String> record : records) { consumed.add(record); } } List<StreamRecord<String>> result = consumed.subList(0, n).stream() .map(cr -> new StreamRecord<>(cr.value())) .collect(Collectors.toList()); consumed.subList(0, n).clear(); return result; }, executorService); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " + \"}\";\n @Unmodifiable private final Map<String, StreamConfiguration> streams;\n private final String bootstrapServers;\n private TestEnvironment(String bootstrapServers, Map<String, StreamConfiguration> streams) {\n this.bootstrapServers = bootstrapServers;\n this.streams = Collections.unmodifiableMap(streams);\n }\n /** Returns a builder for creating a new {@link TestEnvironment}. */\n public static Builder builder() {\n return new Builder();", "score": 0.8666507601737976 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " return new TestEnvironment(bootstrapServers, streams);\n }\n }\n private static final String STREAM_CONFIG_TEMPLATE =\n \"{\\n\"\n + \" \\\"properties\\\": {\\n\"\n + \" \\\"value.format\\\": \\\"debezium-json\\\",\\n\"\n + \" \\\"key.format\\\": \\\"json\\\",\\n\"\n + \" \\\"topic\\\": \\\"%s\\\",\\n\"\n + \" \\\"scan.startup.mode\\\": \\\"earliest-offset\\\",\\n\"", "score": 0.8628304600715637 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/DataStreamJobTest.java", "retrieved_chunk": " TestEnvironment.builder()\n .withBootstrapServers(broker.getBootstrapServers())\n .withStreams(PURCHASE_ORDERS, PURCHASE_ORDERS_PROCESSED)\n .build();\n try (PipelineTestContext ctx = new PipelineTestContext(testEnvironment)) {\n String value =\n \"{\\n\"\n + \" \\\"order_id\\\" : 19001,\\n\"\n + \" \\\"order_date\\\" : \\\"2023-06-09 10:18:38\\\",\\n\"\n + \" \\\"customer_name\\\" : \\\"Yolanda Hagenes\\\",\\n\"", "score": 0.8603407144546509 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " * Decodable streams which then can be accessed from the job under test.\n */\n@Incubating\npublic class TestEnvironment implements Environment {\n /** A builder for creating new {@link TestEnvironment} instances. */\n public static class Builder {\n private String bootstrapServers;\n private final Map<String, StreamConfiguration> streams = new HashMap<>();\n /** Specifies the bootstrap server(s) to be used. */\n public Builder withBootstrapServers(String bootstrapServers) {", "score": 0.84749436378479 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8429800271987915 } ]
java
producerProperties(testEnvironment.bootstrapServers()));
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableStreamSink; import co.decodable.sdk.pipeline.DecodableStreamSinkBuilder; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.internal.config.StreamConfig; import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.flink.api.common.serialization.SerializationSchema; import org.apache.flink.connector.base.DeliveryGuarantee; import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema; import org.apache.flink.connector.kafka.sink.KafkaSink; public class DecodableStreamSinkBuilderImpl<T> implements DecodableStreamSinkBuilder<T> { private String streamId; private String streamName; private SerializationSchema<T> serializationSchema; @Override public DecodableStreamSinkBuilder<T> withStreamName(String streamName) { this.streamName = streamName; return this; } @Override public DecodableStreamSinkBuilder<T> withStreamId(String streamId) { this.streamId = streamId; return this; } @Override public DecodableStreamSinkBuilder<T> withSerializationSchema( SerializationSchema<T> serializationSchema) { this.serializationSchema = serializationSchema; return this; } @Override public DecodableStreamSink<T> build() { Objects.requireNonNull(serializationSchema, "serializationSchema"); Map<String, String> environment = EnvironmentAccess.getEnvironment().getEnvironmentConfiguration(); StreamConfig streamConfig = new StreamConfigMapping(environment).determineConfig(streamName, streamId); KafkaSink<T> delegate = KafkaSink.<T>builder() .setBootstrapServers(streamConfig.bootstrapServers()) .setRecordSerializer( KafkaRecordSerializationSchema.builder() .setTopic(streamConfig.topic()) .setValueSerializationSchema(serializationSchema) .build()) .setDeliveryGuarantee( "exactly-once".equals(streamConfig.deliveryGuarantee()) ? DeliveryGuarantee.EXACTLY_ONCE : "at-least-once".equals(streamConfig.deliveryGuarantee()) ? DeliveryGuarantee.AT_LEAST_ONCE : DeliveryGuarantee.NONE) .setTransactionalIdPrefix(streamConfig.transactionalIdPrefix())
.setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties())) .build();
return new DecodableStreamSinkImpl<T>(delegate); } private static Properties toProperties(Map<String, String> map) { Properties p = new Properties(); p.putAll(map); return p; } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8908522129058838 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8675204515457153 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java", "retrieved_chunk": " private final StartupMode startupMode;\n private final String transactionalIdPrefix;\n private final String deliveryGuarantee;\n @Unmodifiable private final Map<String, String> properties;\n public StreamConfig(String id, String name, Map<String, String> properties) {\n this.id = id;\n this.name = name;\n this.bootstrapServers =\n properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG);\n this.topic = properties.get(\"topic\");", "score": 0.8635616898536682 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " if (streamConfig.startupMode() != null) {\n builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode()));\n } else if (startupMode != null) {\n builder.setStartingOffsets(toOffsetsInitializer(startupMode));\n }\n KafkaSource<T> delegate = builder.build();\n return new DecodableStreamSourceImpl<T>(delegate);\n }\n private static Properties toProperties(Map<String, String> map) {\n Properties p = new Properties();", "score": 0.8424988389015198 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " + \" \\\"properties.compression.type\\\": \\\"zstd\\\",\\n\"\n + \" \\\"properties.enable.idempotence\\\": \\\"true\\\"\\n\"\n + \" },\\n\"\n + \" \\\"name\\\": \\\"shipments\\\"\\n\"\n + \"}\";\n StreamConfigMapping streamConfigMapping =\n new StreamConfigMapping(Map.of(\"DECODABLE_STREAM_CONFIG_078fc8b5\", config));\n StreamConfig streamConfig = streamConfigMapping.determineConfig(null, \"078fc8b5\");\n assertEquals(\"078fc8b5\", streamConfig.id());\n assertEquals(\"shipments\", streamConfig.name());", "score": 0.8422842025756836 } ]
java
.setKafkaProducerConfig(toProperties(streamConfig.kafkaProperties())) .build();
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.testing; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.util.Incubating; import java.lang.System.Logger.Level; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; /** * Provides access to Decodable streams during testing as well as the ability to run custom Flink * jobs. */ @Incubating public class PipelineTestContext implements AutoCloseable { private static final System.Logger LOGGER = System.getLogger(PipelineTestContext.class.getName()); private final TestEnvironment testEnvironment; private final KafkaProducer<String, String> producer; private final Map<String, DecodableStreamImpl> streams; private final ExecutorService executorService; /** Creates a new testing context, using the given {@link TestEnvironment}. */ public PipelineTestContext(TestEnvironment testEnvironment) { EnvironmentAccess.setEnvironment(testEnvironment); this.testEnvironment = testEnvironment; this.producer = new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers())); this.streams = new HashMap<>(); this.executorService = Executors.newCachedThreadPool(); } private static Properties producerProperties(String bootstrapServers) { var props = new Properties(); props.put("bootstrap.servers", bootstrapServers); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); return props; } private static Properties consumerProperties(String bootstrapServers) { var consumerProps = new Properties(); consumerProps.put("bootstrap.servers", bootstrapServers); consumerProps.put( "key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put( "value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); consumerProps.put("auto.offset.reset", "earliest"); consumerProps.put("group.id", "my-group"); return consumerProps; } /** Returns a stream for the given name. */ public DecodableStream<String> stream(String name) { KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers())); consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name))); return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer)); } /** Asynchronously executes the given Flink job main method. */ public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args) throws Exception { executorService.submit( () -> { try { jobMainMethod.accept(args); } catch (InterruptedException e) { LOGGER.log(Level.INFO, "Job aborted"); } catch (Exception e) { LOGGER.log(Level.ERROR, "Job failed", e); } }); } @Override public void close() throws Exception { try { producer.close(); executorService.shutdownNow(); executorService.awaitTermination(100, TimeUnit.MILLISECONDS); for (DecodableStreamImpl stream : streams.values()) { stream.consumer.close(); } } catch (Exception e) { throw new RuntimeException("Couldn't close testing context", e); } finally { EnvironmentAccess.resetEnvironment(); } } /** * A {@link Consumer} variant which allows for declared checked exception types. * * @param <T> The consumed data type. */ @FunctionalInterface public interface ThrowingConsumer<T> { void accept(T t) throws Exception; } private class DecodableStreamImpl implements DecodableStream<String> { private final String streamName; private final KafkaConsumer<String, String> consumer; private final List<ConsumerRecord<String, String>> consumed; public DecodableStreamImpl(String streamName, KafkaConsumer<String, String> consumer) { this.streamName = streamName; this.consumer = consumer; this.consumed = new ArrayList<>(); } @Override public void add(StreamRecord<String> streamRecord) { Future<RecordMetadata> sent = producer.send( new ProducerRecord<>
(testEnvironment.topicFor(streamName), streamRecord.value()));
// wait for record to be ack-ed try { sent.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException("Couldn't send record", e); } } @Override public Future<StreamRecord<String>> takeOne() { return ((CompletableFuture<List<StreamRecord<String>>>) take(1)).thenApply(l -> l.get(0)); } @Override public Future<List<StreamRecord<String>>> take(int n) { return CompletableFuture.supplyAsync( () -> { while (consumed.size() < n) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(20)); for (ConsumerRecord<String, String> record : records) { consumed.add(record); } } List<StreamRecord<String>> result = consumed.subList(0, n).stream() .map(cr -> new StreamRecord<>(cr.value())) .collect(Collectors.toList()); consumed.subList(0, n).clear(); return result; }, executorService); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " .setRecordSerializer(\n KafkaRecordSerializationSchema.builder()\n .setTopic(streamConfig.topic())\n .setValueSerializationSchema(serializationSchema)\n .build())\n .setDeliveryGuarantee(\n \"exactly-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.EXACTLY_ONCE\n : \"at-least-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.AT_LEAST_ONCE", "score": 0.83306884765625 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8219518065452576 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/DecodableStream.java", "retrieved_chunk": "import java.util.concurrent.Future;\n/**\n * Represents a data stream on the Decodable platform.\n *\n * @param <T> The element type of this stream\n */\n@Incubating\npublic interface DecodableStream<T> {\n /** Adds the given stream record to this stream. */\n void add(StreamRecord<T> streamRecord);", "score": 0.817747175693512 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/DataStreamJobTest.java", "retrieved_chunk": " + \" \\\"price\\\" : 15.00,\\n\"\n + \" \\\"product_id\\\" : 108,\\n\"\n + \" \\\"order_status\\\" : false\\n\"\n + \"}\";\n // given\n ctx.stream(PURCHASE_ORDERS).add(new StreamRecord<>(value));\n // when (as an example, PurchaseOrderProcessingJob upper-cases the customer name)\n ctx.runJobAsync(PurchaseOrderProcessingJob::main);\n StreamRecord<String> result =\n ctx.stream(PURCHASE_ORDERS_PROCESSED).takeOne().get(30, TimeUnit.SECONDS);", "score": 0.8140445351600647 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java", "retrieved_chunk": " Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSourceBuilder<T> builder =\n KafkaSource.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())\n .setTopics(streamConfig.topic())\n .setProperties(toProperties(streamConfig.kafkaProperties()))\n .setValueOnlyDeserializer(deserializationSchema);", "score": 0.8114754557609558 } ]
java
(testEnvironment.topicFor(streamName), streamRecord.value()));
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableStreamSource; import co.decodable.sdk.pipeline.DecodableStreamSourceBuilder; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.StartupMode; import co.decodable.sdk.pipeline.internal.config.StreamConfig; import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.KafkaSourceBuilder; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; public class DecodableStreamSourceBuilderImpl<T> implements DecodableStreamSourceBuilder<T> { private String streamId; private String streamName; private StartupMode startupMode; private DeserializationSchema<T> deserializationSchema; @Override public DecodableStreamSourceBuilder<T> withStreamName(String streamName) { this.streamName = streamName; return this; } @Override public DecodableStreamSourceBuilder<T> withStreamId(String streamId) { this.streamId = streamId; return this; } @Override public DecodableStreamSourceBuilder<T> withStartupMode(StartupMode startupMode) { this.startupMode = startupMode; return this; } @Override public DecodableStreamSourceBuilder<T> withDeserializationSchema( DeserializationSchema<T> deserializationSchema) { this.deserializationSchema = deserializationSchema; return this; } @Override public DecodableStreamSource<T> build() { Objects.requireNonNull(deserializationSchema, "deserializationSchema"); Map<String, String> environment = EnvironmentAccess.getEnvironment().getEnvironmentConfiguration(); StreamConfig streamConfig = new StreamConfigMapping(environment).determineConfig(streamName, streamId); KafkaSourceBuilder<T> builder = KafkaSource.<T>builder() .setBootstrapServers(streamConfig.bootstrapServers()) .setTopics(streamConfig.topic()) .setProperties(
toProperties(streamConfig.kafkaProperties())) .setValueOnlyDeserializer(deserializationSchema);
if (streamConfig.startupMode() != null) { builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode())); } else if (startupMode != null) { builder.setStartingOffsets(toOffsetsInitializer(startupMode)); } KafkaSource<T> delegate = builder.build(); return new DecodableStreamSourceImpl<T>(delegate); } private static Properties toProperties(Map<String, String> map) { Properties p = new Properties(); p.putAll(map); return p; } private OffsetsInitializer toOffsetsInitializer(StartupMode startupMode) { switch (startupMode) { case EARLIEST_OFFSET: return OffsetsInitializer.earliest(); case LATEST_OFFSET: return OffsetsInitializer.latest(); default: throw new IllegalArgumentException("Unexpected startup mode: " + startupMode); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " @Override\n public DecodableStreamSink<T> build() {\n Objects.requireNonNull(serializationSchema, \"serializationSchema\");\n Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSink<T> delegate =\n KafkaSink.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())", "score": 0.9004954099655151 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": "import co.decodable.sdk.pipeline.EnvironmentAccess;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfig;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfigMapping;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Properties;\nimport org.apache.flink.api.common.serialization.SerializationSchema;\nimport org.apache.flink.connector.base.DeliveryGuarantee;\nimport org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;\nimport org.apache.flink.connector.kafka.sink.KafkaSink;", "score": 0.879792332649231 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;", "score": 0.873421847820282 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8650861382484436 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " .setRecordSerializer(\n KafkaRecordSerializationSchema.builder()\n .setTopic(streamConfig.topic())\n .setValueSerializationSchema(serializationSchema)\n .build())\n .setDeliveryGuarantee(\n \"exactly-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.EXACTLY_ONCE\n : \"at-least-once\".equals(streamConfig.deliveryGuarantee())\n ? DeliveryGuarantee.AT_LEAST_ONCE", "score": 0.8647174835205078 } ]
java
toProperties(streamConfig.kafkaProperties())) .setValueOnlyDeserializer(deserializationSchema);
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright Decodable, Inc. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package co.decodable.sdk.pipeline.internal; import co.decodable.sdk.pipeline.DecodableStreamSource; import co.decodable.sdk.pipeline.DecodableStreamSourceBuilder; import co.decodable.sdk.pipeline.EnvironmentAccess; import co.decodable.sdk.pipeline.StartupMode; import co.decodable.sdk.pipeline.internal.config.StreamConfig; import co.decodable.sdk.pipeline.internal.config.StreamConfigMapping; import java.util.Map; import java.util.Objects; import java.util.Properties; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.KafkaSourceBuilder; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; public class DecodableStreamSourceBuilderImpl<T> implements DecodableStreamSourceBuilder<T> { private String streamId; private String streamName; private StartupMode startupMode; private DeserializationSchema<T> deserializationSchema; @Override public DecodableStreamSourceBuilder<T> withStreamName(String streamName) { this.streamName = streamName; return this; } @Override public DecodableStreamSourceBuilder<T> withStreamId(String streamId) { this.streamId = streamId; return this; } @Override public DecodableStreamSourceBuilder<T> withStartupMode(StartupMode startupMode) { this.startupMode = startupMode; return this; } @Override public DecodableStreamSourceBuilder<T> withDeserializationSchema( DeserializationSchema<T> deserializationSchema) { this.deserializationSchema = deserializationSchema; return this; } @Override public DecodableStreamSource<T> build() { Objects.requireNonNull(deserializationSchema, "deserializationSchema"); Map<String, String> environment = EnvironmentAccess.getEnvironment().getEnvironmentConfiguration(); StreamConfig streamConfig = new StreamConfigMapping(environment).determineConfig(streamName, streamId); KafkaSourceBuilder<T> builder = KafkaSource.<T>builder() .setBootstrapServers(streamConfig.bootstrapServers()) .setTopics(streamConfig.topic()) .setProperties(toProperties(streamConfig.kafkaProperties())) .setValueOnlyDeserializer(deserializationSchema);
if (streamConfig.startupMode() != null) {
builder.setStartingOffsets(toOffsetsInitializer(streamConfig.startupMode())); } else if (startupMode != null) { builder.setStartingOffsets(toOffsetsInitializer(startupMode)); } KafkaSource<T> delegate = builder.build(); return new DecodableStreamSourceImpl<T>(delegate); } private static Properties toProperties(Map<String, String> map) { Properties p = new Properties(); p.putAll(map); return p; } private OffsetsInitializer toOffsetsInitializer(StartupMode startupMode) { switch (startupMode) { case EARLIEST_OFFSET: return OffsetsInitializer.earliest(); case LATEST_OFFSET: return OffsetsInitializer.latest(); default: throw new IllegalArgumentException("Unexpected startup mode: " + startupMode); } } }
sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java
decodableco-decodable-pipeline-sdk-af78b8a
[ { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": " @Override\n public DecodableStreamSink<T> build() {\n Objects.requireNonNull(serializationSchema, \"serializationSchema\");\n Map<String, String> environment =\n EnvironmentAccess.getEnvironment().getEnvironmentConfiguration();\n StreamConfig streamConfig =\n new StreamConfigMapping(environment).determineConfig(streamName, streamId);\n KafkaSink<T> delegate =\n KafkaSink.<T>builder()\n .setBootstrapServers(streamConfig.bootstrapServers())", "score": 0.8928903341293335 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java", "retrieved_chunk": "import co.decodable.sdk.pipeline.EnvironmentAccess;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfig;\nimport co.decodable.sdk.pipeline.internal.config.StreamConfigMapping;\nimport java.util.Map;\nimport java.util.Objects;\nimport java.util.Properties;\nimport org.apache.flink.api.common.serialization.SerializationSchema;\nimport org.apache.flink.connector.base.DeliveryGuarantee;\nimport org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;\nimport org.apache.flink.connector.kafka.sink.KafkaSink;", "score": 0.8764524459838867 }, { "filename": "sdk/src/test/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMappingTest.java", "retrieved_chunk": " assertEquals(\"my-kafka:9092\", streamConfig.bootstrapServers());\n assertEquals(\"stream-00000000-078fc8b5\", streamConfig.topic());\n assertEquals(StartupMode.LATEST_OFFSET, streamConfig.startupMode());\n assertEquals(\n \"tx-account-00000000-PIPELINE-af78c091-1686579235527\",\n streamConfig.transactionalIdPrefix());\n assertEquals(\"exactly-once\", streamConfig.deliveryGuarantee());\n assertThat(streamConfig.kafkaProperties())\n .contains(\n entry(\"bootstrap.servers\", \"my-kafka:9092\"),", "score": 0.8759145736694336 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/TestEnvironment.java", "retrieved_chunk": " }\n return config.topic();\n }\n /** Returns the Kafka bootstrap server(s) configured for this environment. */\n public String bootstrapServers() {\n return bootstrapServers;\n }\n private static class StreamConfiguration {\n private final String name;\n private final String id;", "score": 0.8758682012557983 }, { "filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java", "retrieved_chunk": " private final StartupMode startupMode;\n private final String transactionalIdPrefix;\n private final String deliveryGuarantee;\n @Unmodifiable private final Map<String, String> properties;\n public StreamConfig(String id, String name, Map<String, String> properties) {\n this.id = id;\n this.name = name;\n this.bootstrapServers =\n properties.get(PROPERTIES_PREFIX + ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG);\n this.topic = properties.get(\"topic\");", "score": 0.8666074872016907 } ]
java
if (streamConfig.startupMode() != null) {
package com.home.chat.services; import cn.hutool.core.map.MapUtil; import cn.hutool.core.text.UnicodeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.http.Header; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.home.chat.controllers.request.Message; import com.home.chat.controllers.request.QueryUserBalanceRequest; import com.home.chat.controllers.response.QueryBalanceResponse; import com.home.chat.controllers.response.QueryUserBalanceResponse; import com.home.chat.dao.TbApikeyDAO; import com.home.chat.dao.TbUserKeyDAO; import com.home.chat.domain.OpenAiConfig; import com.home.chat.domain.ChatWebConfig; import com.home.chat.pojo.entity.TbApikeyEntity; import com.home.chat.pojo.entity.TbUserKeyEntity; import com.home.chat.pojo.query.TbApikeyQuery; import com.home.chat.pojo.query.TbUserKeyQuery; import com.home.chat.utils.DateUtil; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @Service @RequiredArgsConstructor @Slf4j public class ChatGPTService { private final OpenAiConfig openAiConfig; private final ChatWebConfig xinQiuConfig; @Autowired TbApikeyDAO tbApikeyDAO; @Autowired TbUserKeyDAO tbUserKeyDAO; public QueryBalanceResponse creditQuery(String key) { String apikey = openAiConfig.getApiKey(); if (StrUtil.isNotBlank(key)) { apikey = key; } String result = HttpRequest.get(openAiConfig.getCreditApi()) .header(Header.CONTENT_TYPE, "application/json") .header(Header.AUTHORIZATION, "Bearer " + apikey) .execute().body(); if (result.contains("server_error")) { throw new RuntimeException("请求ChatGPT官方服务器出错"); } JSONObject jsonObject = JSONUtil.parseObj(result); // 返回结果 return QueryBalanceResponse.builder() .balances(jsonObject.getStr("total_available")) .build(); } private void genImage(Message message, String key, Consumer<String> send) { // 请求参数 Map<String, String> userMessage = MapUtil.of( "size", "512x512" ); userMessage.put("prompt", message.getMessage().get(0)); // 调用接口 String result = HttpRequest.post(openAiConfig.getImageApi()) .header(Header.CONTENT_TYPE, "application/json") .header(Header.AUTHORIZATION, "Bearer " + key) .body(JSONUtil.toJsonStr(userMessage)) .execute().body(); // 正则匹配出结果 Pattern p = Pattern.compile("\"url\": \"(.*?)\""); Matcher m = p.matcher(result); if (m.find()) { send.accept(m.group(1)); //扣除次数 tbUserKeyDAO.useOnece(3,message.getApiKey()); } else { send.accept("图片生成失败!"); } } public void sendResponse(Message message, Consumer<String> send) throws IOException { TbUserKeyQuery userKeyQuery = new TbUserKeyQuery(); userKeyQuery.setUserKey(message.getApiKey()); TbUserKeyEntity tbUserKeyEntity = tbUserKeyDAO.queryForObject(userKeyQuery); if(StringUtils.isBlank(message.getApiKey()) || tbUserKeyEntity == null || !tbUserKeyEntity.getValidStatus().equals("1")){ send.accept("user key无效,请在页面左下角设置正确的key!"); return; } if(tbUserKeyEntity.getRemainingCount() <= 0){ send.accept("user key次数已耗尽!"); return; } TbApikeyQuery apikeyQuery = new TbApikeyQuery(); apikeyQuery.setValidStatus("1"); apikeyQuery.setEndDate(DateUtil.getCurrDate()); apikeyQuery.setOrder("balance desc,use_times asc"); TbApikeyEntity tbApikeyEntity = tbApikeyDAO.queryForObject(apikeyQuery); String key = tbApikeyEntity.getApiKey();
tbApikeyDAO.useOnece(key);
if (Objects.equals(message.getType(), Message.MessageType.IMAGE)) { genImage(message, key, send); return; } // 构建对话参数 List<Map<String, String>> messages = message.getMessage().stream().map(msg -> { Map<String, String> userMessage = MapUtil.of( "role", "user" ); userMessage.put("content", msg); return userMessage; }).collect(Collectors.toList()); // 构建请求参数 HashMap<Object, Object> params = new HashMap<>(); params.put("stream", true); params.put("model", openAiConfig.getModel()); params.put("messages", messages); // 调用接口 HttpResponse result; try { result = HttpRequest.post(openAiConfig.getOpenaiApi()) .header(Header.CONTENT_TYPE, "application/json") .header(Header.AUTHORIZATION, "Bearer " + key) .body(JSONUtil.toJsonStr(params)) .executeAsync(); } catch (Exception e) { send.accept(String.join("", "出错了", e.getMessage())); send.accept("END"); return; } // 处理数据 String line; assert result != null; BufferedReader reader = new BufferedReader(new InputStreamReader(result.bodyStream())); boolean printErrorMsg = false; StringBuilder errMsg = new StringBuilder(); Boolean userflag = false; while ((line = reader.readLine()) != null) { String msgResult = UnicodeUtil.toString(line); // 正则匹配错误信息 if (msgResult.contains("\"error\":")) { printErrorMsg = true; } // 如果出错,打印错误信息 if (printErrorMsg) { errMsg.append(msgResult); } else if (msgResult.contains("content")) { String data = JSONUtil.parseObj(line.substring(5)).getByPath("choices[0].delta.content").toString(); send.accept(data); //扣除次数 userflag = true; } } if(userflag){ //这里可以调整消耗次数 tbUserKeyDAO.useOnece(message.getMessage().size() > 1 ? message.getMessage().size()/2 : 1,message.getApiKey()); } // 关闭流 reader.close(); // 如果出错,抛出异常 if (printErrorMsg) { send.accept(errMsg.toString()); send.accept("END"); } send.accept("END"); } public QueryUserBalanceResponse queryUserBalance(QueryUserBalanceRequest request){ QueryUserBalanceResponse response = new QueryUserBalanceResponse(); TbUserKeyQuery query = new TbUserKeyQuery(); query.setUserKey(request.getKey()); TbUserKeyEntity tbUserKeyEntity = tbUserKeyDAO.queryForObject(query); if(tbUserKeyEntity == null){ return response; } response.setExpireDate(tbUserKeyEntity.getExpireDate()); response.setRemainingCount(tbUserKeyEntity.getRemainingCount()); return response; } }
src/main/java/com/home/chat/services/ChatGPTService.java
dd8023dd-chatgpt-web-server-7bd2f76
[ { "filename": "src/main/java/com/home/chat/dao/TbUserKeyDAO.java", "retrieved_chunk": " * @return 表记录实体类对象集合list\n */\n List<TbUserKeyEntity> queryForPage(TbUserKeyQuery query);\n /**\n * 通过查询条件查询表记录列表\n * @param query 查询条件对象\n * @return 表记录实体类对象\n */\n TbUserKeyEntity queryForObject(TbUserKeyQuery query);\n int useOnece(int useTimes,String userkey);", "score": 0.8449265956878662 }, { "filename": "src/main/java/com/home/chat/dao/TbApikeyDAO.java", "retrieved_chunk": " * @return 表记录实体类对象集合list\n */\n List<TbApikeyEntity> queryForPage(TbApikeyQuery query);\n /**\n * 通过查询条件查询表记录列表\n * @param query 查询条件对象\n * @return 表记录实体类对象\n */\n TbApikeyEntity queryForObject(TbApikeyQuery query);\n int useOnece(String apikey);", "score": 0.8419643640518188 }, { "filename": "src/main/java/com/home/chat/pojo/entity/TbApikeyEntity.java", "retrieved_chunk": " private String balance;\n /**\n * 失效日期\n *\n * column tb_apikey.expire_date\n */\n private Long expireDate;\n /**\n * 使用次数\n *", "score": 0.8319913148880005 }, { "filename": "src/main/java/com/home/chat/pojo/query/TbApikeyQuery.java", "retrieved_chunk": " */\n public Long getUseTimes() {\n return useTimes;\n }\n /**\n * 使用次数\n *\n * @param useTimes the value for tb_apikey.use_times\n */\n public void setUseTimes(Long useTimes) {", "score": 0.8292872905731201 }, { "filename": "src/main/java/com/home/chat/pojo/query/TbApikeyQuery.java", "retrieved_chunk": " private Long useTimes;\n /**\n * 正常-1,失效-2\n *\n * column tb_apikey.valid_status\n */\n private String validStatus;\n /**\n *\n * column tb_apikey.row_id", "score": 0.8288000822067261 } ]
java
tbApikeyDAO.useOnece(key);
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else {
Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT");
localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8378177285194397 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.8317219614982605 }, { "filename": "jdbc-plus-samples/src/test/java/com/github/deeround/jdbc/plus/samples/Tests.java", "retrieved_chunk": " @Autowired\n private TestUserService testUserService;\n @Test\n void testPage123() {\n PageInfo<Map<String, Object>> page1 = this.jdbcTemplateTestService.page1();\n PageInfo<Map<String, Object>> page2 = this.jdbcTemplateTestService.page2();\n PageInfo<Map<String, Object>> page3 = this.jdbcTemplateTestService.page3();\n System.out.println(page1);\n System.out.println(page2);\n System.out.println(page3);", "score": 0.8173043131828308 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.815990149974823 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " @Override\n public Object mapRow(ResultSet rs, int rowNum) throws SQLException {\n log.info(\"rowNum==>{}\", rowNum);\n return TestAllServiceImpl.toMap(rs);\n }\n }, \"test_tenant_4\");\n PageInfo<Object> page = new PageInfo<>(query);\n }\n /**\n * List<Map<String, Object>> void QUERYForList(String sql)", "score": 0.8148055076599121 } ]
java
Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT");
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); //逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参 if (methodInfo.getArgs
() != null && methodInfo.getArgs().length > 0) {
//回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.9404913187026978 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.9175166487693787 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.9144925475120544 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java", "retrieved_chunk": " }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return;\n }\n try {\n MethodActionInfo actionInfo = methodInfo.getActionInfo();\n Dialect dialect = PageHelper.getDialect(jdbcTemplate);", "score": 0.8812068104743958 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.8643438816070557 } ]
java
() != null && methodInfo.getArgs().length > 0) {
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql
), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT");
localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8304829597473145 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.8246047496795654 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " @Override\n public Object mapRow(ResultSet rs, int rowNum) throws SQLException {\n log.info(\"rowNum==>{}\", rowNum);\n return TestAllServiceImpl.toMap(rs);\n }\n }, \"test_tenant_4\");\n PageInfo<Object> page = new PageInfo<>(query);\n }\n /**\n * List<Map<String, Object>> void QUERYForList(String sql)", "score": 0.8124634623527527 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.8117724061012268 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " private int pages;\n /**\n * 包含count查询\n */\n private boolean count = true;\n /**\n * 分页合理化\n */\n private Boolean reasonable;\n /**", "score": 0.8108769655227661 } ]
java
), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT");
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object
cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT");
localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.8268126249313354 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8248598575592041 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.8208699822425842 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " private int pages;\n /**\n * 包含count查询\n */\n private boolean count = true;\n /**\n * 分页合理化\n */\n private Boolean reasonable;\n /**", "score": 0.8182600140571594 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/AbstractDialect.java", "retrieved_chunk": "public abstract class AbstractDialect implements Dialect {\n @Override\n public String getCountSql(String sql) {\n return \"SELECT COUNT(*) AS PG_COUNT FROM ( \" + sql + \" ) PG_TB \";\n }\n}", "score": 0.817159116268158 } ]
java
cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT");
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); //逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参 if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { //回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log
.debug("finish sql==>{
}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " log.info(\"调用方法名称:{}\", methodInfo.getName());\n log.info(\"调用方法入参:{}\", Arrays.toString(methodInfo.getArgs()));\n methodInfo.putUserAttribute(\"startTime\", LocalDateTime.now());\n }\n /**\n * SQL执行完成后方法(主要用于对返回值修改)\n *\n * @param result 原始返回对象\n * @return 处理后的返回对象\n */", "score": 0.8671027421951294 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8638879060745239 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL结束时间:{}\", LocalDateTime.now());\n LocalDateTime startTime = (LocalDateTime) methodInfo.getUserAttribute(\"startTime\");\n log.info(\"执行SQL耗时:{}毫秒\", Duration.between(startTime, LocalDateTime.now()).toMillis());\n return result;\n }\n}", "score": 0.8449831008911133 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8353121280670166 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.8325417041778564 } ]
java
.debug("finish sql==>{
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 abel533@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.deeround.jdbc.plus.Interceptor.pagination; import java.util.Collection; import java.util.List; /** * 对Page<E>结果进行包装 * <p/> * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907 * * @author liuzh/abel533/isea533 * @version 3.3.0 * @since 3.2.2 * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper */ public class PageInfo<T> extends PageSerializable<T> { public static final int DEFAULT_NAVIGATE_PAGES = 8; //当前页 private int pageNum; //每页的数量 private int pageSize; //当前页的数量 private int size; //由于startRow和endRow不常用,这里说个具体的用法 //可以在页面中"显示startRow到endRow 共size条数据" //当前页面第一个元素在数据库中的行号 private long startRow; //当前页面最后一个元素在数据库中的行号 private long endRow; //总页数 private int pages; //前一页 private int prePage; //下一页 private int nextPage; //是否为第一页 private boolean isFirstPage = false; //是否为最后一页 private boolean isLastPage = false; //是否有前一页 private boolean hasPreviousPage = false; //是否有下一页 private boolean hasNextPage = false; //导航页码数 private int navigatePages; //所有导航页号 private int[] navigatepageNums; //导航条上的第一页 private int navigateFirstPage; //导航条上的最后一页 private int navigateLastPage; public PageInfo() { } /** * 包装Page对象 * * @param list */ public PageInfo(List<T> list) { this(list, DEFAULT_NAVIGATE_PAGES); } /** * 包装Page对象 * * @param list page结果 * @param navigatePages 页码数量 */ public PageInfo(List<T> list, int navigatePages) { super(list); if (list instanceof Page) { Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.
pages = page.getPages();
this.size = page.size(); //由于结果是>startRow的,所以实际的需要+1 if (this.size == 0) { this.startRow = 0; this.endRow = 0; } else { this.startRow = page.getStartRow() + 1; //计算实际的endRow(最后一页的时候特殊) this.endRow = this.startRow - 1 + this.size; } } else if (list instanceof Collection) { this.pageNum = 1; this.pageSize = list.size(); this.pages = this.pageSize > 0 ? 1 : 0; this.size = list.size(); this.startRow = 0; this.endRow = list.size() > 0 ? list.size() - 1 : 0; } if (list instanceof Collection) { this.calcByNavigatePages(navigatePages); } } public static <T> PageInfo<T> of(List<T> list) { return new PageInfo<T>(list); } public static <T> PageInfo<T> of(List<T> list, int navigatePages) { return new PageInfo<T>(list, navigatePages); } public void calcByNavigatePages(int navigatePages) { this.setNavigatePages(navigatePages); //计算导航页 this.calcNavigatepageNums(); //计算前后页,第一页,最后一页 this.calcPage(); //判断页面边界 this.judgePageBoudary(); } /** * 计算导航页 */ private void calcNavigatepageNums() { //当总页数小于或等于导航页码数时 if (this.pages <= this.navigatePages) { this.navigatepageNums = new int[this.pages]; for (int i = 0; i < this.pages; i++) { this.navigatepageNums[i] = i + 1; } } else { //当总页数大于导航页码数时 this.navigatepageNums = new int[this.navigatePages]; int startNum = this.pageNum - this.navigatePages / 2; int endNum = this.pageNum + this.navigatePages / 2; if (startNum < 1) { startNum = 1; //(最前navigatePages页 for (int i = 0; i < this.navigatePages; i++) { this.navigatepageNums[i] = startNum++; } } else if (endNum > this.pages) { endNum = this.pages; //最后navigatePages页 for (int i = this.navigatePages - 1; i >= 0; i--) { this.navigatepageNums[i] = endNum--; } } else { //所有中间页 for (int i = 0; i < this.navigatePages; i++) { this.navigatepageNums[i] = startNum++; } } } } /** * 计算前后页,第一页,最后一页 */ private void calcPage() { if (this.navigatepageNums != null && this.navigatepageNums.length > 0) { this.navigateFirstPage = this.navigatepageNums[0]; this.navigateLastPage = this.navigatepageNums[this.navigatepageNums.length - 1]; if (this.pageNum > 1) { this.prePage = this.pageNum - 1; } if (this.pageNum < this.pages) { this.nextPage = this.pageNum + 1; } } } /** * 判定页面边界 */ private void judgePageBoudary() { this.isFirstPage = this.pageNum == 1; this.isLastPage = this.pageNum == this.pages || this.pages == 0; this.hasPreviousPage = this.pageNum > 1; this.hasNextPage = this.pageNum < this.pages; } public int getPageNum() { return this.pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return this.pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } public long getStartRow() { return this.startRow; } public void setStartRow(long startRow) { this.startRow = startRow; } public long getEndRow() { return this.endRow; } public void setEndRow(long endRow) { this.endRow = endRow; } public int getPages() { return this.pages; } public void setPages(int pages) { this.pages = pages; } public int getPrePage() { return this.prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return this.nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public boolean isFirstPage() { return this.isFirstPage; } public void setFirstPage(boolean firstPage) { this.isFirstPage = firstPage; } public boolean isLastPage() { return this.isLastPage; } public void setLastPage(boolean lastPage) { this.isLastPage = lastPage; } public boolean isHasPreviousPage() { return this.hasPreviousPage; } public void setHasPreviousPage(boolean hasPreviousPage) { this.hasPreviousPage = hasPreviousPage; } public boolean isHasNextPage() { return this.hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } public int getNavigatePages() { return this.navigatePages; } public void setNavigatePages(int navigatePages) { this.navigatePages = navigatePages; } public int[] getNavigatepageNums() { return this.navigatepageNums; } public void setNavigatepageNums(int[] navigatepageNums) { this.navigatepageNums = navigatepageNums; } public int getNavigateFirstPage() { return this.navigateFirstPage; } public void setNavigateFirstPage(int navigateFirstPage) { this.navigateFirstPage = navigateFirstPage; } public int getNavigateLastPage() { return this.navigateLastPage; } public void setNavigateLastPage(int navigateLastPage) { this.navigateLastPage = navigateLastPage; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PageInfo{"); sb.append("pageNum=").append(this.pageNum); sb.append(", pageSize=").append(this.pageSize); sb.append(", size=").append(this.size); sb.append(", startRow=").append(this.startRow); sb.append(", endRow=").append(this.endRow); sb.append(", total=").append(this.total); sb.append(", pages=").append(this.pages); sb.append(", list=").append(this.list); sb.append(", prePage=").append(this.prePage); sb.append(", nextPage=").append(this.nextPage); sb.append(", isFirstPage=").append(this.isFirstPage); sb.append(", isLastPage=").append(this.isLastPage); sb.append(", hasPreviousPage=").append(this.hasPreviousPage); sb.append(", hasNextPage=").append(this.hasNextPage); sb.append(", navigatePages=").append(this.navigatePages); sb.append(", navigateFirstPage=").append(this.navigateFirstPage); sb.append(", navigateLastPage=").append(this.navigateLastPage); sb.append(", navigatepageNums="); if (this.navigatepageNums == null) { sb.append("null"); } else { sb.append('['); for (int i = 0; i < this.navigatepageNums.length; ++i) { sb.append(i == 0 ? "" : ", ").append(this.navigatepageNums[i]); } sb.append(']'); } sb.append('}'); return sb.toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageInfo.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageSerializable.java", "retrieved_chunk": " private static final long serialVersionUID = 1L;\n //总记录数\n protected long total;\n //结果集\n protected List<T> list;\n public PageSerializable() {\n }\n public PageSerializable(List<T> list) {\n this.list = list;\n if (list instanceof Page) {", "score": 0.8521000146865845 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageSerializable.java", "retrieved_chunk": " this.total = ((Page) list).getTotal();\n } else {\n this.total = list.size();\n }\n }\n public static <T> PageSerializable<T> of(List<T> list) {\n return new PageSerializable<T>(list);\n }\n public long getTotal() {\n return this.total;", "score": 0.8334404230117798 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8260124325752258 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " * 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果\n */\n private Boolean pageSizeZero;\n public Page() {\n super();\n }\n public Page(int pageNum, int pageSize) {\n this(pageNum, pageSize, true, null);\n }\n public Page(int pageNum, int pageSize, boolean count) {", "score": 0.8070563077926636 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " this(pageNum, pageSize, count, null);\n }\n public Page(int pageNum, int pageSize, boolean count, Boolean reasonable) {\n this(pageNum, pageSize, count, null, null);\n }\n public Page(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {\n super(0);\n if (pageNum == 1 && pageSize == Integer.MAX_VALUE) {\n this.pageSizeZero = true;\n pageSize = 0;", "score": 0.806311845779419 } ]
java
pages = page.getPages();
package com.github.deeround.jdbc.plus.method; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/23 14:24 */ public class MethodInvocationInfo extends MethodInfo { private boolean isSupport; private final Object[] args; private MethodType type; private MethodActionInfo actionInfo; private final Map<String, Object> userAttributes = new HashMap<>(0); public MethodInvocationInfo(final Object[] args, Method method) { super(method); this.args = args; this.type = MethodType.UNKNOWN; this.isSupport = false; this.resolveMethod(); } public Object[] getArgs() { return this.args; } public MethodType getType() { return this.type; } public boolean isSupport() { return this.isSupport; } public MethodActionInfo getActionInfo() { return this.actionInfo; } public Map<String, Object> getUserAttributes() { return this.userAttributes; } public void putUserAttribute(String key, Object value) { if (this.userAttributes != null) { this.userAttributes.put(key, value); } } public Object getUserAttribute(String key) { if (this.userAttributes != null) { return this.userAttributes.get(key); } return null; } //=================METHOD START================ public void resolveSql(String sql) { this.resolveSql(new String[]{sql}); } public void resolveSql(String[] batchSql) { if (this.actionInfo != null) { if (batchSql == null || batchSql.length == 0) { throw new RuntimeException("batchSql不能为空"); } this.actionInfo.setBatchSql(batchSql); if (this.actionInfo.isSqlIsBatch()) { this.args[0] = this.actionInfo.getBatchSql(); } else { this.args[0] = this.actionInfo.getSql(); } } } public void resolveSql(int i, String sql) { if (this.actionInfo != null) { this.actionInfo.getBatchSql()[i] = sql; if (this.actionInfo.isSqlIsBatch()) { this.args[0] = this.actionInfo.getBatchSql(); } else { this.args[0] = this.actionInfo.getSql(); } } } public void resolveParameter(Object[] parameter) { List<Object[]> objects = new ArrayList<>(); objects.add(parameter); this.resolveParameter(objects); } public void resolveParameter(List<Object[]> batchParameter) { if (this.actionInfo != null) { if (batchParameter == null || batchParameter.size() == 0) { throw new RuntimeException("batchParameter不能为空"); } this.actionInfo.setBatchParameter(batchParameter); if (this.actionInfo.isHasParameter()) { if (!this.actionInfo.isParameterIsPss()) { if (this.actionInfo.isParameterIsBatch()) { this.args[this.actionInfo.getParameterIndex()] = this.actionInfo.getBatchParameter(); } else { this.args[this.actionInfo.getParameterIndex()
] = this.actionInfo.getParameter();
} } } } } //=================METHOD END================ /** * 解析Method */ private void resolveMethod() { if (this.getName().startsWith("execute")) { this.type = MethodType.EXECUTE; } else if (this.getName().startsWith("batchUpdate")) { this.type = MethodType.UPDATE; } else if (this.getName().startsWith("update")) { this.type = MethodType.UPDATE; } else if (this.getName().startsWith("query")) { this.type = MethodType.QUERY; } this.actionInfo = MethodActionRegister.getMethodActionInfo(this.getMethod(), this.args); if (this.actionInfo != null && !this.actionInfo.getActionType().equals(MethodActionType.UNKNOWN)) { this.isSupport = true; } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.9015569090843201 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionInfo.java", "retrieved_chunk": " */\n private List<Object[]> batchParameter;\n /**\n * 参数是否是批量\n */\n private boolean parameterIsBatch;\n /**\n * 入参索引\n */\n private int parameterIndex;", "score": 0.8807256817817688 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionInfo.java", "retrieved_chunk": " public Object[] getParameter() {\n if (this.batchParameter != null && this.batchParameter.size() > 0) {\n return this.batchParameter.get(0);\n }\n return null;\n }\n private void setParameter(Object[] parameter) {\n }\n //以下是针对出参分分析\n /**", "score": 0.8486462831497192 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionInfo.java", "retrieved_chunk": " /**\n * 入参是否是pss\n */\n private boolean parameterIsPss;\n /**\n * 入参Object[]\n */\n// private Object[] parameter;\n /**\n * 批量入参List<Object[]>", "score": 0.8425033092498779 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionInfo.java", "retrieved_chunk": " private String[] batchSql;\n /**\n * 是否批量SQL语句\n */\n private boolean sqlIsBatch;\n //以下针对入参-SQL入参\n /**\n * 是否有入参\n */\n private boolean hasParameter;", "score": 0.8378497362136841 } ]
java
] = this.actionInfo.getParameter();
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package dev.cru.context.k8s; import dev.cru.context.Location; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class K8sNeedleExtractor { private final Pattern cpuPattern = Pattern.compile( "cru: container=(?<container>.*) cluster=(?<cluster>.*)\\n\\s*cpu: (?<cpu>\\S*)" ); private final Pattern memoryPattern = Pattern.compile( "cru: container=(?<container>.*) cluster=(?<cluster>.*)\\n\\s*memory: (?<memory>\\S*)" ); public Set<Match> extractLinesFrom(Location location) { Set<Match> result = new HashSet<>(); for (Matcher cpuMatcher =
cpuPattern.matcher(location.fileContent());
cpuMatcher.find();) { result.add( new Match( cpuMatcher.group("container"), cpuMatcher.group("cluster"), cpuMatcher.group("cpu"), K8sResourceType.Cpu ) ); } for (Matcher memoryMatcher = memoryPattern.matcher(location.fileContent()); memoryMatcher.find();) { result.add( new Match( memoryMatcher.group("container"), memoryMatcher.group("cluster"), memoryMatcher.group("memory"), K8sResourceType.Memory ) ); } return result; } public record Match(String container, String namespace, String value, K8sResourceType resourceType) {} }
src/main/java/dev/cru/context/k8s/K8sNeedleExtractor.java
DennisRippinger-cru-6558fde
[ { "filename": "src/test/java/dev/cru/context/K8sNeedleExtractorTest.java", "retrieved_chunk": "\t\t\tPath.of(\"src\", \"test\", \"resources\", \"K8s\", \"patch-resources.yaml\")\n\t\t);\n\t\tSet<K8sNeedleExtractor.Match> matches = new K8sNeedleExtractor().extractLinesFrom(k8sTestLocation);\n\t\tassertThat(matches)\n\t\t\t.contains(\n\t\t\t\tnew K8sNeedleExtractor.Match(\"container_one\", \"Cluster1\", \"670m\", K8sResourceType.Cpu),\n\t\t\t\tnew K8sNeedleExtractor.Match(\"container_one\", \"Cluster1\", \"1021Mi\", K8sResourceType.Memory),\n\t\t\t\tnew K8sNeedleExtractor.Match(\"container_two\", \"Cluster1\", \"298m\", K8sResourceType.Cpu),\n\t\t\t\tnew K8sNeedleExtractor.Match(\"container_two\", \"Cluster1\", \"40Mi\", K8sResourceType.Memory)\n\t\t\t);", "score": 0.8439540863037109 }, { "filename": "src/test/java/dev/cru/context/K8sTestLocation.java", "retrieved_chunk": "import java.net.URI;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\npublic class K8sTestLocation implements Location {\n\tprivate final String location;\n\tprivate final String fileContent;\n\tpublic K8sTestLocation(Path location) throws IOException {\n\t\tthis.location = location.toString();\n\t\tfileContent = Files.readString(location);\n\t}", "score": 0.7902344465255737 }, { "filename": "src/test/java/dev/cru/context/K8sNeedleExtractorTest.java", "retrieved_chunk": "import dev.cru.context.k8s.K8sNeedleExtractor;\nimport dev.cru.context.k8s.K8sResourceType;\nimport java.io.IOException;\nimport java.nio.file.Path;\nimport java.util.Set;\nimport org.junit.jupiter.api.Test;\nclass K8sNeedleExtractorTest {\n\t@Test\n\tvoid name() throws IOException {\n\t\tK8sTestLocation k8sTestLocation = new K8sTestLocation(", "score": 0.7664825320243835 }, { "filename": "src/main/java/dev/cru/context/k8s/ResourceParser.java", "retrieved_chunk": "\t// TODO Layman Solution for first approach, replace with comparable data later.\n\tpublic static double parseMemory(String input) {\n\t\treturn Double.parseDouble(input.replace(\"Mi\", \"\"));\n\t}\n\tpublic static double parseCpu(String input) {\n\t\treturn Double.parseDouble(input.replace(\"m\", \"\"));\n\t}\n}", "score": 0.755645751953125 }, { "filename": "src/test/java/dev/cru/context/K8sTestLocation.java", "retrieved_chunk": "\t@Override\n\tpublic String path() {\n\t\treturn location;\n\t}\n\t@Override\n\tpublic String fileContent() {\n\t\treturn fileContent;\n\t}\n\t@Override\n\tpublic boolean isVirtual() {", "score": 0.7498449087142944 } ]
java
cpuPattern.matcher(location.fileContent());
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try {
MethodActionInfo actionInfo = methodInfo.getActionInfo();
Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.9080883264541626 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.9071826338768005 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8795514106750488 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " log.debug(\"origin sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"origin parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n //逻辑处理(核心方法:主要处理SQL和SQL参数)\n if (this.interceptors != null && this.interceptors.size() > 0) {\n for (IInterceptor interceptor : this.interceptors) {\n if (interceptor.supportMethod(methodInfo)) {\n interceptor.beforePrepare(methodInfo, jdbcTemplate);\n //插件允许修改原始SQL以及入参\n if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {\n //回写参数", "score": 0.8567171692848206 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/IInterceptor.java", "retrieved_chunk": " * @since 3.4.0\n */\npublic interface IInterceptor {\n default boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return true;\n }\n default void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n // do nothing\n }\n default Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {", "score": 0.848887026309967 } ]
java
MethodActionInfo actionInfo = methodInfo.getActionInfo();
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log
.debug("method==>name:{
},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); //逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参 if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { //回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8168932795524597 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java", "retrieved_chunk": " }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return;\n }\n try {\n MethodActionInfo actionInfo = methodInfo.getActionInfo();\n Dialect dialect = PageHelper.getDialect(jdbcTemplate);", "score": 0.8107224702835083 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodAdvisor.java", "retrieved_chunk": "import org.springframework.aop.support.AbstractPointcutAdvisor;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\n/**\n * @author TaoYu\n * @since 1.2.0\n */\npublic class JdbcTemplateMethodAdvisor extends AbstractPointcutAdvisor implements BeanFactoryAware {\n private final Advice advice;", "score": 0.80159991979599 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInfo.java", "retrieved_chunk": "package com.github.deeround.jdbc.plus.method;\nimport java.lang.reflect.Method;\n/**\n * @author wanghao 913351190@qq.com\n * @create 2023/4/20 16:53\n */\npublic class MethodInfo {\n private Method method;\n private String name;\n private Class<?>[] parameterTypes;", "score": 0.8013963103294373 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": "package com.github.deeround.jdbc.plus.method;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.jdbc.core.*;\nimport java.lang.reflect.Method;\nimport java.util.*;\n/**\n * @author wanghao 913351190@qq.com\n * @create 2023/7/17 15:24\n */\n@Slf4j", "score": 0.8006819486618042 } ]
java
.debug("method==>name:{
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.
queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT");
localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8286616206169128 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.823328971862793 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " @Override\n public Object mapRow(ResultSet rs, int rowNum) throws SQLException {\n log.info(\"rowNum==>{}\", rowNum);\n return TestAllServiceImpl.toMap(rs);\n }\n }, \"test_tenant_4\");\n PageInfo<Object> page = new PageInfo<>(query);\n }\n /**\n * List<Map<String, Object>> void QUERYForList(String sql)", "score": 0.8123044371604919 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.8110651969909668 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " private int pages;\n /**\n * 包含count查询\n */\n private boolean count = true;\n /**\n * 分页合理化\n */\n private Boolean reasonable;\n /**", "score": 0.8079084157943726 } ]
java
queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT");
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate);
String sql = actionInfo.getSql();
//查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8992435336112976 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.8943495750427246 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8930454254150391 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " log.debug(\"origin sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"origin parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n //逻辑处理(核心方法:主要处理SQL和SQL参数)\n if (this.interceptors != null && this.interceptors.size() > 0) {\n for (IInterceptor interceptor : this.interceptors) {\n if (interceptor.supportMethod(methodInfo)) {\n interceptor.beforePrepare(methodInfo, jdbcTemplate);\n //插件允许修改原始SQL以及入参\n if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {\n //回写参数", "score": 0.8773099780082703 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL结束时间:{}\", LocalDateTime.now());\n LocalDateTime startTime = (LocalDateTime) methodInfo.getUserAttribute(\"startTime\");\n log.info(\"执行SQL耗时:{}毫秒\", Duration.between(startTime, LocalDateTime.now()).toMillis());\n return result;\n }\n}", "score": 0.8715993165969849 } ]
java
String sql = actionInfo.getSql();
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package dev.cru.context; import dev.cru.conf.Repository; import dev.cru.repository.gitlab.GitLabMockRepositoryApi; import java.util.List; public class CruService { private final GitLabMockRepositoryApi gitLabRepositoryApi = new GitLabMockRepositoryApi(); public List<String> applyGitLab() { for (
Repository repository : gitLabRepositoryApi.findRepositories()) {
applyFor(repository); } return List.of(); } public List<String> applyFor(Repository repository) { for (Location location : gitLabRepositoryApi.readLocationsFrom(repository)) {} return List.of(); } }
src/main/java/dev/cru/context/CruService.java
DennisRippinger-cru-6558fde
[ { "filename": "src/main/java/dev/cru/repository/gitlab/GitLabMockRepositoryApi.java", "retrieved_chunk": "import dev.cru.conf.Repository;\nimport dev.cru.context.Location;\nimport dev.cru.repository.RepositoryApi;\nimport java.util.List;\npublic class GitLabMockRepositoryApi implements RepositoryApi {\n\t@Override\n\tpublic Iterable<Repository> findRepositories() {\n\t\treturn List.of(\n\t\t\tnew Repository(\n\t\t\t\t\"12345\",", "score": 0.9003578424453735 }, { "filename": "src/main/java/dev/cru/repository/gitlab/GitLabMockRepositoryApi.java", "retrieved_chunk": " *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dev.cru.repository.gitlab;\nimport dev.cru.conf.RepoConfig;", "score": 0.8627105951309204 }, { "filename": "src/main/java/dev/cru/repository/RepositoryApi.java", "retrieved_chunk": " *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dev.cru.repository;\nimport dev.cru.conf.Repository;", "score": 0.8539658784866333 }, { "filename": "src/main/java/dev/cru/repository/package-info.java", "retrieved_chunk": " */\npackage dev.cru.repository;", "score": 0.849341630935669 }, { "filename": "src/main/java/dev/cru/repository/gitlab/package-info.java", "retrieved_chunk": " *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n */\npackage dev.cru.repository.gitlab;", "score": 0.8459193110466003 } ]
java
Repository repository : gitLabRepositoryApi.findRepositories()) {
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount
() && methodInfo.getActionInfo().isReturnIsList()) {
if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8333632946014404 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.8333301544189453 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " log.debug(\"origin sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"origin parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n //逻辑处理(核心方法:主要处理SQL和SQL参数)\n if (this.interceptors != null && this.interceptors.size() > 0) {\n for (IInterceptor interceptor : this.interceptors) {\n if (interceptor.supportMethod(methodInfo)) {\n interceptor.beforePrepare(methodInfo, jdbcTemplate);\n //插件允许修改原始SQL以及入参\n if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {\n //回写参数", "score": 0.8272228240966797 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8270230293273926 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.826499879360199 } ]
java
() && methodInfo.getActionInfo().isReturnIsList()) {
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(
sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() {
@Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " log.debug(\"origin sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"origin parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n //逻辑处理(核心方法:主要处理SQL和SQL参数)\n if (this.interceptors != null && this.interceptors.size() > 0) {\n for (IInterceptor interceptor : this.interceptors) {\n if (interceptor.supportMethod(methodInfo)) {\n interceptor.beforePrepare(methodInfo, jdbcTemplate);\n //插件允许修改原始SQL以及入参\n if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {\n //回写参数", "score": 0.846807599067688 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " }\n public static MethodActionInfo getMethodActionInfo(Method method, Object[] args) {\n if (Method_MAP.containsKey(method)) {\n MethodActionInfo actionInfo = Method_MAP.get(method);\n //SQL语句\n if (actionInfo.isSqlIsBatch()) {\n actionInfo.setBatchSql((String[]) args[0]);\n } else {\n actionInfo.setBatchSql(new String[]{(String) args[0]});\n }", "score": 0.8426641821861267 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }\n public PageInfo<Map<String, Object>> page2() {\n PageHelper.startPage(2, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 2,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)", "score": 0.8418546915054321 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8416250944137573 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " return page;\n }\n public PageInfo<Map<String, Object>> page3() {\n PageHelper.startPage(3, 2);\n List<Map<String, Object>> list = this.jdbcTemplate.queryForList(\"select * from test_user\");\n //最终执行SQL:select * from test_user LIMIT 4,2\n PageInfo<Map<String, Object>> page = new PageInfo<>(list);\n //PageInfo对象包含了分页信息(总行数等)\n return page;\n }", "score": 0.8394635915756226 } ]
java
sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() {
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("origin parameters==>{}", this.toStr
(methodInfo.getActionInfo().getBatchParameter()));
//逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参 if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { //回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8541297316551208 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8483745455741882 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.8469027280807495 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " }\n public static MethodActionInfo getMethodActionInfo(Method method, Object[] args) {\n if (Method_MAP.containsKey(method)) {\n MethodActionInfo actionInfo = Method_MAP.get(method);\n //SQL语句\n if (actionInfo.isSqlIsBatch()) {\n actionInfo.setBatchSql((String[]) args[0]);\n } else {\n actionInfo.setBatchSql(new String[]{(String) args[0]});\n }", "score": 0.8387923836708069 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " //SQL语句参数\n if (actionInfo.isHasParameter()) {\n if (!actionInfo.isParameterIsPss()) {\n if (actionInfo.isParameterIsBatch()) {\n actionInfo.setBatchParameter((List<Object[]>) args[actionInfo.getParameterIndex()]);\n } else {\n List<Object[]> batchParameter = new ArrayList<>();\n batchParameter.add((Object[]) args[actionInfo.getParameterIndex()]);\n actionInfo.setBatchParameter(batchParameter);\n }", "score": 0.819850504398346 } ]
java
(methodInfo.getActionInfo().getBatchParameter()));
/* * The MIT License (MIT) * * Copyright (c) 2014-2017 abel533@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.deeround.jdbc.plus.Interceptor.pagination; import java.util.Collection; import java.util.List; /** * 对Page<E>结果进行包装 * <p/> * 新增分页的多项属性,主要参考:http://bbs.csdn.net/topics/360010907 * * @author liuzh/abel533/isea533 * @version 3.3.0 * @since 3.2.2 * 项目地址 : http://git.oschina.net/free/Mybatis_PageHelper */ public class PageInfo<T> extends PageSerializable<T> { public static final int DEFAULT_NAVIGATE_PAGES = 8; //当前页 private int pageNum; //每页的数量 private int pageSize; //当前页的数量 private int size; //由于startRow和endRow不常用,这里说个具体的用法 //可以在页面中"显示startRow到endRow 共size条数据" //当前页面第一个元素在数据库中的行号 private long startRow; //当前页面最后一个元素在数据库中的行号 private long endRow; //总页数 private int pages; //前一页 private int prePage; //下一页 private int nextPage; //是否为第一页 private boolean isFirstPage = false; //是否为最后一页 private boolean isLastPage = false; //是否有前一页 private boolean hasPreviousPage = false; //是否有下一页 private boolean hasNextPage = false; //导航页码数 private int navigatePages; //所有导航页号 private int[] navigatepageNums; //导航条上的第一页 private int navigateFirstPage; //导航条上的最后一页 private int navigateLastPage; public PageInfo() { } /** * 包装Page对象 * * @param list */ public PageInfo(List<T> list) { this(list, DEFAULT_NAVIGATE_PAGES); } /** * 包装Page对象 * * @param list page结果 * @param navigatePages 页码数量 */ public PageInfo(List<T> list, int navigatePages) { super(list); if (list instanceof Page) { Page page = (Page) list; this.pageNum = page.getPageNum(); this.pageSize = page.getPageSize(); this.pages = page.getPages(); this.size = page.size(); //由于结果是>startRow的,所以实际的需要+1 if (this.size == 0) { this.startRow = 0; this.endRow = 0; } else { this.startRow =
page.getStartRow() + 1;
//计算实际的endRow(最后一页的时候特殊) this.endRow = this.startRow - 1 + this.size; } } else if (list instanceof Collection) { this.pageNum = 1; this.pageSize = list.size(); this.pages = this.pageSize > 0 ? 1 : 0; this.size = list.size(); this.startRow = 0; this.endRow = list.size() > 0 ? list.size() - 1 : 0; } if (list instanceof Collection) { this.calcByNavigatePages(navigatePages); } } public static <T> PageInfo<T> of(List<T> list) { return new PageInfo<T>(list); } public static <T> PageInfo<T> of(List<T> list, int navigatePages) { return new PageInfo<T>(list, navigatePages); } public void calcByNavigatePages(int navigatePages) { this.setNavigatePages(navigatePages); //计算导航页 this.calcNavigatepageNums(); //计算前后页,第一页,最后一页 this.calcPage(); //判断页面边界 this.judgePageBoudary(); } /** * 计算导航页 */ private void calcNavigatepageNums() { //当总页数小于或等于导航页码数时 if (this.pages <= this.navigatePages) { this.navigatepageNums = new int[this.pages]; for (int i = 0; i < this.pages; i++) { this.navigatepageNums[i] = i + 1; } } else { //当总页数大于导航页码数时 this.navigatepageNums = new int[this.navigatePages]; int startNum = this.pageNum - this.navigatePages / 2; int endNum = this.pageNum + this.navigatePages / 2; if (startNum < 1) { startNum = 1; //(最前navigatePages页 for (int i = 0; i < this.navigatePages; i++) { this.navigatepageNums[i] = startNum++; } } else if (endNum > this.pages) { endNum = this.pages; //最后navigatePages页 for (int i = this.navigatePages - 1; i >= 0; i--) { this.navigatepageNums[i] = endNum--; } } else { //所有中间页 for (int i = 0; i < this.navigatePages; i++) { this.navigatepageNums[i] = startNum++; } } } } /** * 计算前后页,第一页,最后一页 */ private void calcPage() { if (this.navigatepageNums != null && this.navigatepageNums.length > 0) { this.navigateFirstPage = this.navigatepageNums[0]; this.navigateLastPage = this.navigatepageNums[this.navigatepageNums.length - 1]; if (this.pageNum > 1) { this.prePage = this.pageNum - 1; } if (this.pageNum < this.pages) { this.nextPage = this.pageNum + 1; } } } /** * 判定页面边界 */ private void judgePageBoudary() { this.isFirstPage = this.pageNum == 1; this.isLastPage = this.pageNum == this.pages || this.pages == 0; this.hasPreviousPage = this.pageNum > 1; this.hasNextPage = this.pageNum < this.pages; } public int getPageNum() { return this.pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return this.pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getSize() { return this.size; } public void setSize(int size) { this.size = size; } public long getStartRow() { return this.startRow; } public void setStartRow(long startRow) { this.startRow = startRow; } public long getEndRow() { return this.endRow; } public void setEndRow(long endRow) { this.endRow = endRow; } public int getPages() { return this.pages; } public void setPages(int pages) { this.pages = pages; } public int getPrePage() { return this.prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return this.nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public boolean isFirstPage() { return this.isFirstPage; } public void setFirstPage(boolean firstPage) { this.isFirstPage = firstPage; } public boolean isLastPage() { return this.isLastPage; } public void setLastPage(boolean lastPage) { this.isLastPage = lastPage; } public boolean isHasPreviousPage() { return this.hasPreviousPage; } public void setHasPreviousPage(boolean hasPreviousPage) { this.hasPreviousPage = hasPreviousPage; } public boolean isHasNextPage() { return this.hasNextPage; } public void setHasNextPage(boolean hasNextPage) { this.hasNextPage = hasNextPage; } public int getNavigatePages() { return this.navigatePages; } public void setNavigatePages(int navigatePages) { this.navigatePages = navigatePages; } public int[] getNavigatepageNums() { return this.navigatepageNums; } public void setNavigatepageNums(int[] navigatepageNums) { this.navigatepageNums = navigatepageNums; } public int getNavigateFirstPage() { return this.navigateFirstPage; } public void setNavigateFirstPage(int navigateFirstPage) { this.navigateFirstPage = navigateFirstPage; } public int getNavigateLastPage() { return this.navigateLastPage; } public void setNavigateLastPage(int navigateLastPage) { this.navigateLastPage = navigateLastPage; } @Override public String toString() { final StringBuilder sb = new StringBuilder("PageInfo{"); sb.append("pageNum=").append(this.pageNum); sb.append(", pageSize=").append(this.pageSize); sb.append(", size=").append(this.size); sb.append(", startRow=").append(this.startRow); sb.append(", endRow=").append(this.endRow); sb.append(", total=").append(this.total); sb.append(", pages=").append(this.pages); sb.append(", list=").append(this.list); sb.append(", prePage=").append(this.prePage); sb.append(", nextPage=").append(this.nextPage); sb.append(", isFirstPage=").append(this.isFirstPage); sb.append(", isLastPage=").append(this.isLastPage); sb.append(", hasPreviousPage=").append(this.hasPreviousPage); sb.append(", hasNextPage=").append(this.hasNextPage); sb.append(", navigatePages=").append(this.navigatePages); sb.append(", navigateFirstPage=").append(this.navigateFirstPage); sb.append(", navigateLastPage=").append(this.navigateLastPage); sb.append(", navigatepageNums="); if (this.navigatepageNums == null) { sb.append("null"); } else { sb.append('['); for (int i = 0; i < this.navigatepageNums.length; ++i) { sb.append(i == 0 ? "" : ", ").append(this.navigatepageNums[i]); } sb.append(']'); } sb.append('}'); return sb.toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageInfo.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " private int pageNum;\n /**\n * 页面大小\n */\n private int pageSize;\n /**\n * 起始行\n */\n private long startRow;\n /**", "score": 0.8867061138153076 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " }\n return this;\n }\n /**\n * 计算起止行号\n */\n private void calculateStartAndEndRow() {\n this.startRow = this.pageNum > 0 ? (this.pageNum - 1) * this.pageSize : 0;\n this.endRow = this.startRow + this.pageSize * (this.pageNum > 0 ? 1 : 0);\n }", "score": 0.8843692541122437 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " }\n public int getPages() {\n return this.pages;\n }\n public Page<E> setPages(int pages) {\n this.pages = pages;\n return this;\n }\n public long getEndRow() {\n return this.endRow;", "score": 0.870058536529541 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " }\n public Page<E> setEndRow(long endRow) {\n this.endRow = endRow;\n return this;\n }\n public int getPageNum() {\n return this.pageNum;\n }\n public Page<E> setPageNum(int pageNum) {\n //分页合理化,针对不合理的页码自动处理", "score": 0.8668362498283386 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java", "retrieved_chunk": " public long getStartRow() {\n return this.startRow;\n }\n public Page<E> setStartRow(long startRow) {\n this.startRow = startRow;\n return this;\n }\n public long getTotal() {\n return this.total;\n }", "score": 0.8621569871902466 } ]
java
page.getStartRow() + 1;
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); //逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参
if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {
//回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.9440433979034424 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.9210474491119385 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.9191190600395203 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java", "retrieved_chunk": " }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return;\n }\n try {\n MethodActionInfo actionInfo = methodInfo.getActionInfo();\n Dialect dialect = PageHelper.getDialect(jdbcTemplate);", "score": 0.8864254951477051 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " }\n public static MethodActionInfo getMethodActionInfo(Method method, Object[] args) {\n if (Method_MAP.containsKey(method)) {\n MethodActionInfo actionInfo = Method_MAP.get(method);\n //SQL语句\n if (actionInfo.isSqlIsBatch()) {\n actionInfo.setBatchSql((String[]) args[0]);\n } else {\n actionInfo.setBatchSql(new String[]{(String) args[0]});\n }", "score": 0.8609670400619507 } ]
java
if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {
/* * Copyright © 2018 organization baomidou * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.aop; import com.github.deeround.jdbc.plus.Interceptor.IInterceptor; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import lombok.extern.slf4j.Slf4j; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.jdbc.core.JdbcTemplate; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; @Slf4j public class JdbcTemplateMethodInterceptor implements MethodInterceptor { private final List<IInterceptor> interceptors; public JdbcTemplateMethodInterceptor(List<IInterceptor> interceptors) { this.interceptors = interceptors; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation; Object[] args = methodInvocation.getArguments(); Method method = methodInvocation.getMethod(); JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis(); final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method); log.debug("method==>name:{},actionType:{}", methodInfo.getName(), methodInfo.getActionInfo().getActionType()); log.debug("origin sql==>{}", this.
toStr(methodInfo.getActionInfo().getBatchSql()));
log.debug("origin parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); //逻辑处理(核心方法:主要处理SQL和SQL参数) if (this.interceptors != null && this.interceptors.size() > 0) { for (IInterceptor interceptor : this.interceptors) { if (interceptor.supportMethod(methodInfo)) { interceptor.beforePrepare(methodInfo, jdbcTemplate); //插件允许修改原始SQL以及入参 if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { //回写参数 methodInvocation.setArguments(methodInfo.getArgs()); } } } } log.debug("finish sql==>{}", this.toStr(methodInfo.getActionInfo().getBatchSql())); log.debug("finish parameters==>{}", this.toStr(methodInfo.getActionInfo().getBatchParameter())); Object result = methodInvocation.proceed(); log.debug("origin result==>{}", result); //逻辑处理 if (this.interceptors != null && this.interceptors.size() > 0) { for (int i = this.interceptors.size() - 1; i >= 0; i--) { IInterceptor interceptor = this.interceptors.get(i); if (interceptor.supportMethod(methodInfo)) { result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate); } } } log.debug("finish result==>{}", result); return result; } private String toStr(Object[] objs) { if (objs == null) { return null; } return Arrays.toString(objs); } private String toStr(List<Object[]> list) { if (list == null) { return null; } StringBuilder str = new StringBuilder(); str.append("["); for (int i = 0; i < list.size(); i++) { str.append(Arrays.toString(list.get(i))); if (i < list.size() - 1) { str.append(","); } } return str.append("]").toString(); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.8727498054504395 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));", "score": 0.8702349066734314 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.868206262588501 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionRegister.java", "retrieved_chunk": " }\n public static MethodActionInfo getMethodActionInfo(Method method, Object[] args) {\n if (Method_MAP.containsKey(method)) {\n MethodActionInfo actionInfo = Method_MAP.get(method);\n //SQL语句\n if (actionInfo.isSqlIsBatch()) {\n actionInfo.setBatchSql((String[]) args[0]);\n } else {\n actionInfo.setBatchSql(new String[]{(String) args[0]});\n }", "score": 0.8520183563232422 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java", "retrieved_chunk": " }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return;\n }\n try {\n MethodActionInfo actionInfo = methodInfo.getActionInfo();\n Dialect dialect = PageHelper.getDialect(jdbcTemplate);", "score": 0.8326021432876587 } ]
java
toStr(methodInfo.getActionInfo().getBatchSql()));
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize());
methodInfo.resolveSql(sql);
} catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if (methodInfo.getActionInfo().isReturnIsList()) { if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/PostgreSqlDialect.java", "retrieved_chunk": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.github.deeround.jdbc.plus.Interceptor.pagination.dialect;\n/**\n * @author liuzh\n */\npublic class PostgreSqlDialect extends AbstractDialect {\n @Override\n public String getPageSql(String sql, int pageNum, int pageSize) {", "score": 0.8635735511779785 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Dialect.java", "retrieved_chunk": " * @param sql 绑定 SQL 对象\n * @param pageNum\n * @param pageSize\n * @return\n */\n String getPageSql(String sql, int pageNum, int pageSize);\n}", "score": 0.8594120740890503 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Dialect.java", "retrieved_chunk": " /**\n * 生成 count 查询 sql\n *\n * @param sql 绑定 SQL 对象\n * @return\n */\n String getCountSql(String sql);\n /**\n * 生成分页查询 sql\n *", "score": 0.8589860200881958 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/SqlServerDialect.java", "retrieved_chunk": " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\npackage com.github.deeround.jdbc.plus.Interceptor.pagination.dialect;\n/**\n * @author liuzh\n */\npublic class SqlServerDialect extends AbstractDialect {\n @Override\n public String getPageSql(String sql, int pageNum, int pageSize) {", "score": 0.8505091071128845 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/dialect/OracleDialect.java", "retrieved_chunk": " return \"SELECT * FROM ( SELECT PG_TB.*, ROWNUM PG_ROWNUM FROM ( \" + sql + \" ) PG_TB ) PG_TB1 WHERE PG_ROWNUM <= \" + (pageNum * pageSize) + \" AND PG_ROWNUM > \" + ((pageNum - 1) * pageSize) + \" \";\n }\n}", "score": 0.8501373529434204 } ]
java
methodInfo.resolveSql(sql);
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.handler.TenantLineHandler; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import com.github.deeround.jdbc.plus.util.CollectionUtils; import com.github.deeround.jdbc.plus.util.ExceptionUtils; import com.github.deeround.jdbc.plus.util.StringPool; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.update.Update; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * @author hubin * @since 3.4.0 */ public class TenantLineInterceptor extends BaseMultiTableInterceptor implements IInterceptor { private final TenantLineHandler tenantLineHandler; public TenantLineInterceptor(TenantLineHandler tenantLineHandler) { this.tenantLineHandler = tenantLineHandler; } @Override public boolean supportMethod(MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) { for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) { methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null)); } } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { return result; } @Override protected void processSelect(Select select, int index, String sql, Object obj) { final String whereSegment = (String) obj; this.processSelectBody(select.getSelectBody(), whereSegment); List<WithItem> withItemsList = select.getWithItemsList(); if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(withItem -> this.processSelectBody(withItem, whereSegment)); } } @Override protected void processInsert(Insert insert, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(insert.getTable().getName())) { // 过滤退出执行 return; } List<Column> columns = insert.getColumns(); if (CollectionUtils.isEmpty(columns)) { // 针对不给列名的insert 不处理 return; } String tenantIdColumn = this.tenantLineHandler.getTenantIdColumn(); if (this.tenantLineHandler.ignoreInsert(columns, tenantIdColumn)) { // 针对已给出租户列的insert 不处理 return; } columns.add(new Column(tenantIdColumn)); // fixed gitee pulls/141 duplicate update List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList(); if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { EqualsTo equalsTo = new EqualsTo(); equalsTo.setLeftExpression(new StringValue(tenantIdColumn));
equalsTo.setRightExpression(this.tenantLineHandler.getTenantId());
duplicateUpdateColumns.add(equalsTo); } Select select = insert.getSelect(); if (select != null) { this.processInsertSelect(select.getSelectBody(), (String) obj); } else if (insert.getItemsList() != null) { // fixed github pull/295 ItemsList itemsList = insert.getItemsList(); Expression tenantId = this.tenantLineHandler.getTenantId(); if (itemsList instanceof MultiExpressionList) { ((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(tenantId)); } else { ((ExpressionList) itemsList).getExpressions().add(tenantId); } } else { throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); } } /** * update 语句处理 */ @Override protected void processUpdate(Update update, int index, String sql, Object obj) { final Table table = update.getTable(); if (this.tenantLineHandler.ignoreTable(table.getName())) { // 过滤退出执行 return; } update.setWhere(this.andExpression(table, update.getWhere(), (String) obj)); } /** * delete 语句处理 */ @Override protected void processDelete(Delete delete, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(delete.getTable().getName())) { // 过滤退出执行 return; } delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj)); } /** * 处理 insert into select * <p> * 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了 * * @param selectBody SelectBody */ protected void processInsertSelect(SelectBody selectBody, final String whereSegment) { PlainSelect plainSelect = (PlainSelect) selectBody; FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof Table) { // fixed gitee pulls/141 duplicate update this.processPlainSelect(plainSelect, whereSegment); this.appendSelectItem(plainSelect.getSelectItems()); } else if (fromItem instanceof SubSelect) { SubSelect subSelect = (SubSelect) fromItem; this.appendSelectItem(plainSelect.getSelectItems()); this.processInsertSelect(subSelect.getSelectBody(), whereSegment); } } /** * 追加 SelectItem * * @param selectItems SelectItem */ protected void appendSelectItem(List<SelectItem> selectItems) { if (CollectionUtils.isEmpty(selectItems)) { return; } if (selectItems.size() == 1) { SelectItem item = selectItems.get(0); if (item instanceof AllColumns || item instanceof AllTableColumns) { return; } } selectItems.add(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn()))); } /** * 租户字段别名设置 * <p>tenantId 或 tableAlias.tenantId</p> * * @param table 表对象 * @return 字段 */ protected Column getAliasColumn(Table table) { StringBuilder column = new StringBuilder(); // todo 该起别名就要起别名,禁止修改此处逻辑 if (table.getAlias() != null) { column.append(table.getAlias().getName()).append(StringPool.DOT); } column.append(this.tenantLineHandler.getTenantIdColumn()); return new Column(column.toString()); } /** * 构建租户条件表达式 * * @param table 表对象 * @param where 当前where条件 * @param whereSegment 所属Mapper对象全路径(在原租户拦截器功能中,这个参数并不需要参与相关判断) * @return 租户条件表达式 * @see BaseMultiTableInterceptor#buildTableExpression(Table, Expression, String) */ @Override public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) { if (this.tenantLineHandler.ignoreTable(table.getName())) { return null; } return new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/handler/TenantLineHandler.java", "retrieved_chunk": " */\n default boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {\n return columns.stream().map(Column::getColumnName).anyMatch(i -> i.equalsIgnoreCase(tenantIdColumn));\n }\n}", "score": 0.8697292804718018 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/JdbcPlusConfig.java", "retrieved_chunk": " public Expression getTenantId() {\n String currentTenantId = \"test_tenant_4\";//可以从请求上下文中获取(cookie、session、header等)\n return new StringValue(currentTenantId);\n }\n /**\n * 租户字段名\n */\n @Override\n public String getTenantIdColumn() {\n return \"tenant_id\";", "score": 0.8474079370498657 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MybatisPlusConfiguration.java", "retrieved_chunk": " return new StringValue(currentTenantId);\n }\n /**\n * 租户字段名\n */\n @Override\n public String getTenantIdColumn() {\n return \"tenant_id\";\n }\n /**", "score": 0.836707353591919 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/JdbcPlusConfig.java", "retrieved_chunk": " }\n /**\n * 根据表名判断是否忽略拼接多租户条件\n */\n @Override\n public boolean ignoreTable(String tableName) {\n return TenantLineHandler.super.ignoreTable(tableName);\n }\n });\n }", "score": 0.8352439403533936 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/handler/TenantLineHandler.java", "retrieved_chunk": " */\n default boolean ignoreTable(String tableName) {\n return false;\n }\n /**\n * 忽略插入租户字段逻辑\n *\n * @param columns 插入字段\n * @param tenantIdColumn 租户 ID 字段\n * @return", "score": 0.8349615335464478 } ]
java
equalsTo.setRightExpression(this.tenantLineHandler.getTenantId());
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * The data type for Maps. Keys in a map are not allowed to have {@code null} * values. */ public final class MapType extends DataType { private final DataType keyType; private final DataType valueType; private final boolean valueContainsNull; /* * @param keyType the data type of map keys * * @param valueType the data type of map values * * @param valueContainsNull indicates if map values have {@code null} values */ public MapType(DataType keyType, DataType valueType, boolean valueContainsNull) { this.keyType = keyType; this.valueType = valueType; this.valueContainsNull = valueContainsNull; } /* * @return the data type of map keys */ public DataType getKeyType() { return keyType; } /* * @return the data type of map values */ public DataType getValueType() { return valueType; } /* * @return {@code true} if this map has null values, else {@code false} */ public boolean valueContainsNull() { return valueContainsNull; } /* * Builds a readable {@code String} representation of this {@code MapType}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(
String.format("%s-- key: %s\n", prefix, keyType.getTypeName()));
DataType.buildFormattedString(keyType, nextPrefix, builder); builder.append(String.format("%s-- value: %s (valueContainsNull = %b)\n", prefix, valueType.getTypeName(), valueContainsNull)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MapType mapType = (MapType) o; return valueContainsNull == mapType.valueContainsNull && Objects.equals(keyType, mapType.keyType) && Objects.equals(valueType, mapType.valueType); } @Override public int hashCode() { return Objects.hash(keyType, valueType, valueContainsNull); } }
server/src/main/java/io/delta/store/internal/types/MapType.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t */\n\tpublic boolean containsNull() {\n\t\treturn containsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code ArrayType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- element: %s (containsNull = %b)\\n\", prefix, elementType.getTypeName(),", "score": 0.912703812122345 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8533979654312134 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.850494384765625 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\t\tif (dataType instanceof StructType) {\n\t\t\t((StructType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t\tif (dataType instanceof MapType) {\n\t\t\t((MapType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)", "score": 0.828330397605896 }, { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t\t\t\tcontainsNull));\n\t\tDataType.buildFormattedString(elementType, nextPrefix, builder);\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (o == null || getClass() != o.getClass())\n\t\t\treturn false;\n\t\tArrayType arrayType = (ArrayType) o;", "score": 0.8270809650421143 } ]
java
String.format("%s-- key: %s\n", prefix, keyType.getTypeName()));
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * The data type for collections of multiple values. */ public final class ArrayType extends DataType { private final DataType elementType; private final boolean containsNull; /* * @param elementType the data type of values * * @param containsNull indicates if values have {@code null} value */ public ArrayType(DataType elementType, boolean containsNull) { this.elementType = elementType; this.containsNull = containsNull; } /* * @return the type of array elements */ public DataType getElementType() { return elementType; } /* * @return {@code true} if the array has {@code null} values, else {@code false} */ public boolean containsNull() { return containsNull; } /* * Builds a readable {@code String} representation of this {@code ArrayType}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String.format("%s-- element: %s (containsNull = %b)\n", prefix, elementType.getTypeName(), containsNull));
DataType.buildFormattedString(elementType, nextPrefix, builder);
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArrayType arrayType = (ArrayType) o; return containsNull == arrayType.containsNull && Objects.equals(elementType, arrayType.elementType); } @Override public int hashCode() { return Objects.hash(elementType, containsNull); } }
server/src/main/java/io/delta/store/internal/types/ArrayType.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/MapType.java", "retrieved_chunk": "\t * @return {@code true} if this map has null values, else {@code false}\n\t */\n\tpublic boolean valueContainsNull() {\n\t\treturn valueContainsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code MapType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";", "score": 0.902397871017456 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.8978767395019531 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8838343620300293 }, { "filename": "server/src/main/java/io/delta/store/internal/types/MapType.java", "retrieved_chunk": "\t\tbuilder.append(String.format(\"%s-- key: %s\\n\", prefix, keyType.getTypeName()));\n\t\tDataType.buildFormattedString(keyType, nextPrefix, builder);\n\t\tbuilder.append(String.format(\"%s-- value: %s (valueContainsNull = %b)\\n\", prefix, valueType.getTypeName(),\n\t\t\t\tvalueContainsNull));\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (o == null || getClass() != o.getClass())", "score": 0.8688111305236816 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t}\n\t/*\n\t * @return a readable indented tree representation of this {@code StructType}\n\t * and all of its nested elements\n\t */\n\tpublic String getTreeString() {\n\t\tfinal String prefix = \" |\";\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"root\\n\");\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));", "score": 0.8393799066543579 } ]
java
DataType.buildFormattedString(elementType, nextPrefix, builder);
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.handler.TenantLineHandler; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import com.github.deeround.jdbc.plus.util.CollectionUtils; import com.github.deeround.jdbc.plus.util.ExceptionUtils; import com.github.deeround.jdbc.plus.util.StringPool; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.update.Update; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * @author hubin * @since 3.4.0 */ public class TenantLineInterceptor extends BaseMultiTableInterceptor implements IInterceptor { private final TenantLineHandler tenantLineHandler; public TenantLineInterceptor(TenantLineHandler tenantLineHandler) { this.tenantLineHandler = tenantLineHandler; } @Override public boolean supportMethod(MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) { for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) { methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null)); } } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { return result; } @Override protected void processSelect(Select select, int index, String sql, Object obj) { final String whereSegment = (String) obj; this.processSelectBody(select.getSelectBody(), whereSegment); List<WithItem> withItemsList = select.getWithItemsList(); if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(withItem -> this.processSelectBody(withItem, whereSegment)); } } @Override protected void processInsert(Insert insert, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(insert.getTable().getName())) { // 过滤退出执行 return; } List<Column> columns = insert.getColumns(); if (CollectionUtils.isEmpty(columns)) { // 针对不给列名的insert 不处理 return; } String tenantIdColumn = this.tenantLineHandler.getTenantIdColumn(); if (this.tenantLineHandler.ignoreInsert(columns, tenantIdColumn)) { // 针对已给出租户列的insert 不处理 return; } columns.add(new Column(tenantIdColumn)); // fixed gitee pulls/141 duplicate update List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList(); if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { EqualsTo equalsTo = new EqualsTo(); equalsTo.setLeftExpression(new StringValue(tenantIdColumn)); equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); duplicateUpdateColumns.add(equalsTo); } Select select = insert.getSelect(); if (select != null) { this.processInsertSelect(select.getSelectBody(), (String) obj); } else if (insert.getItemsList() != null) { // fixed github pull/295 ItemsList itemsList = insert.getItemsList(); Expression tenantId = this.tenantLineHandler.getTenantId(); if (itemsList instanceof MultiExpressionList) { ((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(tenantId)); } else { ((ExpressionList) itemsList).getExpressions().add(tenantId); } } else { throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); } } /** * update 语句处理 */ @Override protected void processUpdate(Update update, int index, String sql, Object obj) { final Table table = update.getTable(); if (this.tenantLineHandler.ignoreTable(table.getName())) { // 过滤退出执行 return; } update.setWhere(this.andExpression(table, update.getWhere(), (String) obj)); } /** * delete 语句处理 */ @Override protected void processDelete(Delete delete, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(delete.getTable().getName())) { // 过滤退出执行 return; } delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj)); } /** * 处理 insert into select * <p> * 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了 * * @param selectBody SelectBody */ protected void processInsertSelect(SelectBody selectBody, final String whereSegment) { PlainSelect plainSelect = (PlainSelect) selectBody; FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof Table) { // fixed gitee pulls/141 duplicate update this.processPlainSelect(plainSelect, whereSegment); this.appendSelectItem(plainSelect.getSelectItems()); } else if (fromItem instanceof SubSelect) { SubSelect subSelect = (SubSelect) fromItem; this.appendSelectItem(plainSelect.getSelectItems()); this.processInsertSelect(subSelect.getSelectBody(), whereSegment); } } /** * 追加 SelectItem * * @param selectItems SelectItem */ protected void appendSelectItem(List<SelectItem> selectItems) { if (CollectionUtils.isEmpty(selectItems)) { return; } if (selectItems.size() == 1) { SelectItem item = selectItems.get(0); if (item instanceof AllColumns || item instanceof AllTableColumns) { return; } } selectItems.add(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn()))); } /** * 租户字段别名设置 * <p>tenantId 或 tableAlias.tenantId</p> * * @param table 表对象 * @return 字段 */ protected Column getAliasColumn(Table table) { StringBuilder column = new StringBuilder(); // todo 该起别名就要起别名,禁止修改此处逻辑 if (table.getAlias() != null) { column.append(table.getAlias().getName()).append(StringPool.DOT); } column.append(this.tenantLineHandler.getTenantIdColumn()); return new Column(column.toString()); } /** * 构建租户条件表达式 * * @param table 表对象 * @param where 当前where条件 * @param whereSegment 所属Mapper对象全路径(在原租户拦截器功能中,这个参数并不需要参与相关判断) * @return 租户条件表达式 * @see BaseMultiTableInterceptor#buildTableExpression(Table, Expression, String) */ @Override public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) { if (this.tenantLineHandler.ignoreTable(table.getName())) { return null; } return
new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId());
} }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " public abstract Expression buildTableExpression(final Table table, final Expression where, final String whereSegment);\n}", "score": 0.8642805814743042 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " */\n protected Expression builderExpression(Expression currentExpression, List<Table> tables, final String whereSegment) {\n // 没有表需要处理直接返回\n if (CollectionUtils.isEmpty(tables)) {\n return currentExpression;\n }\n // 构造每张表的条件\n List<Expression> expressions = tables.stream()\n .map(item -> this.buildTableExpression(item, currentExpression, whereSegment))\n .filter(Objects::nonNull)", "score": 0.8522460460662842 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " }\n }\n }\n /**\n * delete update 语句 where 处理\n */\n protected Expression andExpression(Table table, Expression where, final String whereSegment) {\n //获得where条件表达式\n final Expression expression = this.buildTableExpression(table, where, whereSegment);\n if (expression == null) {", "score": 0.8511620163917542 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/JdbcPlusConfig.java", "retrieved_chunk": " }\n /**\n * 根据表名判断是否忽略拼接多租户条件\n */\n @Override\n public boolean ignoreTable(String tableName) {\n return TenantLineHandler.super.ignoreTable(tableName);\n }\n });\n }", "score": 0.846652090549469 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": "import net.sf.jsqlparser.expression.operators.conditional.OrExpression;\nimport net.sf.jsqlparser.expression.operators.relational.ExistsExpression;\nimport net.sf.jsqlparser.expression.operators.relational.ExpressionList;\nimport net.sf.jsqlparser.expression.operators.relational.InExpression;\nimport net.sf.jsqlparser.schema.Table;\nimport net.sf.jsqlparser.statement.select.*;\nimport java.util.*;\nimport java.util.stream.Collectors;\n/**\n * 多表条件处理基对象,从原有的 {@link TenantLineInterceptor} 拦截器中提取出来", "score": 0.8352937698364258 } ]
java
new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId());
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * A field inside a {@link StructType}. */ public final class StructField { private final String name; private final DataType dataType; private final boolean nullable; private final FieldMetadata metadata; /* * Constructor with default {@code nullable = true}. * * @param name the name of this field * * @param dataType the data type of this field */ public StructField(String name, DataType dataType) { this(name, dataType, true); } /* * @param name the name of this field * * @param dataType the data type of this field * * @param nullable indicates if values of this field can be {@code null} values */ public StructField(String name, DataType dataType, boolean nullable) { this(name, dataType, nullable, FieldMetadata.builder().build()); } /* * @param name the name of this field * * @param dataType the data type of this field * * @param nullable indicates if values of this field can be {@code null} values * * @param metadata metadata for this field */ public StructField(String name, DataType dataType, boolean nullable, FieldMetadata metadata) { this.name = name; this.dataType = dataType; this.nullable = nullable; this.metadata = metadata; } /* * @return the name of this field */ public String getName() { return name; } /* * @return the data type of this field */ public DataType getDataType() { return dataType; } /* * @return whether this field allows to have a {@code null} value. */ public boolean isNullable() { return nullable; } /* * @return the metadata for this field */ public FieldMetadata getMetadata() { return metadata; } /* * Builds a readable {@code String} representation of this {@code StructField}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String.format("%s-- %s: %s (nullable = %b) (metadata =%s)\n", prefix, name, dataType.getTypeName(), nullable, metadata.toString()));
DataType.buildFormattedString(dataType, nextPrefix, builder);
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StructField that = (StructField) o; return name.equals(that.name) && dataType.equals(that.dataType) && nullable == that.nullable && metadata.equals(that.metadata); } @Override public int hashCode() { return Objects.hash(name, dataType, nullable, metadata); } }
server/src/main/java/io/delta/store/internal/types/StructField.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8982818722724915 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.8759625554084778 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t}\n\t/*\n\t * @return a readable indented tree representation of this {@code StructType}\n\t * and all of its nested elements\n\t */\n\tpublic String getTreeString() {\n\t\tfinal String prefix = \" |\";\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"root\\n\");\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));", "score": 0.8604879379272461 }, { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t */\n\tpublic boolean containsNull() {\n\t\treturn containsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code ArrayType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- element: %s (containsNull = %b)\\n\", prefix, elementType.getTypeName(),", "score": 0.8435275554656982 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\t\tif (dataType instanceof StructType) {\n\t\t\t((StructType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t\tif (dataType instanceof MapType) {\n\t\t\t((MapType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)", "score": 0.8390016555786133 } ]
java
DataType.buildFormattedString(dataType, nextPrefix, builder);
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * The data type for Maps. Keys in a map are not allowed to have {@code null} * values. */ public final class MapType extends DataType { private final DataType keyType; private final DataType valueType; private final boolean valueContainsNull; /* * @param keyType the data type of map keys * * @param valueType the data type of map values * * @param valueContainsNull indicates if map values have {@code null} values */ public MapType(DataType keyType, DataType valueType, boolean valueContainsNull) { this.keyType = keyType; this.valueType = valueType; this.valueContainsNull = valueContainsNull; } /* * @return the data type of map keys */ public DataType getKeyType() { return keyType; } /* * @return the data type of map values */ public DataType getValueType() { return valueType; } /* * @return {@code true} if this map has null values, else {@code false} */ public boolean valueContainsNull() { return valueContainsNull; } /* * Builds a readable {@code String} representation of this {@code MapType}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String.format("%s-- key: %s\n", prefix, keyType.getTypeName())); DataType.buildFormattedString(keyType, nextPrefix, builder); builder.append(String.format("%s-- value: %s (valueContainsNull = %b)\n",
prefix, valueType.getTypeName(), valueContainsNull));
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MapType mapType = (MapType) o; return valueContainsNull == mapType.valueContainsNull && Objects.equals(keyType, mapType.keyType) && Objects.equals(valueType, mapType.valueType); } @Override public int hashCode() { return Objects.hash(keyType, valueType, valueContainsNull); } }
server/src/main/java/io/delta/store/internal/types/MapType.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.885852575302124 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8807766437530518 }, { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t */\n\tpublic boolean containsNull() {\n\t\treturn containsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code ArrayType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- element: %s (containsNull = %b)\\n\", prefix, elementType.getTypeName(),", "score": 0.8704879283905029 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t}\n\t/*\n\t * @return a readable indented tree representation of this {@code StructType}\n\t * and all of its nested elements\n\t */\n\tpublic String getTreeString() {\n\t\tfinal String prefix = \" |\";\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"root\\n\");\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));", "score": 0.8477091193199158 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\t\tif (dataType instanceof StructType) {\n\t\t\t((StructType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t\tif (dataType instanceof MapType) {\n\t\t\t((MapType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)", "score": 0.840341329574585 } ]
java
prefix, valueType.getTypeName(), valueContainsNull));
package me.dio.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import me.dio.exception.BusinessException; import me.dio.exception.NotFoundException; import me.dio.model.Hero; import me.dio.repository.HeroRepository; import me.dio.service.HeroService; @Service @Transactional public class HeroServiceImpl implements HeroService { @Autowired private HeroRepository heroRepository; @Transactional(readOnly = true) public List<Hero> findAll() { // DONE! Sort Heroes by "xp" descending. return this.heroRepository.findAll(Sort.by(Sort.Direction.DESC, "xp")); } @Transactional(readOnly = true) public Hero findById(Long id) { return this.heroRepository.findById(id).orElseThrow(NotFoundException::new); } public Hero create(Hero heroToCreate) { heroToCreate.setXp(0); return this.heroRepository.save(heroToCreate); } public Hero update(Long id, Hero heroToUpdate) { Hero dbHero = this.findById(id); if
(!dbHero.getId().equals(heroToUpdate.getId())) {
throw new BusinessException("Update IDs must be the same."); } // DONE! Make sure "xp" is not changed. In practice, only "name" can be changed. dbHero.setName(heroToUpdate.getName()); return this.heroRepository.save(dbHero); } public void delete(Long id) { Hero dbHero = this.findById(id); this.heroRepository.delete(dbHero); } public void increaseXp(Long id) { Hero dbHero = this.findById(id); dbHero.setXp(dbHero.getXp() + 2); heroRepository.save(dbHero); } }
src/main/java/me/dio/service/impl/HeroServiceImpl.java
digitalinnovationone-spring-boot-3-rest-api-template-55aab88
[ { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"404\", description = \"Hero not found\"),\n @ApiResponse(responseCode = \"422\", description = \"Invalid hero data provided\")\n })\n public ResponseEntity<Hero> update(@PathVariable Long id, @RequestBody Hero hero) {\n // TODO: Create a DTO to avoid expose unnecessary Hero model attributes.\n return ResponseEntity.ok(heroService.update(id, hero));\n }\n @DeleteMapping(\"/{id}\")\n @Operation(summary = \"Delete a hero\", description = \"Delete an existing hero based on its ID\")\n @ApiResponses(value = { ", "score": 0.8836327791213989 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " return ResponseEntity.ok(heroService.findAll());\n }\n @GetMapping(\"/{id}\")\n @Operation(summary = \"Get a hero by ID\", description = \"Get a specific hero based on its ID\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"200\", description = \"Successful operation\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Hero> findById(@PathVariable Long id) {\n return ResponseEntity.ok(heroService.findById(id));", "score": 0.8688788414001465 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n .path(\"/{id}\")\n .buildAndExpand(createdHero.getId())\n .toUri();\n return ResponseEntity.created(location).body(createdHero);\n }\n @PutMapping(\"/{id}\")\n @Operation(summary = \"Update a hero\", description = \"Update an existing hero based on its ID\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"200\", description = \"Hero updated successfully\"),", "score": 0.8651607036590576 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"204\", description = \"Hero deleted successfully\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Void> delete(@PathVariable Long id) {\n heroService.delete(id);\n return ResponseEntity.noContent().build();\n }\n @PatchMapping(\"/{id}/up\")\n @Operation(summary = \"Increase hero XP\", description = \"Up XP to an existing hero based on its ID\")\n @ApiResponses(value = { ", "score": 0.8627344369888306 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " }\n @PostMapping\n @Operation(summary = \"Create a new hero\", description = \"Create a new hero and returns the created hero\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"201\", description = \"Hero created successfully\"),\n @ApiResponse(responseCode = \"422\", description = \"Invalid hero data provided\")\n })\n public ResponseEntity<Hero> create(@RequestBody Hero hero) {\n // TODO: Create a DTO to avoid expose unnecessary Hero model attributes.\n Hero createdHero = heroService.create(hero);", "score": 0.8572235703468323 } ]
java
(!dbHero.getId().equals(heroToUpdate.getId())) {
package me.dio.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import me.dio.exception.BusinessException; import me.dio.exception.NotFoundException; import me.dio.model.Hero; import me.dio.repository.HeroRepository; import me.dio.service.HeroService; @Service @Transactional public class HeroServiceImpl implements HeroService { @Autowired private HeroRepository heroRepository; @Transactional(readOnly = true) public List<Hero> findAll() { // DONE! Sort Heroes by "xp" descending. return this.heroRepository.findAll(Sort.by(Sort.Direction.DESC, "xp")); } @Transactional(readOnly = true) public Hero findById(Long id) { return this.heroRepository.findById(id).orElseThrow(NotFoundException::new); } public Hero create(Hero heroToCreate) { heroToCreate.setXp(0); return this.heroRepository.save(heroToCreate); } public Hero update(Long id, Hero heroToUpdate) { Hero dbHero = this.findById(id); if (!dbHero.getId().equals(heroToUpdate.getId())) { throw new BusinessException("Update IDs must be the same."); } // DONE! Make sure "xp" is not changed. In practice, only "name" can be changed. dbHero.setName(heroToUpdate.getName()); return this.heroRepository.save(dbHero); } public void delete(Long id) { Hero dbHero = this.findById(id); this.heroRepository.delete(dbHero); } public void increaseXp(Long id) { Hero dbHero = this.findById(id); dbHero.setXp(
dbHero.getXp() + 2);
heroRepository.save(dbHero); } }
src/main/java/me/dio/service/impl/HeroServiceImpl.java
digitalinnovationone-spring-boot-3-rest-api-template-55aab88
[ { "filename": "src/main/java/me/dio/service/HeroService.java", "retrieved_chunk": "package me.dio.service;\nimport me.dio.model.Hero;\npublic interface HeroService extends CrudService<Long, Hero> {\n void increaseXp(Long id);\n}", "score": 0.883529543876648 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"204\", description = \"Hero deleted successfully\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Void> delete(@PathVariable Long id) {\n heroService.delete(id);\n return ResponseEntity.noContent().build();\n }\n @PatchMapping(\"/{id}/up\")\n @Operation(summary = \"Increase hero XP\", description = \"Up XP to an existing hero based on its ID\")\n @ApiResponses(value = { ", "score": 0.8831841945648193 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"204\", description = \"Vote registered successfully\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Void> vote(@PathVariable Long id) {\n heroService.increaseXp(id);\n return ResponseEntity.noContent().build();\n }\n}", "score": 0.860479474067688 }, { "filename": "src/main/java/me/dio/model/Hero.java", "retrieved_chunk": " private Long id;\n private String name;\n private int xp;\n /*\n * The version field is marked with the @Version annotation. This means JPA will\n * automatically take care of versioning for the Hero entity, which helps\n * prevent concurrent modification conflicts.\n */\n @Version\n private int version;", "score": 0.8566926717758179 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " return ResponseEntity.ok(heroService.findAll());\n }\n @GetMapping(\"/{id}\")\n @Operation(summary = \"Get a hero by ID\", description = \"Get a specific hero based on its ID\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"200\", description = \"Successful operation\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Hero> findById(@PathVariable Long id) {\n return ResponseEntity.ok(heroService.findById(id));", "score": 0.8428294658660889 } ]
java
dbHero.getXp() + 2);
package me.dio.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import me.dio.exception.BusinessException; import me.dio.exception.NotFoundException; import me.dio.model.Hero; import me.dio.repository.HeroRepository; import me.dio.service.HeroService; @Service @Transactional public class HeroServiceImpl implements HeroService { @Autowired private HeroRepository heroRepository; @Transactional(readOnly = true) public List<Hero> findAll() { // DONE! Sort Heroes by "xp" descending. return this.heroRepository.findAll(Sort.by(Sort.Direction.DESC, "xp")); } @Transactional(readOnly = true) public Hero findById(Long id) { return this.heroRepository.findById(id).orElseThrow(NotFoundException::new); } public Hero create(Hero heroToCreate) { heroToCreate.setXp(0); return this.heroRepository.save(heroToCreate); } public Hero update(Long id, Hero heroToUpdate) { Hero dbHero = this.findById(id); if (!dbHero.getId(
).equals(heroToUpdate.getId())) {
throw new BusinessException("Update IDs must be the same."); } // DONE! Make sure "xp" is not changed. In practice, only "name" can be changed. dbHero.setName(heroToUpdate.getName()); return this.heroRepository.save(dbHero); } public void delete(Long id) { Hero dbHero = this.findById(id); this.heroRepository.delete(dbHero); } public void increaseXp(Long id) { Hero dbHero = this.findById(id); dbHero.setXp(dbHero.getXp() + 2); heroRepository.save(dbHero); } }
src/main/java/me/dio/service/impl/HeroServiceImpl.java
digitalinnovationone-spring-boot-3-rest-api-template-55aab88
[ { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"404\", description = \"Hero not found\"),\n @ApiResponse(responseCode = \"422\", description = \"Invalid hero data provided\")\n })\n public ResponseEntity<Hero> update(@PathVariable Long id, @RequestBody Hero hero) {\n // TODO: Create a DTO to avoid expose unnecessary Hero model attributes.\n return ResponseEntity.ok(heroService.update(id, hero));\n }\n @DeleteMapping(\"/{id}\")\n @Operation(summary = \"Delete a hero\", description = \"Delete an existing hero based on its ID\")\n @ApiResponses(value = { ", "score": 0.8820661902427673 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " return ResponseEntity.ok(heroService.findAll());\n }\n @GetMapping(\"/{id}\")\n @Operation(summary = \"Get a hero by ID\", description = \"Get a specific hero based on its ID\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"200\", description = \"Successful operation\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Hero> findById(@PathVariable Long id) {\n return ResponseEntity.ok(heroService.findById(id));", "score": 0.8632655739784241 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " URI location = ServletUriComponentsBuilder.fromCurrentRequest()\n .path(\"/{id}\")\n .buildAndExpand(createdHero.getId())\n .toUri();\n return ResponseEntity.created(location).body(createdHero);\n }\n @PutMapping(\"/{id}\")\n @Operation(summary = \"Update a hero\", description = \"Update an existing hero based on its ID\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"200\", description = \"Hero updated successfully\"),", "score": 0.8624880909919739 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " @ApiResponse(responseCode = \"204\", description = \"Hero deleted successfully\"),\n @ApiResponse(responseCode = \"404\", description = \"Hero not found\")\n })\n public ResponseEntity<Void> delete(@PathVariable Long id) {\n heroService.delete(id);\n return ResponseEntity.noContent().build();\n }\n @PatchMapping(\"/{id}/up\")\n @Operation(summary = \"Increase hero XP\", description = \"Up XP to an existing hero based on its ID\")\n @ApiResponses(value = { ", "score": 0.8586118221282959 }, { "filename": "src/main/java/me/dio/controller/HeroController.java", "retrieved_chunk": " }\n @PostMapping\n @Operation(summary = \"Create a new hero\", description = \"Create a new hero and returns the created hero\")\n @ApiResponses(value = { \n @ApiResponse(responseCode = \"201\", description = \"Hero created successfully\"),\n @ApiResponse(responseCode = \"422\", description = \"Invalid hero data provided\")\n })\n public ResponseEntity<Hero> create(@RequestBody Hero hero) {\n // TODO: Create a DTO to avoid expose unnecessary Hero model attributes.\n Hero createdHero = heroService.create(hero);", "score": 0.8557668328285217 } ]
java
).equals(heroToUpdate.getId())) {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * The data type for collections of multiple values. */ public final class ArrayType extends DataType { private final DataType elementType; private final boolean containsNull; /* * @param elementType the data type of values * * @param containsNull indicates if values have {@code null} value */ public ArrayType(DataType elementType, boolean containsNull) { this.elementType = elementType; this.containsNull = containsNull; } /* * @return the type of array elements */ public DataType getElementType() { return elementType; } /* * @return {@code true} if the array has {@code null} values, else {@code false} */ public boolean containsNull() { return containsNull; } /* * Builds a readable {@code String} representation of this {@code ArrayType}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String
.format("%s-- element: %s (containsNull = %b)\n", prefix, elementType.getTypeName(), containsNull));
DataType.buildFormattedString(elementType, nextPrefix, builder); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ArrayType arrayType = (ArrayType) o; return containsNull == arrayType.containsNull && Objects.equals(elementType, arrayType.elementType); } @Override public int hashCode() { return Objects.hash(elementType, containsNull); } }
server/src/main/java/io/delta/store/internal/types/ArrayType.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/MapType.java", "retrieved_chunk": "\t * @return {@code true} if this map has null values, else {@code false}\n\t */\n\tpublic boolean valueContainsNull() {\n\t\treturn valueContainsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code MapType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";", "score": 0.9117183089256287 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8873573541641235 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.8867475986480713 }, { "filename": "server/src/main/java/io/delta/store/internal/types/MapType.java", "retrieved_chunk": "\t\tbuilder.append(String.format(\"%s-- key: %s\\n\", prefix, keyType.getTypeName()));\n\t\tDataType.buildFormattedString(keyType, nextPrefix, builder);\n\t\tbuilder.append(String.format(\"%s-- value: %s (valueContainsNull = %b)\\n\", prefix, valueType.getTypeName(),\n\t\t\t\tvalueContainsNull));\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (o == null || getClass() != o.getClass())", "score": 0.8607568144798279 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructField.java", "retrieved_chunk": "\t */\n\tpublic FieldMetadata getMetadata() {\n\t\treturn metadata;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructField}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- %s: %s (nullable = %b) (metadata =%s)\\n\", prefix, name,", "score": 0.8382469415664673 } ]
java
.format("%s-- element: %s (containsNull = %b)\n", prefix, elementType.getTypeName(), containsNull));
package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.Interceptor.pagination.Dialect; import com.github.deeround.jdbc.plus.Interceptor.pagination.Page; import com.github.deeround.jdbc.plus.Interceptor.pagination.PageHelper; import com.github.deeround.jdbc.plus.method.MethodActionInfo; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.jdbc.core.ResultSetExtractor; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @author wanghao 913351190@qq.com * @create 2023/4/19 9:30 */ public class PaginationInterceptor implements IInterceptor { @Override public boolean supportMethod(final MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return; } try { MethodActionInfo actionInfo = methodInfo.getActionInfo(); Dialect dialect = PageHelper.getDialect(jdbcTemplate); String sql = actionInfo.getSql(); //查询汇总 if (localPage.isCount() && methodInfo.getActionInfo().isReturnIsList()) { if (actionInfo.isHasParameter()) { if (actionInfo.isParameterIsPss()) { Object cnt = jdbcTemplate.query(dialect.getCountSql(sql), (PreparedStatementSetter) methodInfo.getArgs()[actionInfo.getParameterIndex()], new ResultSetExtractor<Map>() { @Override public Map extractData(ResultSet rs) throws SQLException, DataAccessException { while (rs.next()) { Map<String, Object> map = new HashMap<>(); map.put("PG_COUNT", rs.getLong("PG_COUNT")); return map; } return new HashMap<>(); } }).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { if (actionInfo.isHasParameterType()) { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter(), actionInfo.getParameterType()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql), actionInfo.getParameter()).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } } else { Object cnt = jdbcTemplate.queryForMap(dialect.getCountSql(sql)).get("PG_COUNT"); localPage.setTotal(Long.parseLong(cnt.toString())); } } //生成分页SQL sql = dialect.getPageSql(sql, localPage.getPageNum(), localPage.getPageSize()); methodInfo.resolveSql(sql); } catch (Exception e) { PageHelper.clearPage(); throw e; } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { Page<Object> localPage = PageHelper.getLocalPage(); if (localPage == null) { return result; } try { if
(methodInfo.getActionInfo().isReturnIsList()) {
if (result != null) { localPage.addAll((Collection<?>) result); } return localPage; } else { return result; } } finally { PageHelper.clearPage(); } } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL结束时间:{}\", LocalDateTime.now());\n LocalDateTime startTime = (LocalDateTime) methodInfo.getUserAttribute(\"startTime\");\n log.info(\"执行SQL耗时:{}毫秒\", Duration.between(startTime, LocalDateTime.now()).toMillis());\n return result;\n }\n}", "score": 0.8946101665496826 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " if (this.interceptors != null && this.interceptors.size() > 0) {\n for (int i = this.interceptors.size() - 1; i >= 0; i--) {\n IInterceptor interceptor = this.interceptors.get(i);\n if (interceptor.supportMethod(methodInfo)) {\n result = interceptor.beforeFinish(result, methodInfo, jdbcTemplate);\n }\n }\n }\n log.debug(\"finish result==>{}\", result);\n return result;", "score": 0.8859230875968933 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java", "retrieved_chunk": " }\n }\n }\n @Override\n public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n return result;\n }\n @Override\n protected void processSelect(Select select, int index, String sql, Object obj) {\n final String whereSegment = (String) obj;", "score": 0.8640558123588562 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " methodInvocation.setArguments(methodInfo.getArgs());\n }\n }\n }\n }\n log.debug(\"finish sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"finish parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n Object result = methodInvocation.proceed();\n log.debug(\"origin result==>{}\", result);\n //逻辑处理", "score": 0.8494122624397278 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " log.info(\"调用方法名称:{}\", methodInfo.getName());\n log.info(\"调用方法入参:{}\", Arrays.toString(methodInfo.getArgs()));\n methodInfo.putUserAttribute(\"startTime\", LocalDateTime.now());\n }\n /**\n * SQL执行完成后方法(主要用于对返回值修改)\n *\n * @param result 原始返回对象\n * @return 处理后的返回对象\n */", "score": 0.8492851257324219 } ]
java
(methodInfo.getActionInfo().isReturnIsList()) {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * A field inside a {@link StructType}. */ public final class StructField { private final String name; private final DataType dataType; private final boolean nullable; private final FieldMetadata metadata; /* * Constructor with default {@code nullable = true}. * * @param name the name of this field * * @param dataType the data type of this field */ public StructField(String name, DataType dataType) { this(name, dataType, true); } /* * @param name the name of this field * * @param dataType the data type of this field * * @param nullable indicates if values of this field can be {@code null} values */ public StructField(String name, DataType dataType, boolean nullable) { this(name, dataType, nullable, FieldMetadata.builder().build()); } /* * @param name the name of this field * * @param dataType the data type of this field * * @param nullable indicates if values of this field can be {@code null} values * * @param metadata metadata for this field */ public StructField(String name, DataType dataType, boolean nullable, FieldMetadata metadata) { this.name = name; this.dataType = dataType; this.nullable = nullable; this.metadata = metadata; } /* * @return the name of this field */ public String getName() { return name; } /* * @return the data type of this field */ public DataType getDataType() { return dataType; } /* * @return whether this field allows to have a {@code null} value. */ public boolean isNullable() { return nullable; } /* * @return the metadata for this field */ public FieldMetadata getMetadata() { return metadata; } /* * Builds a readable {@code String} representation of this {@code StructField}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String.format("%s-- %s: %s (nullable = %b) (metadata =%s)\n", prefix, name,
dataType.getTypeName(), nullable, metadata.toString()));
DataType.buildFormattedString(dataType, nextPrefix, builder); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StructField that = (StructField) o; return name.equals(that.name) && dataType.equals(that.dataType) && nullable == that.nullable && metadata.equals(that.metadata); } @Override public int hashCode() { return Objects.hash(name, dataType, nullable, metadata); } }
server/src/main/java/io/delta/store/internal/types/StructField.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8925068378448486 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t}\n\t/*\n\t * @return a readable indented tree representation of this {@code StructType}\n\t * and all of its nested elements\n\t */\n\tpublic String getTreeString() {\n\t\tfinal String prefix = \" |\";\n\t\tStringBuilder builder = new StringBuilder();\n\t\tbuilder.append(\"root\\n\");\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));", "score": 0.8629298210144043 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.8551291227340698 }, { "filename": "server/src/main/java/io/delta/store/internal/types/FieldMetadata.java", "retrieved_chunk": "import java.util.stream.Collectors;\n/*\n * The metadata for a given {@link StructField}.\n */\npublic final class FieldMetadata {\n\tprivate final Map<String, Object> metadata;\n\tprivate FieldMetadata(Map<String, Object> metadata) {\n\t\tthis.metadata = metadata;\n\t}\n\t/*", "score": 0.8337613344192505 }, { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t */\n\tpublic boolean containsNull() {\n\t\treturn containsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code ArrayType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- element: %s (containsNull = %b)\\n\", prefix, elementType.getTypeName(),", "score": 0.8286975622177124 } ]
java
dataType.getTypeName(), nullable, metadata.toString()));
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This file contains code from the Apache Spark project (original license above). * It contains modifications, which are licensed as follows: */ /* * Copyright (2020-present) The Delta Lake Project Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.delta.store.internal.types; import java.util.Objects; /* * The data type for Maps. Keys in a map are not allowed to have {@code null} * values. */ public final class MapType extends DataType { private final DataType keyType; private final DataType valueType; private final boolean valueContainsNull; /* * @param keyType the data type of map keys * * @param valueType the data type of map values * * @param valueContainsNull indicates if map values have {@code null} values */ public MapType(DataType keyType, DataType valueType, boolean valueContainsNull) { this.keyType = keyType; this.valueType = valueType; this.valueContainsNull = valueContainsNull; } /* * @return the data type of map keys */ public DataType getKeyType() { return keyType; } /* * @return the data type of map values */ public DataType getValueType() { return valueType; } /* * @return {@code true} if this map has null values, else {@code false} */ public boolean valueContainsNull() { return valueContainsNull; } /* * Builds a readable {@code String} representation of this {@code MapType}. */ protected void buildFormattedString(String prefix, StringBuilder builder) { final String nextPrefix = prefix + " |"; builder.append(String.format("%s-- key: %s\n", prefix, keyType.getTypeName()));
DataType.buildFormattedString(keyType, nextPrefix, builder);
builder.append(String.format("%s-- value: %s (valueContainsNull = %b)\n", prefix, valueType.getTypeName(), valueContainsNull)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MapType mapType = (MapType) o; return valueContainsNull == mapType.valueContainsNull && Objects.equals(keyType, mapType.keyType) && Objects.equals(valueType, mapType.valueType); } @Override public int hashCode() { return Objects.hash(keyType, valueType, valueContainsNull); } }
server/src/main/java/io/delta/store/internal/types/MapType.java
dataplatform-lab-deltastore-017c850
[ { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t */\n\tpublic boolean containsNull() {\n\t\treturn containsNull;\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code ArrayType}.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tfinal String nextPrefix = prefix + \" |\";\n\t\tbuilder.append(String.format(\"%s-- element: %s (containsNull = %b)\\n\", prefix, elementType.getTypeName(),", "score": 0.9069440960884094 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\tpublic String toPrettyJson() {\n\t\treturn DataTypeParser.toPrettyJson(this);\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of the {@code ArrayType}\n\t */\n\tprotected static void buildFormattedString(DataType dataType, String prefix, StringBuilder builder) {\n\t\tif (dataType instanceof ArrayType) {\n\t\t\t((ArrayType) dataType).buildFormattedString(prefix, builder);\n\t\t}", "score": 0.8569920659065247 }, { "filename": "server/src/main/java/io/delta/store/internal/types/StructType.java", "retrieved_chunk": "\t\treturn builder.toString();\n\t}\n\t/*\n\t * Builds a readable {@code String} representation of this {@code StructType}\n\t * and all of its nested elements.\n\t */\n\tprotected void buildFormattedString(String prefix, StringBuilder builder) {\n\t\tArrays.stream(fields).forEach(field -> field.buildFormattedString(prefix, builder));\n\t}\n\t@Override", "score": 0.8496569395065308 }, { "filename": "server/src/main/java/io/delta/store/internal/types/DataType.java", "retrieved_chunk": "\t\tif (dataType instanceof StructType) {\n\t\t\t((StructType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t\tif (dataType instanceof MapType) {\n\t\t\t((MapType) dataType).buildFormattedString(prefix, builder);\n\t\t}\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)", "score": 0.8372290134429932 }, { "filename": "server/src/main/java/io/delta/store/internal/types/ArrayType.java", "retrieved_chunk": "\t\t\t\tcontainsNull));\n\t\tDataType.buildFormattedString(elementType, nextPrefix, builder);\n\t}\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (o == null || getClass() != o.getClass())\n\t\t\treturn false;\n\t\tArrayType arrayType = (ArrayType) o;", "score": 0.8294787406921387 } ]
java
DataType.buildFormattedString(keyType, nextPrefix, builder);
package raven.toast.ui; import static com.formdev.flatlaf.FlatClientProperties.*; import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.ui.FlatStylingSupport; import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI; import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.LoggingFacade; import com.formdev.flatlaf.util.UIScale; import static raven.toast.ToastClientProperties.*; import raven.toast.util.UIUtils; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicPanelUI; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.function.Consumer; public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener { protected JComponent iconComponent; protected JComponent component; protected JComponent closeButton; @Styleable protected int iconTextGap; @Styleable protected int closeButtonGap; @Styleable protected int minimumWidth; @Styleable protected int maximumWidth; @Styleable protected int arc; @Styleable protected int outlineWidth; @Styleable protected Color outlineColor; @Styleable protected boolean showCloseButton; @Styleable protected Color closeIconColor; @Styleable protected Insets margin; @Styleable protected Icon closeButtonIcon; @Styleable protected boolean useEffect; @Styleable protected Color effectColor; @Styleable protected float effectWidth; @Styleable protected float effectOpacity; @Styleable protected String effectAlignment; private PanelNotificationLayout layout; private Map<String, Object> oldStyleValues; @Override public void installUI(JComponent c) { super.installUI(c); c.addPropertyChangeListener(this); installIconComponent(c); installComponent(c); installCloseButton(c); installStyle((JPanel) c); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removePropertyChangeListener(this); uninstallIconComponent(c); uninstallComponent(c); uninstallCloseButton(c); } @Override protected void installDefaults(JPanel p) { super.installDefaults(p); String prefix = getPropertyPrefix(); iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5); closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5); minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50); maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1); arc = FlatUIUtils.getUIInt(prefix + ".arc", 20); outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0); outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor"); margin = UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8)); showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true); closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150)); closeButtonIcon = UIUtils.getIcon(prefix + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true); effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor"); effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f); effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f); effectAlignment = UIUtils.getString(prefix + ".effectAlignment", "left"); p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background")); p.setBorder(createDefaultBorder()); LookAndFeel.installProperty(p, "opaque", false); } @Override protected void uninstallDefaults(JPanel p) { super.uninstallDefaults(p); oldStyleValues = null; } protected Border createDefaultBorder() { Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0));
Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6));
float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f); return new DropShadowBorder(color, insets, shadowOpacity); } protected String getPropertyPrefix() { return "Toast"; } @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case TOAST_ICON: { JPanel c = (JPanel) e.getSource(); uninstallIconComponent(c); installIconComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_COMPONENT: { JPanel c = (JPanel) e.getSource(); uninstallComponent(c); installComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_SHOW_CLOSE_BUTTON: { JPanel c = (JPanel) e.getSource(); uninstallCloseButton(c); installCloseButton(c); c.revalidate(); c.repaint(); break; } case STYLE: case STYLE_CLASS: { JPanel c = (JPanel) e.getSource(); installStyle(c); c.revalidate(); c.repaint(); break; } } } private void installIconComponent(JComponent c) { iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class); if (iconComponent != null) { installLayout(c); c.add(iconComponent); } } private void uninstallIconComponent(JComponent c) { if (iconComponent != null) { c.remove(iconComponent); iconComponent = null; } } private void installComponent(JComponent c) { component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class); if (component != null) { installLayout(c); c.add(component); } } private void uninstallComponent(JComponent c) { if (component != null) { c.remove(component); component = null; } } private void installCloseButton(JComponent c) { if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) { closeButton = createCloseButton(c); installLayout(c); c.add(closeButton); } } private void uninstallCloseButton(JComponent c) { if (closeButton != null) { c.remove(closeButton); closeButton = null; } } protected JComponent createCloseButton(JComponent c) { JButton button = new JButton(); button.setFocusable(false); button.setName("Toast.closeButton"); button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON); button.putClientProperty(STYLE, "" + "arc:999"); button.setIcon(closeButtonIcon); button.addActionListener(e -> closeButtonClicked(c)); return button; } protected void closeButtonClicked(JComponent c) { Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK); if (callback instanceof Runnable) { ((Runnable) callback).run(); } else if (callback instanceof Consumer) { ((Consumer) callback).accept(c); } } public void installLayout(JComponent c) { if (layout == null) { layout = new PanelNotificationLayout(); } c.setLayout(layout); } protected void installStyle(JPanel c) { try { applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel")); } catch (RuntimeException ex) { LoggingFacade.INSTANCE.logSevere(null, ex); } } protected void applyStyle(JPanel c, Object style) { boolean oldShowCloseButton = showCloseButton; oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value)); if (oldShowCloseButton != showCloseButton) { uninstallCloseButton(c); installCloseButton(c); } } protected Object applyStyleProperty(JPanel c, String key, Object value) { return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value); } @Override public Map<String, Class<?>> getStyleableInfos(JComponent c) { return FlatStylingSupport.getAnnotatedStyleableInfos(this); } @Override public Object getStyleableValue(JComponent c, String key) { return FlatStylingSupport.getAnnotatedStyleableValue(this, key); } protected class PanelNotificationLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int width = insets.left + insets.right; int height = 0; int gap = 0; int closeGap = 0; if (iconComponent != null) { width += iconComponent.getPreferredSize().width; height = Math.max(height, iconComponent.getPreferredSize().height); gap = UIScale.scale(iconTextGap); } if (component != null) { width += gap; width += component.getPreferredSize().width; height = Math.max(height, component.getPreferredSize().height); closeGap = UIScale.scale(closeButtonGap); } if (closeButton != null) { width += closeGap; width += closeButton.getPreferredSize().width; height = Math.max(height, closeButton.getPreferredSize().height); } height += (insets.top + insets.bottom); width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width)); return new Dimension(width, height); } } @Override public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return new Dimension(0, 0); } } private int getMaxWidth(int insets) { int width = Math.max(maximumWidth, minimumWidth) - insets; if (iconComponent != null) { width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap)); } if (closeButton != null) { width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width); } return width; } @Override public void layoutContainer(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int x = insets.left; int y = insets.top; int height = 0; if (iconComponent != null) { int iconW = iconComponent.getPreferredSize().width; int iconH = iconComponent.getPreferredSize().height; iconComponent.setBounds(x, y, iconW, iconH); x += iconW; height = iconH; } if (component != null) { int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right)); int cH = component.getPreferredSize().height; x += UIScale.scale(iconTextGap); component.setBounds(x, y, cW, cH); height = Math.max(height, cH); } if (closeButton != null) { int cW = closeButton.getPreferredSize().width; int cH = closeButton.getPreferredSize().height; int cX = parent.getWidth() - insets.right - cW; int cy = y + ((height - cH) / 2); closeButton.setBounds(cX, cy, cW, cH); } } } } }
src/main/java/raven/toast/ui/ToastPanelUI.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " protected JTextPane textPane;\n private Notifications.Type type;\n public ToastNotificationPanel() {\n installDefault();\n }\n private void installPropertyStyle() {\n String key = getKey();\n String outlineColor = toTextColor(getDefaultColor());\n String outline = convertsKey(key, \"outlineColor\", outlineColor);\n putClientProperty(FlatClientProperties.STYLE, \"\" +", "score": 0.8709558248519897 }, { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": " window = new JWindow(frame);\n window.setBackground(new Color(0, 0, 0, 0));\n window.setContentPane(component);\n window.setFocusableWindowState(false);\n window.setSize(component.getPreferredSize());\n }\n private void installDefault() {\n frameInsets = UIUtils.getInsets(\"Toast.frameInsets\", new Insets(10, 10, 10, 10));\n horizontalSpace = FlatUIUtils.getUIInt(\"Toast.horizontalGap\", 10);\n animationMove = FlatUIUtils.getUIInt(\"Toast.animationMove\", 10);", "score": 0.8647182583808899 }, { "filename": "src/main/java/raven/toast/ui/DropShadowBorder.java", "retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatPropertiesLaf;\nimport com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.util.ShadowRenderer;\nimport javax.swing.*;\nimport javax.swing.border.EmptyBorder;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;", "score": 0.8591247797012329 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " removeDialogBackground();\n }\n private void removeDialogBackground() {\n if (window != null) {\n Color bg = getBackground();\n window.setBackground(new Color(bg.getRed(), bg.getGreen(), bg.getBlue(), 0));\n window.setSize(getPreferredSize());\n }\n }\n private void installDefault() {", "score": 0.8556016683578491 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " this.type = type;\n labelIcon.setIcon(getDefaultIcon());\n textPane.setText(message);\n installPropertyStyle();\n }\n public void setDialog(JWindow window) {\n this.window = window;\n removeDialogBackground();\n }\n public Color getDefaultColor() {", "score": 0.8454313278198242 } ]
java
Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6));
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.handler.TenantLineHandler; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import com.github.deeround.jdbc.plus.util.CollectionUtils; import com.github.deeround.jdbc.plus.util.ExceptionUtils; import com.github.deeround.jdbc.plus.util.StringPool; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.update.Update; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * @author hubin * @since 3.4.0 */ public class TenantLineInterceptor extends BaseMultiTableInterceptor implements IInterceptor { private final TenantLineHandler tenantLineHandler; public TenantLineInterceptor(TenantLineHandler tenantLineHandler) { this.tenantLineHandler = tenantLineHandler; } @Override public boolean supportMethod(MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) { for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) { methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null)); } } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { return result; } @Override protected void processSelect(Select select, int index, String sql, Object obj) { final String whereSegment = (String) obj; this.processSelectBody(select.getSelectBody(), whereSegment); List<WithItem> withItemsList = select.getWithItemsList(); if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(withItem -> this.processSelectBody(withItem, whereSegment)); } } @Override protected void processInsert(Insert insert, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(insert.getTable().getName())) { // 过滤退出执行 return; } List<Column> columns = insert.getColumns(); if (CollectionUtils.isEmpty(columns)) { // 针对不给列名的insert 不处理 return; } String tenantIdColumn = this.tenantLineHandler.getTenantIdColumn(); if (this.tenantLineHandler.ignoreInsert(columns, tenantIdColumn)) { // 针对已给出租户列的insert 不处理 return; } columns.add(new Column(tenantIdColumn)); // fixed gitee pulls/141 duplicate update List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList(); if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { EqualsTo equalsTo = new EqualsTo(); equalsTo.setLeftExpression(new StringValue(tenantIdColumn)); equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); duplicateUpdateColumns.add(equalsTo); } Select select = insert.getSelect(); if (select != null) { this.processInsertSelect(select.getSelectBody(), (String) obj); } else if (insert.getItemsList() != null) { // fixed github pull/295 ItemsList itemsList = insert.getItemsList(); Expression tenantId = this.tenantLineHandler.getTenantId(); if (itemsList instanceof MultiExpressionList) { ((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(tenantId)); } else { ((ExpressionList) itemsList).getExpressions().add(tenantId); } } else { throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); } } /** * update 语句处理 */ @Override protected void processUpdate(Update update, int index, String sql, Object obj) { final Table table = update.getTable(); if (this.tenantLineHandler.ignoreTable(table.getName())) { // 过滤退出执行 return; } update.setWhere(this.andExpression(table, update.getWhere(), (String) obj)); } /** * delete 语句处理 */ @Override protected void processDelete(Delete delete, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(delete.getTable().getName())) { // 过滤退出执行 return; } delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj)); } /** * 处理 insert into select * <p> * 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了 * * @param selectBody SelectBody */ protected void processInsertSelect(SelectBody selectBody, final String whereSegment) { PlainSelect plainSelect = (PlainSelect) selectBody; FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof Table) { // fixed gitee pulls/141 duplicate update this.processPlainSelect(plainSelect, whereSegment); this.appendSelectItem(plainSelect.getSelectItems()); } else if (fromItem instanceof SubSelect) { SubSelect subSelect = (SubSelect) fromItem; this.appendSelectItem(plainSelect.getSelectItems()); this.processInsertSelect(subSelect.getSelectBody(), whereSegment); } } /** * 追加 SelectItem * * @param selectItems SelectItem */ protected void appendSelectItem(List<SelectItem> selectItems) { if (CollectionUtils.isEmpty(selectItems)) { return; } if (selectItems.size() == 1) { SelectItem item = selectItems.get(0); if (item instanceof AllColumns || item instanceof AllTableColumns) { return; } } selectItems.add
(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn())));
} /** * 租户字段别名设置 * <p>tenantId 或 tableAlias.tenantId</p> * * @param table 表对象 * @return 字段 */ protected Column getAliasColumn(Table table) { StringBuilder column = new StringBuilder(); // todo 该起别名就要起别名,禁止修改此处逻辑 if (table.getAlias() != null) { column.append(table.getAlias().getName()).append(StringPool.DOT); } column.append(this.tenantLineHandler.getTenantIdColumn()); return new Column(column.toString()); } /** * 构建租户条件表达式 * * @param table 表对象 * @param where 当前where条件 * @param whereSegment 所属Mapper对象全路径(在原租户拦截器功能中,这个参数并不需要参与相关判断) * @return 租户条件表达式 * @see BaseMultiTableInterceptor#buildTableExpression(Table, Expression, String) */ @Override public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) { if (this.tenantLineHandler.ignoreTable(table.getName())) { return null; } return new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " } else if (fromItem instanceof LateralSubSelect) {\n LateralSubSelect lateralSubSelect = (LateralSubSelect) fromItem;\n if (lateralSubSelect.getSubSelect() != null) {\n SubSelect subSelect = lateralSubSelect.getSubSelect();\n if (subSelect.getSelectBody() != null) {\n this.processSelectBody(subSelect.getSelectBody(), whereSegment);\n }\n }\n }\n }", "score": 0.8229526281356812 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " if (selectBody instanceof PlainSelect) {\n this.processPlainSelect((PlainSelect) selectBody, whereSegment);\n } else if (selectBody instanceof WithItem) {\n WithItem withItem = (WithItem) selectBody;\n this.processSelectBody(withItem.getSubSelect().getSelectBody(), whereSegment);\n } else {\n SetOperationList operationList = (SetOperationList) selectBody;\n List<SelectBody> selectBodyList = operationList.getSelects();\n if (CollectionUtils.isNotEmpty(selectBodyList)) {\n selectBodyList.forEach(body -> this.processSelectBody(body, whereSegment));", "score": 0.820782482624054 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " Parenthesis expression = (Parenthesis) where;\n this.processWhereSubSelect(expression.getExpression(), whereSegment);\n }\n }\n }\n protected void processSelectItem(SelectItem selectItem, final String whereSegment) {\n if (selectItem instanceof SelectExpressionItem) {\n SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem;\n final Expression expression = selectExpressionItem.getExpression();\n if (expression instanceof SubSelect) {", "score": 0.8156487941741943 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " while (fromItem instanceof ParenthesisFromItem) {\n fromItem = ((ParenthesisFromItem) fromItem).getFromItem();\n }\n if (fromItem instanceof SubSelect) {\n SubSelect subSelect = (SubSelect) fromItem;\n if (subSelect.getSelectBody() != null) {\n this.processSelectBody(subSelect.getSelectBody(), whereSegment);\n }\n } else if (fromItem instanceof ValuesList) {\n log.debug(\"Perform a subQuery, if you do not give us feedback\");", "score": 0.8103237152099609 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java", "retrieved_chunk": " // 处理 where 中的子查询\n Expression where = plainSelect.getWhere();\n this.processWhereSubSelect(where, whereSegment);\n // 处理 fromItem\n FromItem fromItem = plainSelect.getFromItem();\n List<Table> list = this.processFromItem(fromItem, whereSegment);\n List<Table> mainTables = new ArrayList<>(list);\n // 处理 join\n List<Join> joins = plainSelect.getJoins();\n if (CollectionUtils.isNotEmpty(joins)) {", "score": 0.8077811002731323 } ]
java
(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn())));
package raven.toast.ui; import static com.formdev.flatlaf.FlatClientProperties.*; import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.ui.FlatStylingSupport; import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI; import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.LoggingFacade; import com.formdev.flatlaf.util.UIScale; import static raven.toast.ToastClientProperties.*; import raven.toast.util.UIUtils; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicPanelUI; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.function.Consumer; public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener { protected JComponent iconComponent; protected JComponent component; protected JComponent closeButton; @Styleable protected int iconTextGap; @Styleable protected int closeButtonGap; @Styleable protected int minimumWidth; @Styleable protected int maximumWidth; @Styleable protected int arc; @Styleable protected int outlineWidth; @Styleable protected Color outlineColor; @Styleable protected boolean showCloseButton; @Styleable protected Color closeIconColor; @Styleable protected Insets margin; @Styleable protected Icon closeButtonIcon; @Styleable protected boolean useEffect; @Styleable protected Color effectColor; @Styleable protected float effectWidth; @Styleable protected float effectOpacity; @Styleable protected String effectAlignment; private PanelNotificationLayout layout; private Map<String, Object> oldStyleValues; @Override public void installUI(JComponent c) { super.installUI(c); c.addPropertyChangeListener(this); installIconComponent(c); installComponent(c); installCloseButton(c); installStyle((JPanel) c); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removePropertyChangeListener(this); uninstallIconComponent(c); uninstallComponent(c); uninstallCloseButton(c); } @Override protected void installDefaults(JPanel p) { super.installDefaults(p); String prefix = getPropertyPrefix(); iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5); closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5); minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50); maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1); arc = FlatUIUtils.getUIInt(prefix + ".arc", 20); outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0); outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor"); margin = UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8)); showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true); closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150)); closeButtonIcon = UIUtils.getIcon(prefix + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true); effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor"); effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f); effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f); effectAlignment =
UIUtils.getString(prefix + ".effectAlignment", "left");
p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background")); p.setBorder(createDefaultBorder()); LookAndFeel.installProperty(p, "opaque", false); } @Override protected void uninstallDefaults(JPanel p) { super.uninstallDefaults(p); oldStyleValues = null; } protected Border createDefaultBorder() { Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0)); Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6)); float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f); return new DropShadowBorder(color, insets, shadowOpacity); } protected String getPropertyPrefix() { return "Toast"; } @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case TOAST_ICON: { JPanel c = (JPanel) e.getSource(); uninstallIconComponent(c); installIconComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_COMPONENT: { JPanel c = (JPanel) e.getSource(); uninstallComponent(c); installComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_SHOW_CLOSE_BUTTON: { JPanel c = (JPanel) e.getSource(); uninstallCloseButton(c); installCloseButton(c); c.revalidate(); c.repaint(); break; } case STYLE: case STYLE_CLASS: { JPanel c = (JPanel) e.getSource(); installStyle(c); c.revalidate(); c.repaint(); break; } } } private void installIconComponent(JComponent c) { iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class); if (iconComponent != null) { installLayout(c); c.add(iconComponent); } } private void uninstallIconComponent(JComponent c) { if (iconComponent != null) { c.remove(iconComponent); iconComponent = null; } } private void installComponent(JComponent c) { component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class); if (component != null) { installLayout(c); c.add(component); } } private void uninstallComponent(JComponent c) { if (component != null) { c.remove(component); component = null; } } private void installCloseButton(JComponent c) { if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) { closeButton = createCloseButton(c); installLayout(c); c.add(closeButton); } } private void uninstallCloseButton(JComponent c) { if (closeButton != null) { c.remove(closeButton); closeButton = null; } } protected JComponent createCloseButton(JComponent c) { JButton button = new JButton(); button.setFocusable(false); button.setName("Toast.closeButton"); button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON); button.putClientProperty(STYLE, "" + "arc:999"); button.setIcon(closeButtonIcon); button.addActionListener(e -> closeButtonClicked(c)); return button; } protected void closeButtonClicked(JComponent c) { Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK); if (callback instanceof Runnable) { ((Runnable) callback).run(); } else if (callback instanceof Consumer) { ((Consumer) callback).accept(c); } } public void installLayout(JComponent c) { if (layout == null) { layout = new PanelNotificationLayout(); } c.setLayout(layout); } protected void installStyle(JPanel c) { try { applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel")); } catch (RuntimeException ex) { LoggingFacade.INSTANCE.logSevere(null, ex); } } protected void applyStyle(JPanel c, Object style) { boolean oldShowCloseButton = showCloseButton; oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value)); if (oldShowCloseButton != showCloseButton) { uninstallCloseButton(c); installCloseButton(c); } } protected Object applyStyleProperty(JPanel c, String key, Object value) { return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value); } @Override public Map<String, Class<?>> getStyleableInfos(JComponent c) { return FlatStylingSupport.getAnnotatedStyleableInfos(this); } @Override public Object getStyleableValue(JComponent c, String key) { return FlatStylingSupport.getAnnotatedStyleableValue(this, key); } protected class PanelNotificationLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int width = insets.left + insets.right; int height = 0; int gap = 0; int closeGap = 0; if (iconComponent != null) { width += iconComponent.getPreferredSize().width; height = Math.max(height, iconComponent.getPreferredSize().height); gap = UIScale.scale(iconTextGap); } if (component != null) { width += gap; width += component.getPreferredSize().width; height = Math.max(height, component.getPreferredSize().height); closeGap = UIScale.scale(closeButtonGap); } if (closeButton != null) { width += closeGap; width += closeButton.getPreferredSize().width; height = Math.max(height, closeButton.getPreferredSize().height); } height += (insets.top + insets.bottom); width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width)); return new Dimension(width, height); } } @Override public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return new Dimension(0, 0); } } private int getMaxWidth(int insets) { int width = Math.max(maximumWidth, minimumWidth) - insets; if (iconComponent != null) { width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap)); } if (closeButton != null) { width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width); } return width; } @Override public void layoutContainer(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int x = insets.left; int y = insets.top; int height = 0; if (iconComponent != null) { int iconW = iconComponent.getPreferredSize().width; int iconH = iconComponent.getPreferredSize().height; iconComponent.setBounds(x, y, iconW, iconH); x += iconW; height = iconH; } if (component != null) { int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right)); int cH = component.getPreferredSize().height; x += UIScale.scale(iconTextGap); component.setBounds(x, y, cW, cH); height = Math.max(height, cH); } if (closeButton != null) { int cW = closeButton.getPreferredSize().width; int cH = closeButton.getPreferredSize().height; int cX = parent.getWidth() - insets.right - cW; int cy = y + ((height - cH) / 2); closeButton.setBounds(cX, cy, cW, cH); } } } } }
src/main/java/raven/toast/ui/ToastPanelUI.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/ui/DropShadowBorder.java", "retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatPropertiesLaf;\nimport com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.util.ShadowRenderer;\nimport javax.swing.*;\nimport javax.swing.border.EmptyBorder;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;", "score": 0.8622696995735168 }, { "filename": "src/main/java/raven/toast/ToastClientProperties.java", "retrieved_chunk": "package raven.toast;\npublic interface ToastClientProperties {\n String TOAST_ICON = \"Toast.icon\";\n String TOAST_COMPONENT = \"Toast.component\";\n String TOAST_SHOW_CLOSE_BUTTON = \"Toast.showCloseButton\";\n String TOAST_CLOSE_CALLBACK = \"Toast.closeCallback\";\n String TOAST_CLOSE_ICON = \"Toast.closeIcon\";\n String TOAST_SUCCESS_ICON = \"Toast.success.icon\";\n String TOAST_INFO_ICON = \"Toast.info.icon\";\n String TOAST_WARNING_ICON = \"Toast.warning.icon\";", "score": 0.8607469797134399 }, { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": "package raven.toast;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.Animator;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.ui.ToastNotificationPanel;\nimport raven.toast.util.NotificationHolder;\nimport raven.toast.util.UIUtils;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ComponentAdapter;", "score": 0.8505061268806458 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " \"background:\" + convertsKey(key, \"background\", \"$Panel.background\") + \";\" +\n \"outlineColor:\" + outline + \";\" +\n \"effectColor:\" + convertsKey(key, \"effectColor\", outline));\n }\n private String convertsKey(String key, String value, String defaultValue) {\n return \"if($Toast.\" + key + \".\" + value + \", $Toast.\" + key + \".\" + value + \", if($Toast.\" + value + \", $Toast.\" + value + \", \" + defaultValue + \"))\";\n }\n @Override\n public void updateUI() {\n setUI(new ToastPanelUI());", "score": 0.8446680307388306 }, { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": "import java.awt.event.ComponentEvent;\nimport java.awt.event.ComponentListener;\nimport java.util.*;\nimport java.util.List;\nimport java.util.function.Consumer;\n/**\n * <!-- FlatLaf Property -->\n * <p>\n * Toast.outlineWidth int 0 (default)\n * Toast.iconTextGap int 5 (default)", "score": 0.843326210975647 } ]
java
UIUtils.getString(prefix + ".effectAlignment", "left");
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() {
notificationHolder.clearHold();
for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }", "score": 0.9150360226631165 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.900610089302063 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.8692158460617065 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8663949966430664 }, { "filename": "src/test/java/raven/demo/Test.java", "retrieved_chunk": " });\n getContentPane().add(button);\n getContentPane().add(cmdMode);\n JButton buttonClear = new JButton(\"Clear\");\n buttonClear.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n Notifications.getInstance().clearHold();\n }\n });", "score": 0.7856774926185608 } ]
java
notificationHolder.clearHold();
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets =
UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10));
horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " protected JTextPane textPane;\n private Notifications.Type type;\n public ToastNotificationPanel() {\n installDefault();\n }\n private void installPropertyStyle() {\n String key = getKey();\n String outlineColor = toTextColor(getDefaultColor());\n String outline = convertsKey(key, \"outlineColor\", outlineColor);\n putClientProperty(FlatClientProperties.STYLE, \"\" +", "score": 0.8630931973457336 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " removeDialogBackground();\n }\n private void removeDialogBackground() {\n if (window != null) {\n Color bg = getBackground();\n window.setBackground(new Color(bg.getRed(), bg.getGreen(), bg.getBlue(), 0));\n window.setSize(getPreferredSize());\n }\n }\n private void installDefault() {", "score": 0.8629620671272278 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " }\n c.setLayout(layout);\n }\n protected void installStyle(JPanel c) {\n try {\n applyStyle(c, FlatStylingSupport.getResolvedStyle(c, \"ToastPanel\"));\n } catch (RuntimeException ex) {\n LoggingFacade.INSTANCE.logSevere(null, ex);\n }\n }", "score": 0.8595972657203674 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " if (component != null) {\n c.remove(component);\n component = null;\n }\n }\n private void installCloseButton(JComponent c) {\n if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) {\n closeButton = createCloseButton(c);\n installLayout(c);\n c.add(closeButton);", "score": 0.8498294353485107 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);\n if (callback instanceof Runnable) {\n ((Runnable) callback).run();\n } else if (callback instanceof Consumer) {\n ((Consumer) callback).accept(c);\n }\n }\n public void installLayout(JComponent c) {\n if (layout == null) {\n layout = new PanelNotificationLayout();", "score": 0.8498249053955078 } ]
java
UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10));
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) {
notificationHolder.removeHold(hold);
} } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }", "score": 0.896906852722168 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.8743979930877686 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.8512531518936157 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8390133380889893 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);\n if (callback instanceof Runnable) {\n ((Runnable) callback).run();\n } else if (callback instanceof Consumer) {\n ((Consumer) callback).accept(c);\n }\n }\n public void installLayout(JComponent c) {\n if (layout == null) {\n layout = new PanelNotificationLayout();", "score": 0.7647109031677246 } ]
java
notificationHolder.removeHold(hold);
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack();
toastNotificationPanel.setDialog(window);
} public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/test/java/raven/demo/CustomNotification.java", "retrieved_chunk": "package raven.demo;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport raven.toast.ui.ToastNotificationPanel;\nimport javax.swing.*;\npublic class CustomNotification extends Notifications {\n @Override\n protected ToastNotificationPanel createNotification(Type type, String message) {\n ToastNotificationPanel toastNotificationPanel = super.createNotification(type, message);", "score": 0.87059485912323 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " protected JTextPane textPane;\n private Notifications.Type type;\n public ToastNotificationPanel() {\n installDefault();\n }\n private void installPropertyStyle() {\n String key = getKey();\n String outlineColor = toTextColor(getDefaultColor());\n String outline = convertsKey(key, \"outlineColor\", outlineColor);\n putClientProperty(FlatClientProperties.STYLE, \"\" +", "score": 0.868863046169281 }, { "filename": "src/test/java/raven/demo/CustomNotification.java", "retrieved_chunk": " JLabel label = new JLabel(toastNotificationPanel.getKey(), toastNotificationPanel.getDefaultIcon(), JLabel.CENTER);\n label.setVerticalTextPosition(JLabel.BOTTOM);\n label.setForeground(toastNotificationPanel.getDefaultColor());\n label.setHorizontalTextPosition(JLabel.CENTER);\n label.putClientProperty(FlatClientProperties.STYLE, \"\" +\n \"font:$Notifications.font;\" +\n \"iconTextGap:0\");\n toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_ICON, label);\n return toastNotificationPanel;\n }", "score": 0.8664376139640808 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);\n if (callback instanceof Runnable) {\n ((Runnable) callback).run();\n } else if (callback instanceof Consumer) {\n ((Consumer) callback).accept(c);\n }\n }\n public void installLayout(JComponent c) {\n if (layout == null) {\n layout = new PanelNotificationLayout();", "score": 0.8621926307678223 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " labelIcon = new JLabel();\n textPane = new JTextPane();\n textPane.setText(\"Hello!\\nToast Notification\");\n textPane.setOpaque(false);\n textPane.setFocusable(false);\n textPane.setCursor(Cursor.getDefaultCursor());\n putClientProperty(ToastClientProperties.TOAST_ICON, labelIcon);\n putClientProperty(ToastClientProperties.TOAST_COMPONENT, textPane);\n }\n public void set(Notifications.Type type, String message) {", "score": 0.8586950302124023 } ]
java
toastNotificationPanel.setDialog(window);
package raven.toast.ui; import static com.formdev.flatlaf.FlatClientProperties.*; import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.ui.FlatStylingSupport; import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI; import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.LoggingFacade; import com.formdev.flatlaf.util.UIScale; import static raven.toast.ToastClientProperties.*; import raven.toast.util.UIUtils; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicPanelUI; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.function.Consumer; public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener { protected JComponent iconComponent; protected JComponent component; protected JComponent closeButton; @Styleable protected int iconTextGap; @Styleable protected int closeButtonGap; @Styleable protected int minimumWidth; @Styleable protected int maximumWidth; @Styleable protected int arc; @Styleable protected int outlineWidth; @Styleable protected Color outlineColor; @Styleable protected boolean showCloseButton; @Styleable protected Color closeIconColor; @Styleable protected Insets margin; @Styleable protected Icon closeButtonIcon; @Styleable protected boolean useEffect; @Styleable protected Color effectColor; @Styleable protected float effectWidth; @Styleable protected float effectOpacity; @Styleable protected String effectAlignment; private PanelNotificationLayout layout; private Map<String, Object> oldStyleValues; @Override public void installUI(JComponent c) { super.installUI(c); c.addPropertyChangeListener(this); installIconComponent(c); installComponent(c); installCloseButton(c); installStyle((JPanel) c); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removePropertyChangeListener(this); uninstallIconComponent(c); uninstallComponent(c); uninstallCloseButton(c); } @Override protected void installDefaults(JPanel p) { super.installDefaults(p); String prefix = getPropertyPrefix(); iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5); closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5); minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50); maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1); arc = FlatUIUtils.getUIInt(prefix + ".arc", 20); outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0); outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor"); margin = UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8)); showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true); closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150)); closeButtonIcon = UIUtils.getIcon(prefix
+ ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f));
useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true); effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor"); effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f); effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f); effectAlignment = UIUtils.getString(prefix + ".effectAlignment", "left"); p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background")); p.setBorder(createDefaultBorder()); LookAndFeel.installProperty(p, "opaque", false); } @Override protected void uninstallDefaults(JPanel p) { super.uninstallDefaults(p); oldStyleValues = null; } protected Border createDefaultBorder() { Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0)); Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6)); float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f); return new DropShadowBorder(color, insets, shadowOpacity); } protected String getPropertyPrefix() { return "Toast"; } @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case TOAST_ICON: { JPanel c = (JPanel) e.getSource(); uninstallIconComponent(c); installIconComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_COMPONENT: { JPanel c = (JPanel) e.getSource(); uninstallComponent(c); installComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_SHOW_CLOSE_BUTTON: { JPanel c = (JPanel) e.getSource(); uninstallCloseButton(c); installCloseButton(c); c.revalidate(); c.repaint(); break; } case STYLE: case STYLE_CLASS: { JPanel c = (JPanel) e.getSource(); installStyle(c); c.revalidate(); c.repaint(); break; } } } private void installIconComponent(JComponent c) { iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class); if (iconComponent != null) { installLayout(c); c.add(iconComponent); } } private void uninstallIconComponent(JComponent c) { if (iconComponent != null) { c.remove(iconComponent); iconComponent = null; } } private void installComponent(JComponent c) { component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class); if (component != null) { installLayout(c); c.add(component); } } private void uninstallComponent(JComponent c) { if (component != null) { c.remove(component); component = null; } } private void installCloseButton(JComponent c) { if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) { closeButton = createCloseButton(c); installLayout(c); c.add(closeButton); } } private void uninstallCloseButton(JComponent c) { if (closeButton != null) { c.remove(closeButton); closeButton = null; } } protected JComponent createCloseButton(JComponent c) { JButton button = new JButton(); button.setFocusable(false); button.setName("Toast.closeButton"); button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON); button.putClientProperty(STYLE, "" + "arc:999"); button.setIcon(closeButtonIcon); button.addActionListener(e -> closeButtonClicked(c)); return button; } protected void closeButtonClicked(JComponent c) { Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK); if (callback instanceof Runnable) { ((Runnable) callback).run(); } else if (callback instanceof Consumer) { ((Consumer) callback).accept(c); } } public void installLayout(JComponent c) { if (layout == null) { layout = new PanelNotificationLayout(); } c.setLayout(layout); } protected void installStyle(JPanel c) { try { applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel")); } catch (RuntimeException ex) { LoggingFacade.INSTANCE.logSevere(null, ex); } } protected void applyStyle(JPanel c, Object style) { boolean oldShowCloseButton = showCloseButton; oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value)); if (oldShowCloseButton != showCloseButton) { uninstallCloseButton(c); installCloseButton(c); } } protected Object applyStyleProperty(JPanel c, String key, Object value) { return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value); } @Override public Map<String, Class<?>> getStyleableInfos(JComponent c) { return FlatStylingSupport.getAnnotatedStyleableInfos(this); } @Override public Object getStyleableValue(JComponent c, String key) { return FlatStylingSupport.getAnnotatedStyleableValue(this, key); } protected class PanelNotificationLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int width = insets.left + insets.right; int height = 0; int gap = 0; int closeGap = 0; if (iconComponent != null) { width += iconComponent.getPreferredSize().width; height = Math.max(height, iconComponent.getPreferredSize().height); gap = UIScale.scale(iconTextGap); } if (component != null) { width += gap; width += component.getPreferredSize().width; height = Math.max(height, component.getPreferredSize().height); closeGap = UIScale.scale(closeButtonGap); } if (closeButton != null) { width += closeGap; width += closeButton.getPreferredSize().width; height = Math.max(height, closeButton.getPreferredSize().height); } height += (insets.top + insets.bottom); width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width)); return new Dimension(width, height); } } @Override public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return new Dimension(0, 0); } } private int getMaxWidth(int insets) { int width = Math.max(maximumWidth, minimumWidth) - insets; if (iconComponent != null) { width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap)); } if (closeButton != null) { width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width); } return width; } @Override public void layoutContainer(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int x = insets.left; int y = insets.top; int height = 0; if (iconComponent != null) { int iconW = iconComponent.getPreferredSize().width; int iconH = iconComponent.getPreferredSize().height; iconComponent.setBounds(x, y, iconW, iconH); x += iconW; height = iconH; } if (component != null) { int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right)); int cH = component.getPreferredSize().height; x += UIScale.scale(iconTextGap); component.setBounds(x, y, cW, cH); height = Math.max(height, cH); } if (closeButton != null) { int cW = closeButton.getPreferredSize().width; int cH = closeButton.getPreferredSize().height; int cX = parent.getWidth() - insets.right - cW; int cy = y + ((height - cH) / 2); closeButton.setBounds(cX, cy, cW, cH); } } } } }
src/main/java/raven/toast/ui/ToastPanelUI.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/ui/DropShadowBorder.java", "retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatPropertiesLaf;\nimport com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.util.ShadowRenderer;\nimport javax.swing.*;\nimport javax.swing.border.EmptyBorder;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;", "score": 0.8530904650688171 }, { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": "import java.awt.event.ComponentEvent;\nimport java.awt.event.ComponentListener;\nimport java.util.*;\nimport java.util.List;\nimport java.util.function.Consumer;\n/**\n * <!-- FlatLaf Property -->\n * <p>\n * Toast.outlineWidth int 0 (default)\n * Toast.iconTextGap int 5 (default)", "score": 0.8523644804954529 }, { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": "package raven.toast;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.Animator;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.ui.ToastNotificationPanel;\nimport raven.toast.util.NotificationHolder;\nimport raven.toast.util.UIUtils;\nimport javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.ComponentAdapter;", "score": 0.8446903228759766 }, { "filename": "src/main/java/raven/toast/ToastClientProperties.java", "retrieved_chunk": "package raven.toast;\npublic interface ToastClientProperties {\n String TOAST_ICON = \"Toast.icon\";\n String TOAST_COMPONENT = \"Toast.component\";\n String TOAST_SHOW_CLOSE_BUTTON = \"Toast.showCloseButton\";\n String TOAST_CLOSE_CALLBACK = \"Toast.closeCallback\";\n String TOAST_CLOSE_ICON = \"Toast.closeIcon\";\n String TOAST_SUCCESS_ICON = \"Toast.success.icon\";\n String TOAST_INFO_ICON = \"Toast.info.icon\";\n String TOAST_WARNING_ICON = \"Toast.warning.icon\";", "score": 0.8440412878990173 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport com.formdev.flatlaf.extras.FlatSVGIcon;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport javax.swing.*;\nimport java.awt.*;\npublic class ToastNotificationPanel extends JPanel {\n protected JWindow window;\n protected JLabel labelIcon;", "score": 0.8309094309806824 } ]
java
+ ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f));
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation
hold = notificationHolder.getHold(notificationAnimation.getLocation());
if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }", "score": 0.8957071304321289 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.8859193921089172 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8551511764526367 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.8508152365684509 }, { "filename": "src/main/java/raven/toast/ui/ToastPanelUI.java", "retrieved_chunk": " Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK);\n if (callback instanceof Runnable) {\n ((Runnable) callback).run();\n } else if (callback instanceof Consumer) {\n ((Consumer) callback).accept(c);\n }\n }\n public void installLayout(JComponent c) {\n if (layout == null) {\n layout = new PanelNotificationLayout();", "score": 0.7726491689682007 } ]
java
hold = notificationHolder.getHold(notificationAnimation.getLocation());
package raven.toast.ui; import static com.formdev.flatlaf.FlatClientProperties.*; import com.formdev.flatlaf.FlatClientProperties; import com.formdev.flatlaf.ui.FlatStylingSupport; import com.formdev.flatlaf.ui.FlatStylingSupport.StyleableUI; import com.formdev.flatlaf.ui.FlatStylingSupport.Styleable; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.LoggingFacade; import com.formdev.flatlaf.util.UIScale; import static raven.toast.ToastClientProperties.*; import raven.toast.util.UIUtils; import javax.swing.*; import javax.swing.border.Border; import javax.swing.plaf.basic.BasicPanelUI; import java.awt.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Map; import java.util.function.Consumer; public class ToastPanelUI extends BasicPanelUI implements StyleableUI, PropertyChangeListener { protected JComponent iconComponent; protected JComponent component; protected JComponent closeButton; @Styleable protected int iconTextGap; @Styleable protected int closeButtonGap; @Styleable protected int minimumWidth; @Styleable protected int maximumWidth; @Styleable protected int arc; @Styleable protected int outlineWidth; @Styleable protected Color outlineColor; @Styleable protected boolean showCloseButton; @Styleable protected Color closeIconColor; @Styleable protected Insets margin; @Styleable protected Icon closeButtonIcon; @Styleable protected boolean useEffect; @Styleable protected Color effectColor; @Styleable protected float effectWidth; @Styleable protected float effectOpacity; @Styleable protected String effectAlignment; private PanelNotificationLayout layout; private Map<String, Object> oldStyleValues; @Override public void installUI(JComponent c) { super.installUI(c); c.addPropertyChangeListener(this); installIconComponent(c); installComponent(c); installCloseButton(c); installStyle((JPanel) c); } @Override public void uninstallUI(JComponent c) { super.uninstallUI(c); c.removePropertyChangeListener(this); uninstallIconComponent(c); uninstallComponent(c); uninstallCloseButton(c); } @Override protected void installDefaults(JPanel p) { super.installDefaults(p); String prefix = getPropertyPrefix(); iconTextGap = FlatUIUtils.getUIInt(prefix + ".iconTextGap", 5); closeButtonGap = FlatUIUtils.getUIInt(prefix + ".closeButtonGap", 5); minimumWidth = FlatUIUtils.getUIInt(prefix + ".minimumWidth", 50); maximumWidth = FlatUIUtils.getUIInt(prefix + ".maximumWidth", -1); arc = FlatUIUtils.getUIInt(prefix + ".arc", 20); outlineWidth = FlatUIUtils.getUIInt(prefix + ".outlineWidth", 0); outlineColor = FlatUIUtils.getUIColor(prefix + ".outlineColor", "Component.focusColor"); margin =
UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8));
showCloseButton = FlatUIUtils.getUIBoolean(prefix + ".showCloseButton", true); closeIconColor = FlatUIUtils.getUIColor(prefix + ".closeIconColor", new Color(150, 150, 150)); closeButtonIcon = UIUtils.getIcon(prefix + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); useEffect = FlatUIUtils.getUIBoolean(prefix + ".useEffect", true); effectColor = FlatUIUtils.getUIColor(prefix + ".effectColor", "Component.focusColor"); effectWidth = FlatUIUtils.getUIFloat(prefix + ".effectWidth", 0.5f); effectOpacity = FlatUIUtils.getUIFloat(prefix + ".effectOpacity", 0.2f); effectAlignment = UIUtils.getString(prefix + ".effectAlignment", "left"); p.setBackground(FlatUIUtils.getUIColor(prefix + ".background", "Panel.background")); p.setBorder(createDefaultBorder()); LookAndFeel.installProperty(p, "opaque", false); } @Override protected void uninstallDefaults(JPanel p) { super.uninstallDefaults(p); oldStyleValues = null; } protected Border createDefaultBorder() { Color color = FlatUIUtils.getUIColor("Toast.shadowColor", new Color(0, 0, 0)); Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6)); float shadowOpacity = FlatUIUtils.getUIFloat("Toast.shadowOpacity", 0.1f); return new DropShadowBorder(color, insets, shadowOpacity); } protected String getPropertyPrefix() { return "Toast"; } @Override public void propertyChange(PropertyChangeEvent e) { switch (e.getPropertyName()) { case TOAST_ICON: { JPanel c = (JPanel) e.getSource(); uninstallIconComponent(c); installIconComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_COMPONENT: { JPanel c = (JPanel) e.getSource(); uninstallComponent(c); installComponent(c); c.revalidate(); c.repaint(); break; } case TOAST_SHOW_CLOSE_BUTTON: { JPanel c = (JPanel) e.getSource(); uninstallCloseButton(c); installCloseButton(c); c.revalidate(); c.repaint(); break; } case STYLE: case STYLE_CLASS: { JPanel c = (JPanel) e.getSource(); installStyle(c); c.revalidate(); c.repaint(); break; } } } private void installIconComponent(JComponent c) { iconComponent = clientProperty(c, TOAST_ICON, null, JComponent.class); if (iconComponent != null) { installLayout(c); c.add(iconComponent); } } private void uninstallIconComponent(JComponent c) { if (iconComponent != null) { c.remove(iconComponent); iconComponent = null; } } private void installComponent(JComponent c) { component = FlatClientProperties.clientProperty(c, TOAST_COMPONENT, null, JComponent.class); if (component != null) { installLayout(c); c.add(component); } } private void uninstallComponent(JComponent c) { if (component != null) { c.remove(component); component = null; } } private void installCloseButton(JComponent c) { if (clientPropertyBoolean(c, TOAST_SHOW_CLOSE_BUTTON, showCloseButton)) { closeButton = createCloseButton(c); installLayout(c); c.add(closeButton); } } private void uninstallCloseButton(JComponent c) { if (closeButton != null) { c.remove(closeButton); closeButton = null; } } protected JComponent createCloseButton(JComponent c) { JButton button = new JButton(); button.setFocusable(false); button.setName("Toast.closeButton"); button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON); button.putClientProperty(STYLE, "" + "arc:999"); button.setIcon(closeButtonIcon); button.addActionListener(e -> closeButtonClicked(c)); return button; } protected void closeButtonClicked(JComponent c) { Object callback = c.getClientProperty(TOAST_CLOSE_CALLBACK); if (callback instanceof Runnable) { ((Runnable) callback).run(); } else if (callback instanceof Consumer) { ((Consumer) callback).accept(c); } } public void installLayout(JComponent c) { if (layout == null) { layout = new PanelNotificationLayout(); } c.setLayout(layout); } protected void installStyle(JPanel c) { try { applyStyle(c, FlatStylingSupport.getResolvedStyle(c, "ToastPanel")); } catch (RuntimeException ex) { LoggingFacade.INSTANCE.logSevere(null, ex); } } protected void applyStyle(JPanel c, Object style) { boolean oldShowCloseButton = showCloseButton; oldStyleValues = FlatStylingSupport.parseAndApply(oldStyleValues, style, (key, value) -> applyStyleProperty(c, key, value)); if (oldShowCloseButton != showCloseButton) { uninstallCloseButton(c); installCloseButton(c); } } protected Object applyStyleProperty(JPanel c, String key, Object value) { return FlatStylingSupport.applyToAnnotatedObjectOrComponent(this, c, key, value); } @Override public Map<String, Class<?>> getStyleableInfos(JComponent c) { return FlatStylingSupport.getAnnotatedStyleableInfos(this); } @Override public Object getStyleableValue(JComponent c, String key) { return FlatStylingSupport.getAnnotatedStyleableValue(this, key); } protected class PanelNotificationLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) { } @Override public void removeLayoutComponent(Component comp) { } @Override public Dimension preferredLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int width = insets.left + insets.right; int height = 0; int gap = 0; int closeGap = 0; if (iconComponent != null) { width += iconComponent.getPreferredSize().width; height = Math.max(height, iconComponent.getPreferredSize().height); gap = UIScale.scale(iconTextGap); } if (component != null) { width += gap; width += component.getPreferredSize().width; height = Math.max(height, component.getPreferredSize().height); closeGap = UIScale.scale(closeButtonGap); } if (closeButton != null) { width += closeGap; width += closeButton.getPreferredSize().width; height = Math.max(height, closeButton.getPreferredSize().height); } height += (insets.top + insets.bottom); width = Math.max(minimumWidth, maximumWidth == -1 ? width : Math.min(maximumWidth, width)); return new Dimension(width, height); } } @Override public Dimension minimumLayoutSize(Container parent) { synchronized (parent.getTreeLock()) { return new Dimension(0, 0); } } private int getMaxWidth(int insets) { int width = Math.max(maximumWidth, minimumWidth) - insets; if (iconComponent != null) { width -= (iconComponent.getPreferredSize().width + UIScale.scale(iconTextGap)); } if (closeButton != null) { width -= (UIScale.scale(closeButtonGap) + closeButton.getPreferredSize().width); } return width; } @Override public void layoutContainer(Container parent) { synchronized (parent.getTreeLock()) { Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin)); int x = insets.left; int y = insets.top; int height = 0; if (iconComponent != null) { int iconW = iconComponent.getPreferredSize().width; int iconH = iconComponent.getPreferredSize().height; iconComponent.setBounds(x, y, iconW, iconH); x += iconW; height = iconH; } if (component != null) { int cW = maximumWidth == -1 ? component.getPreferredSize().width : Math.min(component.getPreferredSize().width, getMaxWidth(insets.left + insets.right)); int cH = component.getPreferredSize().height; x += UIScale.scale(iconTextGap); component.setBounds(x, y, cW, cH); height = Math.max(height, cH); } if (closeButton != null) { int cW = closeButton.getPreferredSize().width; int cH = closeButton.getPreferredSize().height; int cX = parent.getWidth() - insets.right - cW; int cy = y + ((height - cH) / 2); closeButton.setBounds(cX, cy, cW, cH); } } } } }
src/main/java/raven/toast/ui/ToastPanelUI.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/Notifications.java", "retrieved_chunk": "import java.awt.event.ComponentEvent;\nimport java.awt.event.ComponentListener;\nimport java.util.*;\nimport java.util.List;\nimport java.util.function.Consumer;\n/**\n * <!-- FlatLaf Property -->\n * <p>\n * Toast.outlineWidth int 0 (default)\n * Toast.iconTextGap int 5 (default)", "score": 0.844719409942627 }, { "filename": "src/main/java/raven/toast/ui/DropShadowBorder.java", "retrieved_chunk": "package raven.toast.ui;\nimport com.formdev.flatlaf.FlatPropertiesLaf;\nimport com.formdev.flatlaf.ui.FlatStylingSupport.Styleable;\nimport com.formdev.flatlaf.ui.FlatUIUtils;\nimport com.formdev.flatlaf.util.UIScale;\nimport raven.toast.util.ShadowRenderer;\nimport javax.swing.*;\nimport javax.swing.border.EmptyBorder;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;", "score": 0.8346985578536987 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " protected JTextPane textPane;\n private Notifications.Type type;\n public ToastNotificationPanel() {\n installDefault();\n }\n private void installPropertyStyle() {\n String key = getKey();\n String outlineColor = toTextColor(getDefaultColor());\n String outline = convertsKey(key, \"outlineColor\", outlineColor);\n putClientProperty(FlatClientProperties.STYLE, \"\" +", "score": 0.8308393955230713 }, { "filename": "src/main/java/raven/toast/ui/DropShadowBorder.java", "retrieved_chunk": " JComponent com = (JComponent) c;\n int arc = FlatPropertiesLaf.getStyleableValue(com, \"arc\");\n boolean useEffect = FlatPropertiesLaf.getStyleableValue(com, \"useEffect\");\n if (shadowImage == null || !shadowColor.equals(lastShadowColor) || width != lastWidth || height != lastHeight || shadowSize != lastShadowSize || shadowOpacity != lastShadowOpacity || arc != lastArc) {\n shadowImage = createShadowImage(width, height, arc);\n lastShadowColor = shadowColor;\n lastWidth = width;\n lastHeight = height;\n lastShadowSize = shadowSize;\n lastShadowOpacity = shadowOpacity;", "score": 0.8305410146713257 }, { "filename": "src/main/java/raven/toast/util/UIUtils.java", "retrieved_chunk": " if (icon == null) {\n return defaultValue;\n }\n return icon;\n }\n public static Insets getInsets(String key, Insets defaultValue) {\n Insets insets = UIManager.getInsets(key);\n if (insets == null) {\n return defaultValue;\n }", "score": 0.8265836238861084 } ]
java
UIUtils.getInsets(prefix + ".margin", new Insets(8, 8, 8, 8));
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) {
notificationHolder.clearHold(location);
List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.9257774949073792 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.8730863332748413 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }", "score": 0.8467250466346741 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8265222907066345 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " if (n.getLocation() == location) {\n lists.remove(n);\n i--;\n }\n }\n }\n }\n}", "score": 0.7941205501556396 } ]
java
notificationHolder.clearHold(location);
package sprites; import domain.CompositeShape; import domain.GenericShape; import domain.Point; import domain.Shape; import primitives.Line; import primitives.Rectangle; import primitives.Square; import transformations.MoveBy; import java.util.ArrayList; import java.util.List; public class House extends CompositeShape { private final Point lowerLeft; public House(Point lowerLeft) { this.lowerLeft = lowerLeft; } @Override protected List<Shape> getShapes() { List<Shape> allShapes = new ArrayList<>(); allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall allShapes.add(new Rectangle(new Point(17, 0), new Point(22, 12))); //door allShapes.add(new Square(new Point(5, 10), 5)); //window allShapes.add(new Line(new Point(0, 20), new Point(12, 25))); allShapes.add(new Line(new Point(12, 25), new Point(26, 20))); return allShapes; } @Override public List<Point> getPoints() { List<Point> originalPoints = super.getPoints(); return new MoveBy(lowerLeft.getX(),
lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();
} }
src/main/java/sprites/House.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/primitives/Dot.java", "retrieved_chunk": " @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n result.add(coordinates);\n return result;\n }\n}", "score": 0.8450281620025635 }, { "filename": "src/main/java/transformations/PerPointTransformation.java", "retrieved_chunk": " List<Point> result = new ArrayList<>();\n for (Point point : origin.getPoints()) {\n Point newPoint = transformPoint(point);\n result.add(newPoint);\n }\n return new GenericShape(result);\n }\n}", "score": 0.8412286043167114 }, { "filename": "src/main/java/domain/GenericShape.java", "retrieved_chunk": "package domain;\nimport java.util.List;\npublic class GenericShape implements Shape{\n private final List<Point> points;\n public GenericShape(List<Point> points) {\n this.points = points;\n }\n @Override\n public List<Point> getPoints() {\n return points;", "score": 0.8357837200164795 }, { "filename": "src/main/java/domain/CompositeShape.java", "retrieved_chunk": "package domain;\nimport java.util.ArrayList;\nimport java.util.List;\npublic abstract class CompositeShape implements Shape {\n protected abstract List<Shape> getShapes();\n @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n for (Shape shape: getShapes()) {\n result.addAll(shape.getPoints());", "score": 0.83265221118927 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " }\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n for (Point point : allPoints) {\n g.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);\n }\n }\n }\n}", "score": 0.8292645215988159 } ]
java
lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else { notificationHolder.hold(notificationAnimation); return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel();
toastNotificationPanel.set(type, message);
return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.8747495412826538 }, { "filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java", "retrieved_chunk": " labelIcon = new JLabel();\n textPane = new JTextPane();\n textPane.setText(\"Hello!\\nToast Notification\");\n textPane.setOpaque(false);\n textPane.setFocusable(false);\n textPane.setCursor(Cursor.getDefaultCursor());\n putClientProperty(ToastClientProperties.TOAST_ICON, labelIcon);\n putClientProperty(ToastClientProperties.TOAST_COMPONENT, textPane);\n }\n public void set(Notifications.Type type, String message) {", "score": 0.8449504971504211 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8368517160415649 }, { "filename": "src/test/java/raven/demo/CustomNotification.java", "retrieved_chunk": "package raven.demo;\nimport com.formdev.flatlaf.FlatClientProperties;\nimport raven.toast.Notifications;\nimport raven.toast.ToastClientProperties;\nimport raven.toast.ui.ToastNotificationPanel;\nimport javax.swing.*;\npublic class CustomNotification extends Notifications {\n @Override\n protected ToastNotificationPanel createNotification(Type type, String message) {\n ToastNotificationPanel toastNotificationPanel = super.createNotification(type, message);", "score": 0.8345960974693298 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.8333200216293335 } ]
java
toastNotificationPanel.set(type, message);
package sprites; import domain.CompositeShape; import domain.GenericShape; import domain.Point; import domain.Shape; import primitives.Line; import primitives.Rectangle; import primitives.Square; import transformations.MoveBy; import java.util.ArrayList; import java.util.List; public class House extends CompositeShape { private final Point lowerLeft; public House(Point lowerLeft) { this.lowerLeft = lowerLeft; } @Override protected List<Shape> getShapes() { List<Shape> allShapes = new ArrayList<>(); allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall allShapes.add(new Rectangle(new Point(17, 0), new Point(22, 12))); //door allShapes.add(new Square(new Point(5, 10), 5)); //window allShapes.add(new Line(new Point(0, 20), new Point(12, 25))); allShapes.add(new Line(new Point(12, 25), new Point(26, 20))); return allShapes; } @Override public List<Point> getPoints() { List<Point> originalPoints = super.getPoints(); return new MoveBy(
lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();
} }
src/main/java/sprites/House.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/primitives/Dot.java", "retrieved_chunk": " @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n result.add(coordinates);\n return result;\n }\n}", "score": 0.8483234643936157 }, { "filename": "src/main/java/transformations/PerPointTransformation.java", "retrieved_chunk": " List<Point> result = new ArrayList<>();\n for (Point point : origin.getPoints()) {\n Point newPoint = transformPoint(point);\n result.add(newPoint);\n }\n return new GenericShape(result);\n }\n}", "score": 0.8417301177978516 }, { "filename": "src/main/java/domain/GenericShape.java", "retrieved_chunk": "package domain;\nimport java.util.List;\npublic class GenericShape implements Shape{\n private final List<Point> points;\n public GenericShape(List<Point> points) {\n this.points = points;\n }\n @Override\n public List<Point> getPoints() {\n return points;", "score": 0.8362374305725098 }, { "filename": "src/main/java/domain/CompositeShape.java", "retrieved_chunk": "package domain;\nimport java.util.ArrayList;\nimport java.util.List;\npublic abstract class CompositeShape implements Shape {\n protected abstract List<Shape> getShapes();\n @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n for (Shape shape: getShapes()) {\n result.addAll(shape.getPoints());", "score": 0.8324533700942993 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " }\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n for (Point point : allPoints) {\n g.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);\n }\n }\n }\n}", "score": 0.8316256999969482 } ]
java
lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();
package canvas; import domain.Point; import domain.Shape; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; public class TextCanvas implements Canvas { private final Pixel[][] pixels; private final int height; private final int width; private String SET = " 0 "; private String UNSET = " · "; public TextCanvas(int width, int height) { this.width = width; this.height = height; this.pixels = new Pixel[height][width]; clean(); } public void clean() { for (Pixel[] row : pixels) { Arrays.fill(row, new Pixel(false)); } } public void draw(Shape shape) { for (Point point : shape.getPoints()) { set(point.getX(), point.getY()); } } private void set(int x, int y) { if (x >= 0 && y >= 0 && x < width && y < height) { pixels[y][x] = new Pixel(true); } } @Override public void show() { for (int y = height - 1; y >= 0; y--) { if (y % 5 == 0) { System.out.print(String.format("%1$3s", y)); } else { System.out.print(" "); } for (int x = 0; x < width; x++) { if (pixels[
y][x].isSet()) {
System.out.print(SET); } else { System.out.print(UNSET); } } System.out.println(); } System.out.print(" "); for (int x = 0; x < width; x++) { if (x % 5 == 0) { System.out.print(StringUtils.rightPad(String.valueOf(x), 3)); } else { System.out.print(" "); } } System.out.println(); } }
src/main/java/canvas/TextCanvas.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " int y = point.getY();\n if (x >= 0 && y >= 0 && x < width && y < height) {\n allPoints.add(new Point(x, height - 1 - y));\n }\n }\n }\n public void show() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {", "score": 0.8454214334487915 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " }\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n for (Point point : allPoints) {\n g.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);\n }\n }\n }\n}", "score": 0.7946637272834778 }, { "filename": "src/main/java/canvas/Pixel.java", "retrieved_chunk": "package canvas;\npublic class Pixel {\n private boolean isSet;\n public Pixel(boolean isSet) {\n this.isSet = isSet;\n }\n public boolean isSet() {\n return isSet;\n }\n}", "score": 0.7886430025100708 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " new Frame().setVisible(true);\n }\n });\n }\n class Frame extends JFrame {\n Frame() {\n super(\"Graphic Canvas\");\n setSize(factor * width + 2*factor, factor * height + 50);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);", "score": 0.7796602249145508 }, { "filename": "src/main/java/canvas/Canvas.java", "retrieved_chunk": "package canvas;\nimport domain.Shape;\npublic interface Canvas {\n void draw(Shape shape);\n void show();\n}", "score": 0.7782981991767883 } ]
java
y][x].isSet()) {
package canvas; import domain.Point; import domain.Shape; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; public class TextCanvas implements Canvas { private final Pixel[][] pixels; private final int height; private final int width; private String SET = " 0 "; private String UNSET = " · "; public TextCanvas(int width, int height) { this.width = width; this.height = height; this.pixels = new Pixel[height][width]; clean(); } public void clean() { for (Pixel[] row : pixels) { Arrays.fill(row, new Pixel(false)); } } public void draw(Shape shape) { for (Point point : shape.getPoints()) { set
(point.getX(), point.getY());
} } private void set(int x, int y) { if (x >= 0 && y >= 0 && x < width && y < height) { pixels[y][x] = new Pixel(true); } } @Override public void show() { for (int y = height - 1; y >= 0; y--) { if (y % 5 == 0) { System.out.print(String.format("%1$3s", y)); } else { System.out.print(" "); } for (int x = 0; x < width; x++) { if (pixels[y][x].isSet()) { System.out.print(SET); } else { System.out.print(UNSET); } } System.out.println(); } System.out.print(" "); for (int x = 0; x < width; x++) { if (x % 5 == 0) { System.out.print(StringUtils.rightPad(String.valueOf(x), 3)); } else { System.out.print(" "); } } System.out.println(); } }
src/main/java/canvas/TextCanvas.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " private final int factor;\n public SwingCanvas(int width, int height, int factor) {\n this.width = width;\n this.height = height;\n this.factor = factor;\n }\n private List<Point> allPoints = new ArrayList<>();\n public void draw(Shape shape) {\n for (Point point: shape.getPoints()) {\n int x = point.getX();", "score": 0.8462771773338318 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " }\n @Override\n public void paint(Graphics g) {\n super.paint(g);\n for (Point point : allPoints) {\n g.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);\n }\n }\n }\n}", "score": 0.8183542490005493 }, { "filename": "src/main/java/canvas/Canvas.java", "retrieved_chunk": "package canvas;\nimport domain.Shape;\npublic interface Canvas {\n void draw(Shape shape);\n void show();\n}", "score": 0.8085788488388062 }, { "filename": "src/main/java/canvas/Pixel.java", "retrieved_chunk": "package canvas;\npublic class Pixel {\n private boolean isSet;\n public Pixel(boolean isSet) {\n this.isSet = isSet;\n }\n public boolean isSet() {\n return isSet;\n }\n}", "score": 0.8009078502655029 }, { "filename": "src/main/java/canvas/SwingCanvas.java", "retrieved_chunk": " int y = point.getY();\n if (x >= 0 && y >= 0 && x < width && y < height) {\n allPoints.add(new Point(x, height - 1 - y));\n }\n }\n }\n public void show() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {", "score": 0.7964515686035156 } ]
java
(point.getX(), point.getY());
package raven.toast; import com.formdev.flatlaf.ui.FlatUIUtils; import com.formdev.flatlaf.util.Animator; import com.formdev.flatlaf.util.UIScale; import raven.toast.ui.ToastNotificationPanel; import raven.toast.util.NotificationHolder; import raven.toast.util.UIUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.*; import java.util.List; import java.util.function.Consumer; /** * <!-- FlatLaf Property --> * <p> * Toast.outlineWidth int 0 (default) * Toast.iconTextGap int 5 (default) * Toast.closeButtonGap int 5 (default) * Toast.arc int 20 (default) * Toast.horizontalGap int 10 (default) * <p> * Toast.limit int -1 (default) -1 as unlimited * Toast.duration long 2500 (default) * Toast.animation int 200 (default) * Toast.animationResolution int 5 (default) * Toast.animationMove int 10 (default) * Toast.minimumWidth int 50 (default) * Toast.maximumWidth int -1 (default) -1 as not set * <p> * Toast.shadowColor Color * Toast.shadowOpacity float 0.1f (default) * Toast.shadowInsets Insets 0,0,6,6 (default) * <p> * Toast.useEffect boolean true (default) * Toast.effectWidth float 0.5f (default) 0.5f as 50% * Toast.effectOpacity float 0.2f (default) 0 to 1 * Toast.effectAlignment String left (default) left, right * Toast.effectColor Color * Toast.success.effectColor Color * Toast.info.effectColor Color * Toast.warning.effectColor Color * Toast.error.effectColor Color * <p> * Toast.outlineColor Color * Toast.foreground Color * Toast.background Color * <p> * Toast.success.outlineColor Color * Toast.success.foreground Color * Toast.success.background Color * Toast.info.outlineColor Color * Toast.info.foreground Color * Toast.info.background Color * Toast.warning.outlineColor Color * Toast.warning.foreground Color * Toast.warning.background Color * Toast.error.outlineColor Color * Toast.error.foreground Color * Toast.error.background Color * <p> * Toast.frameInsets Insets 10,10,10,10 (default) * Toast.margin Insets 8,8,8,8 (default) * <p> * Toast.showCloseButton boolean true (default) * Toast.closeIconColor Color * * <p> * <!-- UIManager --> * <p> * Toast.success.icon Icon * Toast.info.icon Icon * Toast.warning.icon Icon * Toast.error.icon Icon * Toast.closeIcon Icon */ /** * @author Raven */ public class Notifications { private static Notifications instance; private JFrame frame; private final Map<Location, List<NotificationAnimation>> lists = new HashMap<>(); private final NotificationHolder notificationHolder = new NotificationHolder(); private ComponentListener windowEvent; private void installEvent(JFrame frame) { if (windowEvent == null && frame != null) { windowEvent = new ComponentAdapter() { @Override public void componentMoved(ComponentEvent e) { move(frame.getBounds()); } @Override public void componentResized(ComponentEvent e) { move(frame.getBounds()); } }; } if (this.frame != null) { this.frame.removeComponentListener(windowEvent); } if (frame != null) { frame.addComponentListener(windowEvent); } this.frame = frame; } public static Notifications getInstance() { if (instance == null) { instance = new Notifications(); } return instance; } private int getCurrentShowCount(Location location) { List list = lists.get(location); return list == null ? 0 : list.size(); } private synchronized void move(Rectangle rectangle) { for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.move(rectangle); } } } } public void setJFrame(JFrame frame) { installEvent(frame); } public void show(Type type, String message) { show(type, Location.TOP_CENTER, message); } public void show(Type type, long duration, String message) { show(type, Location.TOP_CENTER, duration, message); } public void show(Type type, Location location, String message) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(type, location, duration, message); } public void show(Type type, Location location, long duration, String message) { initStart(new NotificationAnimation(type, location, duration, message), duration); } public void show(JComponent component) { show(Location.TOP_CENTER, component); } public void show(Location location, JComponent component) { long duration = FlatUIUtils.getUIInt("Toast.duration", 2500); show(location, duration, component); } public void show(Location location, long duration, JComponent component) { initStart(new NotificationAnimation(location, duration, component), duration); } private synchronized boolean initStart(NotificationAnimation notificationAnimation, long duration) { int limit = FlatUIUtils.getUIInt("Toast.limit", -1); if (limit == -1 || getCurrentShowCount(notificationAnimation.getLocation()) < limit) { notificationAnimation.start(); return true; } else {
notificationHolder.hold(notificationAnimation);
return false; } } private synchronized void notificationClose(NotificationAnimation notificationAnimation) { NotificationAnimation hold = notificationHolder.getHold(notificationAnimation.getLocation()); if (hold != null) { if (initStart(hold, hold.getDuration())) { notificationHolder.removeHold(hold); } } } public void clearAll() { notificationHolder.clearHold(); for (Map.Entry<Location, List<NotificationAnimation>> set : lists.entrySet()) { for (int i = 0; i < set.getValue().size(); i++) { NotificationAnimation an = set.getValue().get(i); if (an != null) { an.close(); } } } } public void clear(Location location) { notificationHolder.clearHold(location); List<NotificationAnimation> list = lists.get(location); if (list != null) { for (int i = 0; i < list.size(); i++) { NotificationAnimation an = list.get(i); if (an != null) { an.close(); } } } } public void clearHold() { notificationHolder.clearHold(); } public void clearHold(Location location) { notificationHolder.clearHold(location); } protected ToastNotificationPanel createNotification(Type type, String message) { ToastNotificationPanel toastNotificationPanel = new ToastNotificationPanel(); toastNotificationPanel.set(type, message); return toastNotificationPanel; } private synchronized void updateList(Location key, NotificationAnimation values, boolean add) { if (add) { if (lists.containsKey(key)) { lists.get(key).add(values); } else { List<NotificationAnimation> list = new ArrayList<>(); list.add(values); lists.put(key, list); } } else { if (lists.containsKey(key)) { lists.get(key).remove(values); if (lists.get(key).isEmpty()) { lists.remove(key); } } } } public enum Type { SUCCESS, INFO, WARNING, ERROR } public enum Location { TOP_LEFT, TOP_CENTER, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT } public class NotificationAnimation { private JWindow window; private Animator animator; private boolean show = true; private float animate; private int x; private int y; private Location location; private long duration; private Insets frameInsets; private int horizontalSpace; private int animationMove; private boolean top; private boolean close = false; public NotificationAnimation(Type type, Location location, long duration, String message) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); ToastNotificationPanel toastNotificationPanel = createNotification(type, message); toastNotificationPanel.putClientProperty(ToastClientProperties.TOAST_CLOSE_CALLBACK, (Consumer) o -> close()); window.setContentPane(toastNotificationPanel); window.setFocusableWindowState(false); window.pack(); toastNotificationPanel.setDialog(window); } public NotificationAnimation(Location location, long duration, JComponent component) { installDefault(); this.location = location; this.duration = duration; window = new JWindow(frame); window.setBackground(new Color(0, 0, 0, 0)); window.setContentPane(component); window.setFocusableWindowState(false); window.setSize(component.getPreferredSize()); } private void installDefault() { frameInsets = UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); horizontalSpace = FlatUIUtils.getUIInt("Toast.horizontalGap", 10); animationMove = FlatUIUtils.getUIInt("Toast.animationMove", 10); } public void start() { int animation = FlatUIUtils.getUIInt("Toast.animation", 200); int resolution = FlatUIUtils.getUIInt("Toast.animationResolution", 5); animator = new Animator(animation, new Animator.TimingTarget() { @Override public void begin() { if (show) { updateList(location, NotificationAnimation.this, true); installLocation(); } } @Override public void timingEvent(float f) { animate = show ? f : 1f - f; updateLocation(true); } @Override public void end() { if (show && close == false) { SwingUtilities.invokeLater(() -> { new Thread(() -> { sleep(duration); if (close == false) { show = false; animator.start(); } }).start(); }); } else { updateList(location, NotificationAnimation.this, false); window.dispose(); notificationClose(NotificationAnimation.this); } } }); animator.setResolution(resolution); animator.start(); } private void installLocation() { Insets insets; Rectangle rec; if (frame == null) { insets = UIScale.scale(frameInsets); rec = new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize()); } else { insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); rec = frame.getBounds(); } setupLocation(rec, insets); window.setOpacity(0f); window.setVisible(true); } private void move(Rectangle rec) { Insets insets = UIScale.scale(FlatUIUtils.addInsets(frameInsets, frame.getInsets())); setupLocation(rec, insets); } private void setupLocation(Rectangle rec, Insets insets) { if (location == Location.TOP_LEFT) { x = rec.x + insets.left; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + insets.top; top = true; } else if (location == Location.TOP_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + insets.top; top = true; } else if (location == Location.BOTTOM_LEFT) { x = rec.x + insets.left; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_CENTER) { x = rec.x + (rec.width - window.getWidth()) / 2; y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } else if (location == Location.BOTTOM_RIGHT) { x = rec.x + rec.width - (window.getWidth() + insets.right); y = rec.y + rec.height - (window.getHeight() + insets.bottom); top = false; } int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); } private void updateLocation(boolean loop) { int am = UIScale.scale(top ? animationMove : -animationMove); int ly = (int) (getLocation(NotificationAnimation.this) + y + animate * am); window.setLocation(x, ly); window.setOpacity(animate); if (loop) { update(this); } } private int getLocation(NotificationAnimation notification) { int height = 0; List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (notification == n) { return height; } double v = n.animate * (list.get(i).window.getHeight() + UIScale.scale(horizontalSpace)); height += top ? v : -v; } return height; } private void update(NotificationAnimation except) { List<NotificationAnimation> list = lists.get(location); for (int i = 0; i < list.size(); i++) { NotificationAnimation n = list.get(i); if (n != except) { n.updateLocation(false); } } } public void close() { close = true; show = false; if (animator.isRunning()) { animator.stop(); } animator.start(); } private void sleep(long l) { try { Thread.sleep(l); } catch (InterruptedException e) { System.err.println(e); } } public Location getLocation() { return location; } public long getDuration() { return duration; } } }
src/main/java/raven/toast/Notifications.java
DJ-Raven-swing-toast-notifications-4c7978a
[ { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " public Notifications.NotificationAnimation getHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);\n if (n.getLocation() == location) {\n return n;\n }\n }\n return null;\n }", "score": 0.845281720161438 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": "package raven.toast.util;\nimport raven.toast.Notifications;\nimport java.util.ArrayList;\nimport java.util.List;\npublic class NotificationHolder {\n private final List<Notifications.NotificationAnimation> lists = new ArrayList<>();\n private final Object lock = new Object();\n public int getHoldCount() {\n return lists.size();\n }", "score": 0.8087133169174194 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void removeHold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.remove(notificationAnimation);\n }\n }\n public void hold(Notifications.NotificationAnimation notificationAnimation) {\n synchronized (lock) {\n lists.add(notificationAnimation);\n }", "score": 0.8079593777656555 }, { "filename": "src/main/java/raven/toast/util/NotificationHolder.java", "retrieved_chunk": " }\n public void clearHold() {\n synchronized (lock) {\n lists.clear();\n }\n }\n public void clearHold(Notifications.Location location) {\n synchronized (lock) {\n for (int i = 0; i < lists.size(); i++) {\n Notifications.NotificationAnimation n = lists.get(i);", "score": 0.806904137134552 }, { "filename": "src/test/java/raven/demo/Test.java", "retrieved_chunk": " getContentPane().add(buttonClear);\n ToastNotificationPanel panel = new ToastNotificationPanel();\n panel.set(Notifications.Type.INFO, \"Hello my name is raven\\nThis new Toast Panel Notification\");\n getContentPane().add(panel);\n }\n private Notifications.Location getRandomLocation() {\n Random ran = new Random();\n int a = ran.nextInt(6);\n if (a == 0) {\n return Notifications.Location.TOP_LEFT;", "score": 0.8022162914276123 } ]
java
notificationHolder.hold(notificationAnimation);
package canvas; import domain.Point; import domain.Shape; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class SwingCanvas implements Canvas { private final int width; private final int height; private final int factor; public SwingCanvas(int width, int height, int factor) { this.width = width; this.height = height; this.factor = factor; } private List<Point> allPoints = new ArrayList<>(); public void draw(Shape shape) { for (Point point: shape.getPoints()) { int x = point.getX(); int y = point.getY(); if (x >= 0 && y >= 0 && x < width && y < height) { allPoints.add(new Point(x, height - 1 - y)); } } } public void show() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Frame().setVisible(true); } }); } class Frame extends JFrame { Frame() { super("Graphic Canvas"); setSize(factor * width + 2*factor, factor * height + 50); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } @Override public void paint(Graphics g) { super.paint(g); for (Point point : allPoints) { g.drawOval(point.
getX() * factor, point.getY() * factor + 50, factor, factor);
} } } }
src/main/java/canvas/SwingCanvas.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/sprites/House.java", "retrieved_chunk": " allShapes.add(new Rectangle(new Point(17, 0), new Point(22, 12))); //door\n allShapes.add(new Square(new Point(5, 10), 5)); //window\n allShapes.add(new Line(new Point(0, 20), new Point(12, 25)));\n allShapes.add(new Line(new Point(12, 25), new Point(26, 20)));\n return allShapes;\n }\n @Override\n public List<Point> getPoints() {\n List<Point> originalPoints = super.getPoints();\n return new MoveBy(lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();", "score": 0.8312524557113647 }, { "filename": "src/main/java/Main.java", "retrieved_chunk": " Canvas canvas = new SwingCanvas(80, 70, 10);\n House house1 = new House(new Point(1, 1));\n Shape house2 = new House(new Point(0, 0)) //House\n .transform(new MirrorOverX(26)) // GenericShape\n .transform(new MoveBy(5, 3)); //GenericShape - 2\n Shape landscape = house1.combineWith(house2)\n .transform(new MirrorOverX(20));\n canvas.draw(landscape);\n canvas.show();\n }", "score": 0.8261698484420776 }, { "filename": "src/main/java/canvas/TextCanvas.java", "retrieved_chunk": " }\n }\n public void draw(Shape shape) {\n for (Point point : shape.getPoints()) {\n set(point.getX(), point.getY());\n }\n }\n private void set(int x, int y) {\n if (x >= 0 && y >= 0 && x < width && y < height) {\n pixels[y][x] = new Pixel(true);", "score": 0.8203487396240234 }, { "filename": "src/main/java/Main.java", "retrieved_chunk": "import canvas.*;\nimport domain.Point;\nimport domain.Shape;\nimport primitives.*;\nimport sprites.House;\nimport transformations.MirrorOverX;\nimport transformations.MoveBy;\npublic class Main {\n public static void main(String[] args) {\n// Canvas canvas = new TextCanvas(60, 30);", "score": 0.8098018169403076 }, { "filename": "src/main/java/primitives/Rectangle.java", "retrieved_chunk": "package primitives;\nimport domain.Point;\npublic class Rectangle extends Quadrilateral {\n public Rectangle(Point vertex1, Point vertex2) {\n super(\n vertex1, //0, 0\n new Point(vertex1.getX(), vertex2.getY()), //0, 10\n vertex2, //20, 10\n new Point(vertex2.getX(), vertex1.getY())// 20, 0\n );", "score": 0.8064633011817932 } ]
java
getX() * factor, point.getY() * factor + 50, factor, factor);
package canvas; import domain.Point; import domain.Shape; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.List; public class SwingCanvas implements Canvas { private final int width; private final int height; private final int factor; public SwingCanvas(int width, int height, int factor) { this.width = width; this.height = height; this.factor = factor; } private List<Point> allPoints = new ArrayList<>(); public void draw(Shape shape) { for (Point point: shape.getPoints()) { int x = point.getX(); int y = point.getY(); if (x >= 0 && y >= 0 && x < width && y < height) { allPoints.add(new Point(x, height - 1 - y)); } } } public void show() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Frame().setVisible(true); } }); } class Frame extends JFrame { Frame() { super("Graphic Canvas"); setSize(factor * width + 2*factor, factor * height + 50); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); } @Override public void paint(Graphics g) { super.paint(g); for (Point point : allPoints) { g
.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);
} } } }
src/main/java/canvas/SwingCanvas.java
dmitriyvolk-redrover-draw-b9b5e7d
[ { "filename": "src/main/java/sprites/House.java", "retrieved_chunk": " allShapes.add(new Rectangle(new Point(17, 0), new Point(22, 12))); //door\n allShapes.add(new Square(new Point(5, 10), 5)); //window\n allShapes.add(new Line(new Point(0, 20), new Point(12, 25)));\n allShapes.add(new Line(new Point(12, 25), new Point(26, 20)));\n return allShapes;\n }\n @Override\n public List<Point> getPoints() {\n List<Point> originalPoints = super.getPoints();\n return new MoveBy(lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints();", "score": 0.8285878896713257 }, { "filename": "src/main/java/Main.java", "retrieved_chunk": " Canvas canvas = new SwingCanvas(80, 70, 10);\n House house1 = new House(new Point(1, 1));\n Shape house2 = new House(new Point(0, 0)) //House\n .transform(new MirrorOverX(26)) // GenericShape\n .transform(new MoveBy(5, 3)); //GenericShape - 2\n Shape landscape = house1.combineWith(house2)\n .transform(new MirrorOverX(20));\n canvas.draw(landscape);\n canvas.show();\n }", "score": 0.8259785771369934 }, { "filename": "src/main/java/canvas/TextCanvas.java", "retrieved_chunk": " }\n }\n public void draw(Shape shape) {\n for (Point point : shape.getPoints()) {\n set(point.getX(), point.getY());\n }\n }\n private void set(int x, int y) {\n if (x >= 0 && y >= 0 && x < width && y < height) {\n pixels[y][x] = new Pixel(true);", "score": 0.8178220987319946 }, { "filename": "src/main/java/Main.java", "retrieved_chunk": "import canvas.*;\nimport domain.Point;\nimport domain.Shape;\nimport primitives.*;\nimport sprites.House;\nimport transformations.MirrorOverX;\nimport transformations.MoveBy;\npublic class Main {\n public static void main(String[] args) {\n// Canvas canvas = new TextCanvas(60, 30);", "score": 0.8098894953727722 }, { "filename": "src/main/java/primitives/Rectangle.java", "retrieved_chunk": "package primitives;\nimport domain.Point;\npublic class Rectangle extends Quadrilateral {\n public Rectangle(Point vertex1, Point vertex2) {\n super(\n vertex1, //0, 0\n new Point(vertex1.getX(), vertex2.getY()), //0, 10\n vertex2, //20, 10\n new Point(vertex2.getX(), vertex1.getY())// 20, 0\n );", "score": 0.8069090843200684 } ]
java
.drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor);
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.handler.TenantLineHandler; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import com.github.deeround.jdbc.plus.util.CollectionUtils; import com.github.deeround.jdbc.plus.util.ExceptionUtils; import com.github.deeround.jdbc.plus.util.StringPool; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.update.Update; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * @author hubin * @since 3.4.0 */ public class TenantLineInterceptor extends BaseMultiTableInterceptor implements IInterceptor { private final TenantLineHandler tenantLineHandler; public TenantLineInterceptor(TenantLineHandler tenantLineHandler) { this.tenantLineHandler = tenantLineHandler; } @Override public boolean supportMethod(MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) { for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) { methodInfo.resolveSql(i
, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));
} } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { return result; } @Override protected void processSelect(Select select, int index, String sql, Object obj) { final String whereSegment = (String) obj; this.processSelectBody(select.getSelectBody(), whereSegment); List<WithItem> withItemsList = select.getWithItemsList(); if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(withItem -> this.processSelectBody(withItem, whereSegment)); } } @Override protected void processInsert(Insert insert, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(insert.getTable().getName())) { // 过滤退出执行 return; } List<Column> columns = insert.getColumns(); if (CollectionUtils.isEmpty(columns)) { // 针对不给列名的insert 不处理 return; } String tenantIdColumn = this.tenantLineHandler.getTenantIdColumn(); if (this.tenantLineHandler.ignoreInsert(columns, tenantIdColumn)) { // 针对已给出租户列的insert 不处理 return; } columns.add(new Column(tenantIdColumn)); // fixed gitee pulls/141 duplicate update List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList(); if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { EqualsTo equalsTo = new EqualsTo(); equalsTo.setLeftExpression(new StringValue(tenantIdColumn)); equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); duplicateUpdateColumns.add(equalsTo); } Select select = insert.getSelect(); if (select != null) { this.processInsertSelect(select.getSelectBody(), (String) obj); } else if (insert.getItemsList() != null) { // fixed github pull/295 ItemsList itemsList = insert.getItemsList(); Expression tenantId = this.tenantLineHandler.getTenantId(); if (itemsList instanceof MultiExpressionList) { ((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(tenantId)); } else { ((ExpressionList) itemsList).getExpressions().add(tenantId); } } else { throw ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); } } /** * update 语句处理 */ @Override protected void processUpdate(Update update, int index, String sql, Object obj) { final Table table = update.getTable(); if (this.tenantLineHandler.ignoreTable(table.getName())) { // 过滤退出执行 return; } update.setWhere(this.andExpression(table, update.getWhere(), (String) obj)); } /** * delete 语句处理 */ @Override protected void processDelete(Delete delete, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(delete.getTable().getName())) { // 过滤退出执行 return; } delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj)); } /** * 处理 insert into select * <p> * 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了 * * @param selectBody SelectBody */ protected void processInsertSelect(SelectBody selectBody, final String whereSegment) { PlainSelect plainSelect = (PlainSelect) selectBody; FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof Table) { // fixed gitee pulls/141 duplicate update this.processPlainSelect(plainSelect, whereSegment); this.appendSelectItem(plainSelect.getSelectItems()); } else if (fromItem instanceof SubSelect) { SubSelect subSelect = (SubSelect) fromItem; this.appendSelectItem(plainSelect.getSelectItems()); this.processInsertSelect(subSelect.getSelectBody(), whereSegment); } } /** * 追加 SelectItem * * @param selectItems SelectItem */ protected void appendSelectItem(List<SelectItem> selectItems) { if (CollectionUtils.isEmpty(selectItems)) { return; } if (selectItems.size() == 1) { SelectItem item = selectItems.get(0); if (item instanceof AllColumns || item instanceof AllTableColumns) { return; } } selectItems.add(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn()))); } /** * 租户字段别名设置 * <p>tenantId 或 tableAlias.tenantId</p> * * @param table 表对象 * @return 字段 */ protected Column getAliasColumn(Table table) { StringBuilder column = new StringBuilder(); // todo 该起别名就要起别名,禁止修改此处逻辑 if (table.getAlias() != null) { column.append(table.getAlias().getName()).append(StringPool.DOT); } column.append(this.tenantLineHandler.getTenantIdColumn()); return new Column(column.toString()); } /** * 构建租户条件表达式 * * @param table 表对象 * @param where 当前where条件 * @param whereSegment 所属Mapper对象全路径(在原租户拦截器功能中,这个参数并不需要参与相关判断) * @return 租户条件表达式 * @see BaseMultiTableInterceptor#buildTableExpression(Table, Expression, String) */ @Override public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) { if (this.tenantLineHandler.ignoreTable(table.getName())) { return null; } return new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java", "retrieved_chunk": " if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;\n }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) {\n for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) {\n methodInfo.resolveSql(i, this.changeTable(methodInfo.getActionInfo().getBatchSql()[i]));", "score": 0.9679974317550659 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/config/MyStatInterceptor.java", "retrieved_chunk": " public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n return IInterceptor.super.supportMethod(methodInfo);\n }\n /**\n * SQL执行前方法(主要用于对SQL进行修改)\n */\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n log.info(\"执行SQL开始时间:{}\", LocalDateTime.now());\n log.info(\"原始SQL:{}\", Arrays.toString(methodInfo.getActionInfo().getBatchSql()));", "score": 0.9167760610580444 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " log.debug(\"origin sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"origin parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n //逻辑处理(核心方法:主要处理SQL和SQL参数)\n if (this.interceptors != null && this.interceptors.size() > 0) {\n for (IInterceptor interceptor : this.interceptors) {\n if (interceptor.supportMethod(methodInfo)) {\n interceptor.beforePrepare(methodInfo, jdbcTemplate);\n //插件允许修改原始SQL以及入参\n if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) {\n //回写参数", "score": 0.9047442078590393 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java", "retrieved_chunk": " }\n @Override\n public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) {\n Page<Object> localPage = PageHelper.getLocalPage();\n if (localPage == null) {\n return;\n }\n try {\n MethodActionInfo actionInfo = methodInfo.getActionInfo();\n Dialect dialect = PageHelper.getDialect(jdbcTemplate);", "score": 0.8893429040908813 }, { "filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java", "retrieved_chunk": " methodInvocation.setArguments(methodInfo.getArgs());\n }\n }\n }\n }\n log.debug(\"finish sql==>{}\", this.toStr(methodInfo.getActionInfo().getBatchSql()));\n log.debug(\"finish parameters==>{}\", this.toStr(methodInfo.getActionInfo().getBatchParameter()));\n Object result = methodInvocation.proceed();\n log.debug(\"origin result==>{}\", result);\n //逻辑处理", "score": 0.8743572235107422 } ]
java
, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null));
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.deeround.jdbc.plus.Interceptor; import com.github.deeround.jdbc.plus.handler.TenantLineHandler; import com.github.deeround.jdbc.plus.method.MethodInvocationInfo; import com.github.deeround.jdbc.plus.method.MethodType; import com.github.deeround.jdbc.plus.util.CollectionUtils; import com.github.deeround.jdbc.plus.util.ExceptionUtils; import com.github.deeround.jdbc.plus.util.StringPool; import net.sf.jsqlparser.expression.Expression; import net.sf.jsqlparser.expression.StringValue; import net.sf.jsqlparser.expression.operators.relational.EqualsTo; import net.sf.jsqlparser.expression.operators.relational.ExpressionList; import net.sf.jsqlparser.expression.operators.relational.ItemsList; import net.sf.jsqlparser.expression.operators.relational.MultiExpressionList; import net.sf.jsqlparser.schema.Column; import net.sf.jsqlparser.schema.Table; import net.sf.jsqlparser.statement.delete.Delete; import net.sf.jsqlparser.statement.insert.Insert; import net.sf.jsqlparser.statement.select.*; import net.sf.jsqlparser.statement.update.Update; import org.springframework.jdbc.core.JdbcTemplate; import java.util.List; /** * @author hubin * @since 3.4.0 */ public class TenantLineInterceptor extends BaseMultiTableInterceptor implements IInterceptor { private final TenantLineHandler tenantLineHandler; public TenantLineInterceptor(TenantLineHandler tenantLineHandler) { this.tenantLineHandler = tenantLineHandler; } @Override public boolean supportMethod(MethodInvocationInfo methodInfo) { if (!methodInfo.isSupport()) { return false; } if (MethodType.UPDATE.equals(methodInfo.getType()) || MethodType.QUERY.equals(methodInfo.getType())) { return true; } return false; } @Override public void beforePrepare(final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { if (methodInfo.getActionInfo() != null && methodInfo.getActionInfo().getBatchSql() != null) { for (int i = 0; i < methodInfo.getActionInfo().getBatchSql().length; i++) { methodInfo.resolveSql(i, this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null)); } } } @Override public Object beforeFinish(Object result, final MethodInvocationInfo methodInfo, JdbcTemplate jdbcTemplate) { return result; } @Override protected void processSelect(Select select, int index, String sql, Object obj) { final String whereSegment = (String) obj; this.processSelectBody(select.getSelectBody(), whereSegment); List<WithItem> withItemsList = select.getWithItemsList(); if (!CollectionUtils.isEmpty(withItemsList)) { withItemsList.forEach(withItem -> this.processSelectBody(withItem, whereSegment)); } } @Override protected void processInsert(Insert insert, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(insert.getTable().getName())) { // 过滤退出执行 return; } List<Column> columns = insert.getColumns(); if (CollectionUtils.isEmpty(columns)) { // 针对不给列名的insert 不处理 return; } String tenantIdColumn = this.tenantLineHandler.getTenantIdColumn(); if (this.tenantLineHandler.ignoreInsert(columns, tenantIdColumn)) { // 针对已给出租户列的insert 不处理 return; } columns.add(new Column(tenantIdColumn)); // fixed gitee pulls/141 duplicate update List<Expression> duplicateUpdateColumns = insert.getDuplicateUpdateExpressionList(); if (CollectionUtils.isNotEmpty(duplicateUpdateColumns)) { EqualsTo equalsTo = new EqualsTo(); equalsTo.setLeftExpression(new StringValue(tenantIdColumn)); equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); duplicateUpdateColumns.add(equalsTo); } Select select = insert.getSelect(); if (select != null) { this.processInsertSelect(select.getSelectBody(), (String) obj); } else if (insert.getItemsList() != null) { // fixed github pull/295 ItemsList itemsList = insert.getItemsList(); Expression tenantId = this.tenantLineHandler.getTenantId(); if (itemsList instanceof MultiExpressionList) { ((MultiExpressionList) itemsList).getExpressionLists().forEach(el -> el.getExpressions().add(tenantId)); } else { ((ExpressionList) itemsList).getExpressions().add(tenantId); } } else { throw
ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
} } /** * update 语句处理 */ @Override protected void processUpdate(Update update, int index, String sql, Object obj) { final Table table = update.getTable(); if (this.tenantLineHandler.ignoreTable(table.getName())) { // 过滤退出执行 return; } update.setWhere(this.andExpression(table, update.getWhere(), (String) obj)); } /** * delete 语句处理 */ @Override protected void processDelete(Delete delete, int index, String sql, Object obj) { if (this.tenantLineHandler.ignoreTable(delete.getTable().getName())) { // 过滤退出执行 return; } delete.setWhere(this.andExpression(delete.getTable(), delete.getWhere(), (String) obj)); } /** * 处理 insert into select * <p> * 进入这里表示需要 insert 的表启用了多租户,则 select 的表都启动了 * * @param selectBody SelectBody */ protected void processInsertSelect(SelectBody selectBody, final String whereSegment) { PlainSelect plainSelect = (PlainSelect) selectBody; FromItem fromItem = plainSelect.getFromItem(); if (fromItem instanceof Table) { // fixed gitee pulls/141 duplicate update this.processPlainSelect(plainSelect, whereSegment); this.appendSelectItem(plainSelect.getSelectItems()); } else if (fromItem instanceof SubSelect) { SubSelect subSelect = (SubSelect) fromItem; this.appendSelectItem(plainSelect.getSelectItems()); this.processInsertSelect(subSelect.getSelectBody(), whereSegment); } } /** * 追加 SelectItem * * @param selectItems SelectItem */ protected void appendSelectItem(List<SelectItem> selectItems) { if (CollectionUtils.isEmpty(selectItems)) { return; } if (selectItems.size() == 1) { SelectItem item = selectItems.get(0); if (item instanceof AllColumns || item instanceof AllTableColumns) { return; } } selectItems.add(new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn()))); } /** * 租户字段别名设置 * <p>tenantId 或 tableAlias.tenantId</p> * * @param table 表对象 * @return 字段 */ protected Column getAliasColumn(Table table) { StringBuilder column = new StringBuilder(); // todo 该起别名就要起别名,禁止修改此处逻辑 if (table.getAlias() != null) { column.append(table.getAlias().getName()).append(StringPool.DOT); } column.append(this.tenantLineHandler.getTenantIdColumn()); return new Column(column.toString()); } /** * 构建租户条件表达式 * * @param table 表对象 * @param where 当前where条件 * @param whereSegment 所属Mapper对象全路径(在原租户拦截器功能中,这个参数并不需要参与相关判断) * @return 租户条件表达式 * @see BaseMultiTableInterceptor#buildTableExpression(Table, Expression, String) */ @Override public Expression buildTableExpression(final Table table, final Expression where, final String whereSegment) { if (this.tenantLineHandler.ignoreTable(table.getName())) { return null; } return new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); } }
jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java
deeround-jdbc-plus-a0dcdfd
[ { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " @Override\n public void setValues(PreparedStatement ps) throws SQLException {\n ps.setString(1, \"test_tenant_4\");\n }\n }, new RowCallbackHandler() {\n @Override\n public void processRow(ResultSet rs) throws SQLException {\n log.info(\"rowNum==>{}\", rowNum[0]++);\n query.add(TestAllServiceImpl.toMap(rs));\n }", "score": 0.8146686553955078 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/JdbcTemplateTestService.java", "retrieved_chunk": " public void insert() {\n this.jdbcTemplate.update(\"insert into test_user(id,name) values('1','wangwu')\");\n //最终执行SQL:insert into test_user(id,name,tenant_id) values('1','wangwu','test_tenant_1')\n }\n public void delete() {\n this.jdbcTemplate.update(\"delete from test_user where id='1'\");\n //最终执行SQL:delete from test_user where id='1' and tenant_id='test_tenant_1'\n }\n public void update() {\n this.jdbcTemplate.update(\"update test_user set name='lisi' where id='1'\");", "score": 0.8003249168395996 }, { "filename": "jdbc-plus-samples/src/test/java/com/github/deeround/jdbc/plus/samples/Tests.java", "retrieved_chunk": " }\n @Test\n void testTenantInsert() {\n this.jdbcTemplateTestService.insert();\n }\n @Test\n void testTenantUpdate() {\n this.jdbcTemplateTestService.update();\n }\n @Test", "score": 0.8001573085784912 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {\n @Override\n public void setValues(PreparedStatement ps, int i) throws SQLException {\n if (i >= 10) {\n return;\n }\n ps.setString(1, String.valueOf(i));\n ps.setString(2, UUID.randomUUID().toString().replaceAll(\"-\", \"\"));\n }\n @Override", "score": 0.797908365726471 }, { "filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java", "retrieved_chunk": " List<Object> query = this.jdbcTemplate.query(sql, new PreparedStatementSetter() {\n @Override\n public void setValues(PreparedStatement ps) throws SQLException {\n ps.setString(1, \"test_tenant_4\");\n }\n }, new RowMapper<Object>() {\n @Override\n public Object mapRow(ResultSet rs, int rowNum) throws SQLException {\n log.info(\"rowNum==>{}\", rowNum);\n return TestAllServiceImpl.toMap(rs);", "score": 0.7965792417526245 } ]
java
ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId");
package com.deshaw.python; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A more Pythonic version of the map: throws exceptions when trying to access * missing keys. */ public class Dict extends HashMap<Object,Object> { /** * Exception thrown when the key is missing from the dictionary. */ public static class MissingKeyException extends RuntimeException { private static final long serialVersionUID = -963449382298809244L; /** * Constructor. * * @param message The exception message. */ public MissingKeyException(String message) { super(message); } } // ---------------------------------------------------------------------- private static final long serialVersionUID = 3896936112974357004L; /** * Return the value to which the specified key is mapped. * * @throws MissingKeyException if the key is not in the dict. */ @Override public Object get(final Object key) throws MissingKeyException { final Object v = super.get(key); if (v != null) { return v; } if (containsKey(key)) { return null; } throw new MissingKeyException("Missing key '" + key + "'"); } /** * Return the value to which the specified key is mapped or the specified * default value if the key is not in the dict. * * @param <T> The type of the object to get. * @param key The key to use for the lookup. * @param dflt The value to return if no match was found for the key. * * @return the element for the given key. * * @throws ClassCastException if any associated value was not the same time * as the given default. */ @SuppressWarnings("unchecked") public <T> T get(final Object key, final T dflt) { final Object v = super.get(key); if (v != null) { return (T) v; } if (containsKey(key)) { return null; } return dflt; } /** * Get the {@code int} value corresponding to the given key. * * @param key The key to use for the lookup. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public int getInt(Object key) { return ((Number) get(key)).intValue(); } /** * Get the {@code int} value corresponding to the given key, or the default * value if it doesn't exist. * * @param key The key to use for the lookup. * @param dflt The value to return if no match was found for the key. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public int getInt(Object key, int dflt) { return containsKey(key) ? getInt(key) : dflt; } /** * Get the {@code long} value corresponding to the given key. * * @param key The key to use for the lookup. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public long getLong(Object key) { return ((Number) get(key)).longValue(); } /** * Get the {@code long} value corresponding to the given key, or the default * value if it doesn't exist. * * @param key The key to use for the lookup. * @param dflt The value to return if no match was found for the key. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public long getLong(Object key, long dflt) { return containsKey(key) ? getLong(key) : dflt; } /** * Get the {@code double} value corresponding to the given key. * * @param key The key to use for the lookup. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public double getDouble(Object key) { return ((Number) get(key)).doubleValue(); } /** * Get the {@code double} value corresponding to the given key, or the default * value if it doesn't exist. * * @param key The key to use for the lookup. * @param dflt The value to return if no match was found for the key. * * @return the value associated with the given key. * * @throws ClassCastException if the associated value was not numeric. */ public double getDouble(Object key, double dflt) { return containsKey(key) ? getDouble(key) : dflt; } /** * Get the {@link List} value corresponding to the given key. * * @param key The key to use for the lookup. * * @return the value associated with the given key, if any. * * @throws ClassCastException if the associated value was not a {@link List}. */ public List<?> getList(Object key) { return (List<?>) get(key); } /** * Return the value to which the key is mapped as a list of * strings. Non-null entries are converted to strings by calling * {@link String#valueOf(Object)}, and null entries are left * unchanged. * * @param key The key to use for the lookup. * * @return the value associated with the given key, if any. * * @throws ClassCastException if the associated value was not a {@link List}. */ @SuppressWarnings("unchecked") public List<String> getStringList(Object key) { final List<?> rawList = getList(key); if (rawList == null || rawList.isEmpty()) { return (List<String>)rawList; } final List<String> stringList = new ArrayList<>(); for (Object raw : rawList) { stringList.add((raw != null) ? String.valueOf(raw) : null); } return stringList; } /** * Return the {@link NumpyArray} corresponding to the given key. * * @param key The key to use for the lookup. * * @return the value associated with the given key, if any. * * @throws ClassCastException if the associated value was not a * {@link NumpyArray}. */ public NumpyArray getArray(Object key) { return (NumpyArray) get(key); } /** * Return the {@link NumpyArray} corresponding to the given key and validate * its dimensions. * * <p>See also {@link NumpyArray#validateShape(String, int...)}. * * @param key The key to use for the lookup. * @param expectedShape The expected shape of the return value. * * @return the value associated with the given key, if any. * * @throws ClassCastException if the associated value was not a * {@link NumpyArray}. */ public NumpyArray getArray(Object key, int... expectedShape) { NumpyArray array = getArray(key);
array.validateShape(String.valueOf(key), expectedShape);
return array; } /** * {@inheritDoc} */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append('{'); boolean first = true; for (Object rawEntry: entrySet()) { Map.Entry e = (Map.Entry) rawEntry; if (!first) { sb.append(','); } first = false; sb.append(' '); Object k = e.getKey(); Object v = e.getValue(); sb.append(stringify(k)).append(": ").append(stringify(v)); } if (!first) { sb.append(' '); } sb.append('}'); return sb.toString(); } /** * Wrap strings in quotes, but defer to {@link String#valueOf} for * other types of objects. * * @param o The object to turn into a string. */ private String stringify(Object o) { return (o instanceof CharSequence) ? "'" + o + "'" : String.valueOf(o); } }
java/src/main/java/com/deshaw/python/Dict.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " // Validate the key before we use it\n assertKeyCorrectness(key);\n // Keep walking down until we get to the penultimate array\n Object array = myArray;\n for (int i=0; i < key.length-1; i++) {\n final Object k = key[i];\n if (k instanceof Number) {\n final int index = ((Number)k).intValue();\n try {\n array = Array.get(value, ((Number)k).intValue());", "score": 0.8295294046401978 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " // Validate the key before we use it\n assertKeyCorrectness(key);\n // Keep walking down and attempt to give back whatever we find for\n // the key\n Object value = myArray;\n for (Object k : key) {\n if (k instanceof Number) {\n final int index = ((Number)k).intValue();\n try {\n value = Array.get(value, index);", "score": 0.8258664011955261 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " /**\n * {@inheritDoc}\n */\n @Override\n @GenericReturnType\n public Object __getitem__(final Object[] key)\n throws ArrayIndexOutOfBoundsException,\n IllegalArgumentException,\n NullPointerException\n {", "score": 0.8184612989425659 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " * <p>Implemenations of this method should include the\n * {@link GenericReturnType} annotation in their signature so that the\n * Python side sees the right type, and not just {@link Object}.\n *\n * @param key The Python-style lookup key.\n *\n * @return The value which was found, if any.\n */\n @GenericReturnType\n public Object __getitem__(final Object[] key);", "score": 0.8103901743888855 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " * Check that a key is correct.\n */\n private void assertKeyCorrectness(final Object[] key)\n {\n // Check key correctness\n if (key == null) {\n throw new NullPointerException(\"Given a null key\");\n }\n if (key.length > myNumDims) {\n throw new ArrayIndexOutOfBoundsException(", "score": 0.7898935675621033 } ]
java
array.validateShape(String.valueOf(key), expectedShape);
package com.easyhome.common.feign; import com.easyhome.common.utils.GrayscaleConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * 打印请求头灰度参数拦截器 * @author wangshufeng */ @Slf4j public class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY); if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) { Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); log.info("接收到的请求头信息:{}={}", name, value); } } } Map<String,String> param=new HashMap<>(8); //获取所有灰度参数值设置到ThreadLocal,以便传值 for (GrayHeaderParam item:GrayHeaderParam.values()) { String hParam = request.getHeader(item.getValue()); if(!StringUtils.isEmpty(hParam)){
param.put(item.getValue(), hParam);
} } GrayParamHolder.putValues(param); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { //清除灰度ThreadLocal GrayParamHolder.clearValue(); } }
src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8550318479537964 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " }**/\n String printLogFlg = attributes.get(GrayscaleConstant.PRINT_HEADER_LOG_KEY);\n if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) {\n requestTemplate.header(GrayscaleConstant.PRINT_HEADER_LOG_KEY, printLogFlg);\n log.info(\"feign传递请求头信息:{}={}\", GrayscaleConstant.HEADER_KEY, version);\n }\n }\n }\n}", "score": 0.8531203866004944 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " for (Map.Entry<String,String> item:map.entrySet()){\n paramMap.put(item.getKey(),item.getValue());\n }\n }\n }\n /**\n * 清空线程参数\n */\n public static void clearValue() {\n GrayParamHolder.paramLocal.remove();", "score": 0.8440079689025879 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " * @return\n */\n public static Map<String, String> getGrayMap() {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if(paramMap==null){\n paramMap=new HashMap<>(8);\n if(GrayUtil.isGrayPod()){\n paramMap.put(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n paramMap.put(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n GrayParamHolder.paramLocal.set(paramMap);", "score": 0.8435661792755127 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " * feign传递请求头信息拦截器\n *\n * @author wangshufeng\n */\n@Slf4j\n@Configuration\npublic class FeignTransmitHeadersRequestInterceptor implements RequestInterceptor {\n @Override\n public void apply(RequestTemplate requestTemplate) {\n Map<String,String> attributes=GrayParamHolder.getGrayMap();", "score": 0.8380895853042603 } ]
java
param.put(item.getValue(), hParam);
package com.easyhome.common.feign; import com.easyhome.common.utils.GrayscaleConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * 打印请求头灰度参数拦截器 * @author wangshufeng */ @Slf4j public class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY); if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) { Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); log.info("接收到的请求头信息:{}={}", name, value); } } } Map<String,String> param=new HashMap<>(8); //获取所有灰度参数值设置到ThreadLocal,以便传值 for (GrayHeaderParam item:GrayHeaderParam.values()) { String hParam = request.getHeader(item.getValue()); if(!StringUtils.isEmpty(hParam)){ param.put(item.getValue(), hParam); } }
GrayParamHolder.putValues(param);
return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { //清除灰度ThreadLocal GrayParamHolder.clearValue(); } }
src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " * @return\n */\n public static Map<String, String> getGrayMap() {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if(paramMap==null){\n paramMap=new HashMap<>(8);\n if(GrayUtil.isGrayPod()){\n paramMap.put(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n paramMap.put(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n GrayParamHolder.paramLocal.set(paramMap);", "score": 0.8902729749679565 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8807222843170166 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " for (Map.Entry<String,String> item:map.entrySet()){\n paramMap.put(item.getKey(),item.getValue());\n }\n }\n }\n /**\n * 清空线程参数\n */\n public static void clearValue() {\n GrayParamHolder.paramLocal.remove();", "score": 0.8774471282958984 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayHeaderParam.java", "retrieved_chunk": "package com.easyhome.common.feign;\nimport com.easyhome.common.utils.GrayscaleConstant;\n/**\n * 异步线程拷贝灰度灰度环境信息枚举\n * @author wangshufeng\n */\npublic enum GrayHeaderParam {\n HEADER_KEY(GrayscaleConstant.HEADER_KEY),\n PRINT_HEADER_LOG_KEY(GrayscaleConstant.PRINT_HEADER_LOG_KEY),\n USER_ID(GrayscaleConstant.USER_ID),", "score": 0.8669705390930176 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayscaleConstant.java", "retrieved_chunk": " public static final String PRINT_HEADER_LOG_KEY = \"print_header_log\";\n /**\n * http请求头灰度标识参数名\n */\n public static final String HEADER_KEY = \"release-version\";\n /**\n * http请求头灰度标识参数值\n */\n public static final String HEADER_VALUE = \"grayscale\";\n /**", "score": 0.8528819680213928 } ]
java
GrayParamHolder.putValues(param);
package com.easyhome.common.nacos.ribbon; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.ribbon.ExtendBalancer; import com.alibaba.cloud.nacos.ribbon.NacosServer; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.easyhome.common.utils.GrayUtil; import com.easyhome.common.utils.GrayscaleConstant; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * nacos自定义负载策略 * * @author wangshufeng */ @Slf4j public class NacosRule extends AbstractLoadBalancerRule { @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; @Override public Server choose(Object key) { try { String clusterName = this.nacosDiscoveryProperties.getClusterName(); DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); String name = loadBalancer.getName(); NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); List<Instance> instances = namingService.selectInstances(name, true); instances = this.getGrayFilterInstances(instances, key); if (CollectionUtils.isEmpty(instances)) { log.warn("no instance in service {}", name); return null; } List<Instance> instancesToChoose = instances; if (StringUtils.isNotBlank(clusterName)) { List<Instance> sameClusterInstances = instances.stream() .filter(instance -> Objects.equals(clusterName, instance.getClusterName())) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(sameClusterInstances)) { instancesToChoose = sameClusterInstances; } else { log.warn( "A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}", name, clusterName, instances); } } Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose); return new NacosServer(instance); } catch (Exception e) { log.warn("NacosRule error", e); return null; } } /** * 根据当前请求是否为灰度过滤服务实例列表 * * @param instances * @return List<Instance> */ private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) { if (CollectionUtils.isEmpty(instances)) { return instances; } else { //是否灰度请求 Boolean isGrayRequest; String grayGroup=GrayscaleConstant.HEADER_VALUE; //兼容gateway传值方式,gateway是nio是通过key来做负载实例识别的 if (Objects.nonNull(key) && !GrayscaleConstant.DEFAULT.equals(key)) { isGrayRequest = true; if(isGrayRequest){ grayGroup=(String)key; } } else { isGrayRequest
= GrayUtil.isGrayRequest();
if(isGrayRequest){ grayGroup=GrayUtil.requestGroup(); } } List<Instance> prodInstance=new ArrayList<>(); List<Instance> grayInstance=new ArrayList<>(); for(Instance item:instances){ Map<String, String> metadata = item.getMetadata(); if (metadata.isEmpty() || !GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) { prodInstance.add(item); } if (isGrayRequest) { if (!metadata.isEmpty() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) { if(Objects.equals(grayGroup,metadata.get(GrayscaleConstant.GRAY_GROUP))){ grayInstance.add(item); } } } } if(!isGrayRequest||CollectionUtils.isEmpty(grayInstance)){ return prodInstance; } return grayInstance; } } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } }
src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " }\n }\n /**\n * 获取当前请求分组\n * @return\n */\n public static String requestGroup(){\n Map<String,String> attributes= GrayParamHolder.getGrayMap();\n String groupFlag =attributes.get(GrayscaleConstant.HEADER_KEY);\n if (groupFlag!=null&&!\"\".equals(groupFlag)) {", "score": 0.8771312832832336 }, { "filename": "src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java", "retrieved_chunk": " Map<String,String> param=new HashMap<>(8);\n //获取所有灰度参数值设置到ThreadLocal,以便传值\n for (GrayHeaderParam item:GrayHeaderParam.values()) {\n String hParam = request.getHeader(item.getValue());\n if(!StringUtils.isEmpty(hParam)){\n param.put(item.getValue(), hParam);\n }\n }\n GrayParamHolder.putValues(param);\n return true;", "score": 0.8724496960639954 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8716391324996948 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " return topicGrayName(topicName);\n } else {\n return topicName;\n }\n }\n /**\n * 是否为灰度请求\n * @return Boolean\n */\n public static Boolean isGrayRequest(){", "score": 0.8557772636413574 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " /**\n * 获取运行实例的灰度分组\n * @return\n */\n public static String podGroup() {\n String groupFlag = System.getProperty(GrayscaleConstant.GRAY_GROUP);\n if (groupFlag!=null&&!\"\".equals(groupFlag)) {\n return groupFlag;\n } else {\n return GrayscaleConstant.HEADER_VALUE;", "score": 0.8518315553665161 } ]
java
= GrayUtil.isGrayRequest();
package com.easyhome.common.feign; import com.alibaba.ttl.TransmittableThreadLocal; import com.easyhome.common.utils.GrayUtil; import com.easyhome.common.utils.GrayscaleConstant; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * 异步线程间参数传递 * * @author wangshufeng */ public class GrayParamHolder { /** * 在Java的启动参数加上:-javaagent:path/to/transmittable-thread-local-2.x.y.jar。 * <p> * 注意: * <p> * 如果修改了下载的TTL的Jar的文件名(transmittable-thread-local-2.x.y.jar),则需要自己手动通过-Xbootclasspath JVM参数来显式配置。 * 比如修改文件名成ttl-foo-name-changed.jar,则还需要加上Java的启动参数:-Xbootclasspath/a:path/to/ttl-foo-name-changed.jar。 * 或使用v2.6.0之前的版本(如v2.5.1),则也需要自己手动通过-Xbootclasspath JVM参数来显式配置(就像TTL之前的版本的做法一样)。 * 加上Java的启动参数:-Xbootclasspath/a:path/to/transmittable-thread-local-2.5.1.jar。 */ private static ThreadLocal<Map<String, String>> paramLocal = new TransmittableThreadLocal(); /** * 获取单个参数值 * * @param key * @return */ public static String getValue(String key) { Map<String, String> paramMap = GrayParamHolder.paramLocal.get(); if (Objects.nonNull(paramMap) && !paramMap.isEmpty()) { return paramMap.get(key); } return null; } /** * 获取所有参数 * * @return */ public static Map<String, String> getGrayMap() { Map<String, String> paramMap = GrayParamHolder.paramLocal.get(); if(paramMap==null){ paramMap=new HashMap<>(8);
if(GrayUtil.isGrayPod()){
paramMap.put(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE); paramMap.put(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE); GrayParamHolder.paramLocal.set(paramMap); } } return paramMap; } /** * 设置单个参数 * * @param key * @param value */ public static void putValue(String key, String value) { Map<String, String> paramMap = GrayParamHolder.paramLocal.get(); if (Objects.isNull(paramMap) || paramMap.isEmpty()) { paramMap = new HashMap<>(6); GrayParamHolder.paramLocal.set(paramMap); } paramMap.put(key, value); } /** * 设置单多个参数 * * @param map */ public static void putValues(Map<String,String> map) { Map<String, String> paramMap = GrayParamHolder.paramLocal.get(); if (Objects.isNull(paramMap) || paramMap.isEmpty()) { paramMap = new HashMap<>(6); GrayParamHolder.paramLocal.set(paramMap); } if(Objects.nonNull(map)&&!map.isEmpty()){ for (Map.Entry<String,String> item:map.entrySet()){ paramMap.put(item.getKey(),item.getValue()); } } } /** * 清空线程参数 */ public static void clearValue() { GrayParamHolder.paramLocal.remove(); } }
src/main/java/com/easyhome/common/feign/GrayParamHolder.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java", "retrieved_chunk": " Map<String,String> param=new HashMap<>(8);\n //获取所有灰度参数值设置到ThreadLocal,以便传值\n for (GrayHeaderParam item:GrayHeaderParam.values()) {\n String hParam = request.getHeader(item.getValue());\n if(!StringUtils.isEmpty(hParam)){\n param.put(item.getValue(), hParam);\n }\n }\n GrayParamHolder.putValues(param);\n return true;", "score": 0.858605146408081 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayHeaderParam.java", "retrieved_chunk": "package com.easyhome.common.feign;\nimport com.easyhome.common.utils.GrayscaleConstant;\n/**\n * 异步线程拷贝灰度灰度环境信息枚举\n * @author wangshufeng\n */\npublic enum GrayHeaderParam {\n HEADER_KEY(GrayscaleConstant.HEADER_KEY),\n PRINT_HEADER_LOG_KEY(GrayscaleConstant.PRINT_HEADER_LOG_KEY),\n USER_ID(GrayscaleConstant.USER_ID),", "score": 0.8239235877990723 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " /**\n * 获取运行实例的灰度分组\n * @return\n */\n public static String podGroup() {\n String groupFlag = System.getProperty(GrayscaleConstant.GRAY_GROUP);\n if (groupFlag!=null&&!\"\".equals(groupFlag)) {\n return groupFlag;\n } else {\n return GrayscaleConstant.HEADER_VALUE;", "score": 0.8207743167877197 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " Map<String,String> attributes= GrayParamHolder.getGrayMap();\n String releaseVersion=attributes.get(GrayscaleConstant.HEADER_KEY);\n if (Objects.nonNull(releaseVersion)&&!\"\".equals(releaseVersion)) {\n return true;\n }\n return false;\n }\n /**\n * 当前环境是否为灰度环境\n *", "score": 0.8194422721862793 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java", "retrieved_chunk": " private List<SubscriptionData> subscribes = new ArrayList<>();\n private ListenerStateEnum currentState;\n private Properties mqProperties;\n @Resource\n private ApplicationContext applicationContext;\n /**\n * 初始化消费者实例\n */\n public void initConsumer() {\n if (GrayUtil.isGrayPod()) {", "score": 0.8192280530929565 } ]
java
if(GrayUtil.isGrayPod()){
package com.easyhome.common.nacos; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.easyhome.common.event.GrayEventChangeEvent; import com.easyhome.common.rocketmq.ListenerStateEnum; import com.easyhome.common.utils.GrayUtil; import com.easyhome.common.utils.GrayscaleConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.List; /** * nacos自定义监听实现 * * @author wangshufeng */ @Slf4j @Component public class NacosEventListener implements EventListener { @Resource private ApplicationEventPublisher publisher; @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { this.mqInit(((NamingEvent) event).getInstances()); } } /** * 当前的mq监听状态 */ private static ListenerStateEnum listenerMqState; public synchronized void mqInit(List<Instance> instances) { ListenerStateEnum newState; //当前实例是灰度实例 if (GrayUtil.isGrayPod()) { newState = ListenerStateEnum.GRAYSCALE; } else { //判断当前服务有灰度实例 if (this.isHaveGray(instances)) { newState = ListenerStateEnum.PRODUCTION; } else { newState = ListenerStateEnum.TOGETHER; } } log.info("当前实例是否为灰度环境:{}", GrayUtil.isGrayPod()); log.
info("当前实例监听mq队列的状态:{
}", newState.getValue()); //防止重复初始化监听mq队列信息 if (!newState.equals(listenerMqState)) { listenerMqState = newState; publisher.publishEvent(new GrayEventChangeEvent(listenerMqState)); } } /** * 是否有灰度实例 * * @return */ private boolean isHaveGray(List<Instance> instances) { if (!CollectionUtils.isEmpty(instances)) { for (Instance instance : instances) { if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(instance.getMetadata().get(GrayscaleConstant.POD_GRAY))) { return true; } } } return false; } }
src/main/java/com/easyhome/common/nacos/NacosEventListener.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java", "retrieved_chunk": " }\n }\n @Override\n public void onApplicationEvent(GrayEventChangeEvent event) {\n ListenerStateEnum listenerStateEnum = (ListenerStateEnum) event.getSource();\n log.info(this.getClass().getName() + \"灰度环境变更:\" + listenerStateEnum.getValue());\n currentState = listenerStateEnum;\n if (ListenerStateEnum.PRODUCTION.equals(listenerStateEnum)) {\n initConsumerProduction();\n for (SubscriptionData item : subscribes) {", "score": 0.85787034034729 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java", "retrieved_chunk": "package com.easyhome.common.rocketmq;\nimport lombok.Getter;\n/**\n * 灰度发版队列监听状态\n *\n * @author wangshufeng\n */\n@Getter\npublic enum ListenerStateEnum {\n /**", "score": 0.8443330526351929 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java", "retrieved_chunk": " * 只监听生产环境队列\n */\n PRODUCTION(0, \"只监听生产环境队列\"),\n /**\n * 只监听灰度环境队列\n */\n GRAYSCALE(1, \"只监听灰度环境队列\"),\n /**\n * 同时监听生产和灰度环境队列\n */", "score": 0.8288515210151672 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java", "retrieved_chunk": " TOGETHER(2, \"同时监听生产和灰度环境队列\");\n /**\n * key\n */\n private Integer key;\n /**\n * value\n */\n private String value;\n ListenerStateEnum(Integer key, String value) {", "score": 0.8244422674179077 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java", "retrieved_chunk": " }\n }\n /**\n * 初始化灰度消费者实例\n */\n private void initConsumerGray() {\n if (consumerGray == null) {\n synchronized (this) {\n if (consumerGray == null) {\n if (Objects.isNull(mqProperties)) {", "score": 0.8198169469833374 } ]
java
info("当前实例监听mq队列的状态:{
package com.easyhome.common.nacos.ribbon; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.ribbon.ExtendBalancer; import com.alibaba.cloud.nacos.ribbon.NacosServer; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.easyhome.common.utils.GrayUtil; import com.easyhome.common.utils.GrayscaleConstant; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * nacos自定义负载策略 * * @author wangshufeng */ @Slf4j public class NacosRule extends AbstractLoadBalancerRule { @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; @Override public Server choose(Object key) { try { String clusterName = this.nacosDiscoveryProperties.getClusterName(); DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); String name = loadBalancer.getName(); NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); List<Instance> instances = namingService.selectInstances(name, true); instances = this.getGrayFilterInstances(instances, key); if (CollectionUtils.isEmpty(instances)) { log.warn("no instance in service {}", name); return null; } List<Instance> instancesToChoose = instances; if (StringUtils.isNotBlank(clusterName)) { List<Instance> sameClusterInstances = instances.stream() .filter(instance -> Objects.equals(clusterName, instance.getClusterName())) .collect(Collectors.toList()); if (!CollectionUtils.isEmpty(sameClusterInstances)) { instancesToChoose = sameClusterInstances; } else { log.warn( "A cross-cluster call occurs,name = {}, clusterName = {}, instance = {}", name, clusterName, instances); } } Instance instance = ExtendBalancer.getHostByRandomWeight2(instancesToChoose); return new NacosServer(instance); } catch (Exception e) { log.warn("NacosRule error", e); return null; } } /** * 根据当前请求是否为灰度过滤服务实例列表 * * @param instances * @return List<Instance> */ private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) { if (CollectionUtils.isEmpty(instances)) { return instances; } else { //是否灰度请求 Boolean isGrayRequest; String grayGroup=GrayscaleConstant.HEADER_VALUE; //兼容gateway传值方式,gateway是nio是通过key来做负载实例识别的 if (Objects.nonNull(key) && !GrayscaleConstant.DEFAULT.equals(key)) { isGrayRequest = true; if(isGrayRequest){ grayGroup=(String)key; } } else { isGrayRequest = GrayUtil.isGrayRequest(); if(isGrayRequest){ grayGroup
=GrayUtil.requestGroup();
} } List<Instance> prodInstance=new ArrayList<>(); List<Instance> grayInstance=new ArrayList<>(); for(Instance item:instances){ Map<String, String> metadata = item.getMetadata(); if (metadata.isEmpty() || !GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) { prodInstance.add(item); } if (isGrayRequest) { if (!metadata.isEmpty() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(metadata.get(GrayscaleConstant.POD_GRAY))) { if(Objects.equals(grayGroup,metadata.get(GrayscaleConstant.GRAY_GROUP))){ grayInstance.add(item); } } } } if(!isGrayRequest||CollectionUtils.isEmpty(grayInstance)){ return prodInstance; } return grayInstance; } } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { } }
src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " }\n }\n /**\n * 获取当前请求分组\n * @return\n */\n public static String requestGroup(){\n Map<String,String> attributes= GrayParamHolder.getGrayMap();\n String groupFlag =attributes.get(GrayscaleConstant.HEADER_KEY);\n if (groupFlag!=null&&!\"\".equals(groupFlag)) {", "score": 0.8736671209335327 }, { "filename": "src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java", "retrieved_chunk": " Map<String,String> param=new HashMap<>(8);\n //获取所有灰度参数值设置到ThreadLocal,以便传值\n for (GrayHeaderParam item:GrayHeaderParam.values()) {\n String hParam = request.getHeader(item.getValue());\n if(!StringUtils.isEmpty(hParam)){\n param.put(item.getValue(), hParam);\n }\n }\n GrayParamHolder.putValues(param);\n return true;", "score": 0.8503206372261047 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " return topicGrayName(topicName);\n } else {\n return topicName;\n }\n }\n /**\n * 是否为灰度请求\n * @return Boolean\n */\n public static Boolean isGrayRequest(){", "score": 0.8468365669250488 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8463736772537231 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " }\n return topicName.concat(GrayscaleConstant.GRAY_TOPIC_SUFFIX);\n }\n /**\n * 自动主题名称拼接灰度后缀\n * @param topicName\n * @return String\n */\n public static String autoTopicGrayName(String topicName) {\n if (isGrayRequest()) {", "score": 0.8410922288894653 } ]
java
=GrayUtil.requestGroup();
package com.easyhome.common.utils; import com.easyhome.common.feign.GrayParamHolder; import org.springframework.util.StringUtils; import java.util.Map; import java.util.Objects; /** * 灰度发布工具类 * * @author wangshufeng */ public class GrayUtil { /** * 主题名称拼接灰度后缀 * * @param topicName * @return String */ public static String topicGrayName(String topicName) { if (StringUtils.isEmpty(topicName)) { throw new NullPointerException("topicName为null"); } return topicName.concat(GrayscaleConstant.GRAY_TOPIC_SUFFIX); } /** * 自动主题名称拼接灰度后缀 * @param topicName * @return String */ public static String autoTopicGrayName(String topicName) { if (isGrayRequest()) { return topicGrayName(topicName); } else { return topicName; } } /** * 是否为灰度请求 * @return Boolean */ public static Boolean isGrayRequest(){ Map<String,
String> attributes= GrayParamHolder.getGrayMap();
String releaseVersion=attributes.get(GrayscaleConstant.HEADER_KEY); if (Objects.nonNull(releaseVersion)&&!"".equals(releaseVersion)) { return true; } return false; } /** * 当前环境是否为灰度环境 * * @return boolean */ public static Boolean isGrayPod() { String grayFlg = System.getProperty(GrayscaleConstant.POD_GRAY); if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(grayFlg)) { return true; } else { return false; } } /** * 获取运行实例的灰度分组 * @return */ public static String podGroup() { String groupFlag = System.getProperty(GrayscaleConstant.GRAY_GROUP); if (groupFlag!=null&&!"".equals(groupFlag)) { return groupFlag; } else { return GrayscaleConstant.HEADER_VALUE; } } /** * 获取当前请求分组 * @return */ public static String requestGroup(){ Map<String,String> attributes= GrayParamHolder.getGrayMap(); String groupFlag =attributes.get(GrayscaleConstant.HEADER_KEY); if (groupFlag!=null&&!"".equals(groupFlag)) { return groupFlag; } else { return GrayscaleConstant.HEADER_VALUE; } } }
src/main/java/com/easyhome/common/utils/GrayUtil.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java", "retrieved_chunk": " Map<String,String> param=new HashMap<>(8);\n //获取所有灰度参数值设置到ThreadLocal,以便传值\n for (GrayHeaderParam item:GrayHeaderParam.values()) {\n String hParam = request.getHeader(item.getValue());\n if(!StringUtils.isEmpty(hParam)){\n param.put(item.getValue(), hParam);\n }\n }\n GrayParamHolder.putValues(param);\n return true;", "score": 0.8668637275695801 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " * @return\n */\n public static Map<String, String> getGrayMap() {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if(paramMap==null){\n paramMap=new HashMap<>(8);\n if(GrayUtil.isGrayPod()){\n paramMap.put(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n paramMap.put(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n GrayParamHolder.paramLocal.set(paramMap);", "score": 0.8416475653648376 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8376479744911194 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayscaleConstant.java", "retrieved_chunk": " public static final String DEVICE_OS = \"deviceOs\";\n /**\n * 是否灰度实例\n */\n public static final String POD_GRAY=\"pod.gray\";\n /**\n * 灰度消息队列后缀\n */\n public static final String GRAY_TOPIC_SUFFIX=\"_gray\";\n /**", "score": 0.8347841501235962 }, { "filename": "src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java", "retrieved_chunk": "import java.util.Map;\n/**\n * 打印请求头灰度参数拦截器\n * @author wangshufeng\n */\n@Slf4j\npublic class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor {\n @Override\n public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY);", "score": 0.8262342214584351 } ]
java
String> attributes= GrayParamHolder.getGrayMap();
package com.easyhome.common.rocketmq; import com.aliyun.openservices.ons.api.Consumer; import com.aliyun.openservices.ons.api.MessageListener; import com.aliyun.openservices.ons.api.ONSFactory; import com.aliyun.openservices.ons.api.PropertyKeyConst; import com.easyhome.common.event.GrayEventChangeEvent; import com.easyhome.common.utils.GrayUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.util.StringUtils; import javax.annotation.PreDestroy; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Properties; /** * 灰度实例上下线事件处理基础类 * * @author wangshufeng */ @Slf4j public abstract class AbstractGrayEventListener implements ApplicationListener<GrayEventChangeEvent> { private Consumer consumer; private Consumer consumerGray; /** * 默认订阅tag规则 */ private static final String DEFAULT_SUB_EXPRESSION = "*"; private List<SubscriptionData> subscribes = new ArrayList<>(); private ListenerStateEnum currentState; private Properties mqProperties; @Resource private ApplicationContext applicationContext; /** * 初始化消费者实例 */ public void initConsumer() { if (GrayUtil.isGrayPod()) { initConsumerGray(); } else { initConsumerProduction(); } } /** * 初始化生产消费者实例 */ private void initConsumerProduction() { if (consumer == null) { synchronized (this) { if (consumer == null) { if (Objects.isNull(mqProperties)) { throw new NullPointerException("rocketMq配置信息未设置"); } else { consumer = ONSFactory.createConsumer(mqProperties); consumer.start(); } } } } } /** * 初始化灰度消费者实例 */ private void initConsumerGray() { if (consumerGray == null) { synchronized (this) { if (consumerGray == null) { if (Objects.isNull(mqProperties)) { throw new NullPointerException("rocketMq配置信息未设置"); } else { Properties grayProperties = new Properties(); grayProperties.putAll(mqProperties); grayProperties.setProperty(PropertyKeyConst.GROUP_ID, GrayUtil.topicGrayName(grayProperties.getProperty(PropertyKeyConst.GROUP_ID))); consumerGray = ONSFactory.createConsumer(grayProperties); consumerGray.start(); } } } } } @Override public void onApplicationEvent(GrayEventChangeEvent event) { ListenerStateEnum listenerStateEnum = (ListenerStateEnum) event.getSource(); log.info(this.getClass().
getName() + "灰度环境变更:" + listenerStateEnum.getValue());
currentState = listenerStateEnum; if (ListenerStateEnum.PRODUCTION.equals(listenerStateEnum)) { initConsumerProduction(); for (SubscriptionData item : subscribes) { if (Objects.nonNull(consumer)) { consumer.subscribe(item.getTopic(), item.getSubExpression(), item.getListener()); } } shutdownConsumerGray(); } if (ListenerStateEnum.TOGETHER.equals(listenerStateEnum)) { initConsumerProduction(); initConsumerGray(); for (SubscriptionData item : subscribes) { if (Objects.nonNull(consumer)) { consumer.subscribe(item.getTopic(), item.getSubExpression(), item.getListener()); } if (Objects.nonNull(consumerGray)) { consumerGray.subscribe(GrayUtil.topicGrayName(item.getTopic()), item.getSubExpression(), item.getListener()); } } } if (ListenerStateEnum.GRAYSCALE.equals(listenerStateEnum)) { initConsumerGray(); for (SubscriptionData item : subscribes) { if (Objects.nonNull(consumerGray)) { consumerGray.subscribe(GrayUtil.topicGrayName(item.getTopic()), item.getSubExpression(), item.getListener()); } } shutdownConsumerProduction(); } } /** * 添加订阅规则 * * @param topic 主题 * @param listenerClass 处理消息监听器类名称 * @return AbstractGrayEventListener */ public AbstractGrayEventListener subscribe(String topic, Class<? extends MessageListener> listenerClass) { return this.subscribe(topic, DEFAULT_SUB_EXPRESSION, listenerClass); } /** * 添加订阅规则 * * @param topic 主题 * @param subExpression 订阅tag规则 * @param listenerClass 处理消息监听器类名称 * @return AbstractGrayEventListener */ public AbstractGrayEventListener subscribe(String topic, String subExpression, Class<? extends MessageListener> listenerClass) { if (Objects.isNull(listenerClass)) { throw new NullPointerException("listenerClass信息未设置"); } MessageListener listener = applicationContext.getBean(listenerClass); if (Objects.isNull(listener)) { throw new NullPointerException(listenerClass.getName().concat("未找到实例对象")); } return this.subscribe(topic, subExpression, listener); } /** * 添加订阅规则 * * @param topic 主题 * @param listener 处理消息监听器 * @return AbstractGrayEventListener */ public AbstractGrayEventListener subscribe(String topic, MessageListener listener) { return this.subscribe(topic, DEFAULT_SUB_EXPRESSION, listener); } /** * 添加订阅规则 * * @param topic 主题 * @param subExpression 订阅tag规则 * @param listener 处理消息监听器 * @return AbstractGrayEventListener */ public AbstractGrayEventListener subscribe(String topic, String subExpression, MessageListener listener) { if (StringUtils.isEmpty(topic)) { throw new NullPointerException("topic信息未设置"); } if (StringUtils.isEmpty(subExpression)) { throw new NullPointerException("subExpression信息未设置"); } if (Objects.isNull(listener)) { throw new NullPointerException("listener信息未设置"); } if (listener instanceof GrayMessageListener) { subscribes.add(new SubscriptionData(topic, subExpression, listener)); } else { subscribes.add(new SubscriptionData(topic, subExpression, new GrayMessageListener(listener))); } return this; } /** * 设置RoketMq配置属性 * * @param mqProperties 配置属性 * @return AbstractGrayEventListener */ public AbstractGrayEventListener setMqProperties(Properties mqProperties) { this.mqProperties = mqProperties; return this; } /** * 销毁方法 */ @PreDestroy public void shutdown() { shutdownConsumerProduction(); shutdownConsumerGray(); } /** * 销毁生产消费实例 */ private void shutdownConsumerProduction() { if (Objects.nonNull(consumer)) { consumer.shutdown(); consumer = null; } } /** * 销毁灰度消费者实例 */ private void shutdownConsumerGray() { if (Objects.nonNull(consumerGray)) { consumerGray.shutdown(); consumerGray = null; } } }
src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/event/GrayEventChangeEvent.java", "retrieved_chunk": "package com.easyhome.common.event;\nimport com.easyhome.common.rocketmq.ListenerStateEnum;\nimport org.springframework.context.ApplicationEvent;\n/**\n * 灰度环境变更事件\n * @author wangshufeng\n */\npublic class GrayEventChangeEvent extends ApplicationEvent {\n /**\n * Create a new {@code ApplicationEvent}.", "score": 0.8839841485023499 }, { "filename": "src/main/java/com/easyhome/common/nacos/NacosEventListener.java", "retrieved_chunk": "package com.easyhome.common.nacos;\nimport com.alibaba.nacos.api.naming.listener.Event;\nimport com.alibaba.nacos.api.naming.listener.EventListener;\nimport com.alibaba.nacos.api.naming.listener.NamingEvent;\nimport com.alibaba.nacos.api.naming.pojo.Instance;\nimport com.easyhome.common.event.GrayEventChangeEvent;\nimport com.easyhome.common.rocketmq.ListenerStateEnum;\nimport com.easyhome.common.utils.GrayUtil;\nimport com.easyhome.common.utils.GrayscaleConstant;\nimport lombok.extern.slf4j.Slf4j;", "score": 0.8426018357276917 }, { "filename": "src/main/java/com/easyhome/common/nacos/NacosEventListener.java", "retrieved_chunk": " }\n /**\n * 当前的mq监听状态\n */\n private static ListenerStateEnum listenerMqState;\n public synchronized void mqInit(List<Instance> instances) {\n ListenerStateEnum newState;\n //当前实例是灰度实例\n if (GrayUtil.isGrayPod()) {\n newState = ListenerStateEnum.GRAYSCALE;", "score": 0.8277945518493652 }, { "filename": "src/main/java/com/easyhome/common/nacos/NacosEventListener.java", "retrieved_chunk": " } else {\n //判断当前服务有灰度实例\n if (this.isHaveGray(instances)) {\n newState = ListenerStateEnum.PRODUCTION;\n } else {\n newState = ListenerStateEnum.TOGETHER;\n }\n }\n log.info(\"当前实例是否为灰度环境:{}\", GrayUtil.isGrayPod());\n log.info(\"当前实例监听mq队列的状态:{}\", newState.getValue());", "score": 0.8261621594429016 }, { "filename": "src/main/java/com/easyhome/common/nacos/NacosEventListener.java", "retrieved_chunk": " //防止重复初始化监听mq队列信息\n if (!newState.equals(listenerMqState)) {\n listenerMqState = newState;\n publisher.publishEvent(new GrayEventChangeEvent(listenerMqState));\n }\n }\n /**\n * 是否有灰度实例\n *\n * @return", "score": 0.820766031742096 } ]
java
getName() + "灰度环境变更:" + listenerStateEnum.getValue());
package com.easyhome.common.feign; import com.easyhome.common.utils.GrayscaleConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * 打印请求头灰度参数拦截器 * @author wangshufeng */ @Slf4j public class TransmitHeaderPrintLogHanlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String printLogFlg = request.getHeader(GrayscaleConstant.PRINT_HEADER_LOG_KEY); if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) { Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); log.info("接收到的请求头信息:{}={}", name, value); } } } Map<String,String> param=new HashMap<>(8); //获取所有灰度参数值设置到ThreadLocal,以便传值 for (GrayHeaderParam item:GrayHeaderParam.values()) { String hParam = request.
getHeader(item.getValue());
if(!StringUtils.isEmpty(hParam)){ param.put(item.getValue(), hParam); } } GrayParamHolder.putValues(param); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { //清除灰度ThreadLocal GrayParamHolder.clearValue(); } }
src/main/java/com/easyhome/common/feign/TransmitHeaderPrintLogHanlerInterceptor.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " }**/\n String printLogFlg = attributes.get(GrayscaleConstant.PRINT_HEADER_LOG_KEY);\n if (log.isInfoEnabled() && GrayscaleConstant.STR_BOOLEAN_TRUE.equals(printLogFlg)) {\n requestTemplate.header(GrayscaleConstant.PRINT_HEADER_LOG_KEY, printLogFlg);\n log.info(\"feign传递请求头信息:{}={}\", GrayscaleConstant.HEADER_KEY, version);\n }\n }\n }\n}", "score": 0.8500316143035889 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " if (Objects.nonNull(attributes)) {\n //灰度标识传递\n String version = attributes.get(GrayscaleConstant.HEADER_KEY);\n if(!StringUtils.isEmpty(version)){\n requestTemplate.header(GrayscaleConstant.HEADER_KEY, version);\n }\n /** 自定义一些通用参数传递\n String deviceOs = attributes.get(GrayscaleConstant.DEVICE_OS);\n if(!StringUtils.isEmpty(deviceOs)){\n requestTemplate.header(GrayscaleConstant.DEVICE_OS, deviceOs);", "score": 0.8496418595314026 }, { "filename": "src/main/java/com/easyhome/common/feign/FeignTransmitHeadersRequestInterceptor.java", "retrieved_chunk": " * feign传递请求头信息拦截器\n *\n * @author wangshufeng\n */\n@Slf4j\n@Configuration\npublic class FeignTransmitHeadersRequestInterceptor implements RequestInterceptor {\n @Override\n public void apply(RequestTemplate requestTemplate) {\n Map<String,String> attributes=GrayParamHolder.getGrayMap();", "score": 0.8429434299468994 }, { "filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java", "retrieved_chunk": " * @return\n */\n public static Map<String, String> getGrayMap() {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if(paramMap==null){\n paramMap=new HashMap<>(8);\n if(GrayUtil.isGrayPod()){\n paramMap.put(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n paramMap.put(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n GrayParamHolder.paramLocal.set(paramMap);", "score": 0.8367270827293396 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayscaleConstant.java", "retrieved_chunk": " public static final String PRINT_HEADER_LOG_KEY = \"print_header_log\";\n /**\n * http请求头灰度标识参数名\n */\n public static final String HEADER_KEY = \"release-version\";\n /**\n * http请求头灰度标识参数值\n */\n public static final String HEADER_VALUE = \"grayscale\";\n /**", "score": 0.8360915184020996 } ]
java
getHeader(item.getValue());
package com.easyhome.common.nacos; import com.alibaba.nacos.api.naming.listener.Event; import com.alibaba.nacos.api.naming.listener.EventListener; import com.alibaba.nacos.api.naming.listener.NamingEvent; import com.alibaba.nacos.api.naming.pojo.Instance; import com.easyhome.common.event.GrayEventChangeEvent; import com.easyhome.common.rocketmq.ListenerStateEnum; import com.easyhome.common.utils.GrayUtil; import com.easyhome.common.utils.GrayscaleConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.util.List; /** * nacos自定义监听实现 * * @author wangshufeng */ @Slf4j @Component public class NacosEventListener implements EventListener { @Resource private ApplicationEventPublisher publisher; @Override public void onEvent(Event event) { if (event instanceof NamingEvent) { this.mqInit(((NamingEvent) event).getInstances()); } } /** * 当前的mq监听状态 */ private static ListenerStateEnum listenerMqState; public synchronized void mqInit(List<Instance> instances) { ListenerStateEnum newState; //当前实例是灰度实例 if (GrayUtil.isGrayPod()) { newState = ListenerStateEnum.GRAYSCALE; } else { //判断当前服务有灰度实例 if (this.isHaveGray(instances)) { newState = ListenerStateEnum.PRODUCTION; } else { newState = ListenerStateEnum.TOGETHER; } } log.info
("当前实例是否为灰度环境:{
}", GrayUtil.isGrayPod()); log.info("当前实例监听mq队列的状态:{}", newState.getValue()); //防止重复初始化监听mq队列信息 if (!newState.equals(listenerMqState)) { listenerMqState = newState; publisher.publishEvent(new GrayEventChangeEvent(listenerMqState)); } } /** * 是否有灰度实例 * * @return */ private boolean isHaveGray(List<Instance> instances) { if (!CollectionUtils.isEmpty(instances)) { for (Instance instance : instances) { if (GrayscaleConstant.STR_BOOLEAN_TRUE.equals(instance.getMetadata().get(GrayscaleConstant.POD_GRAY))) { return true; } } } return false; } }
src/main/java/com/easyhome/common/nacos/NacosEventListener.java
EASYHOME-DOORVERSE-easyhome-springcloud-gray-faee63a
[ { "filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java", "retrieved_chunk": " }\n }\n @Override\n public void onApplicationEvent(GrayEventChangeEvent event) {\n ListenerStateEnum listenerStateEnum = (ListenerStateEnum) event.getSource();\n log.info(this.getClass().getName() + \"灰度环境变更:\" + listenerStateEnum.getValue());\n currentState = listenerStateEnum;\n if (ListenerStateEnum.PRODUCTION.equals(listenerStateEnum)) {\n initConsumerProduction();\n for (SubscriptionData item : subscribes) {", "score": 0.8433009386062622 }, { "filename": "src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java", "retrieved_chunk": " if (CollectionUtils.isEmpty(instances)) {\n return instances;\n } else {\n //是否灰度请求\n Boolean isGrayRequest;\n String grayGroup=GrayscaleConstant.HEADER_VALUE;\n //兼容gateway传值方式,gateway是nio是通过key来做负载实例识别的\n if (Objects.nonNull(key) && !GrayscaleConstant.DEFAULT.equals(key)) {\n isGrayRequest = true;\n if(isGrayRequest){", "score": 0.8344930410385132 }, { "filename": "src/main/java/com/easyhome/common/utils/GrayUtil.java", "retrieved_chunk": " Map<String,String> attributes= GrayParamHolder.getGrayMap();\n String releaseVersion=attributes.get(GrayscaleConstant.HEADER_KEY);\n if (Objects.nonNull(releaseVersion)&&!\"\".equals(releaseVersion)) {\n return true;\n }\n return false;\n }\n /**\n * 当前环境是否为灰度环境\n *", "score": 0.8198301792144775 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java", "retrieved_chunk": " * 只监听生产环境队列\n */\n PRODUCTION(0, \"只监听生产环境队列\"),\n /**\n * 只监听灰度环境队列\n */\n GRAYSCALE(1, \"只监听灰度环境队列\"),\n /**\n * 同时监听生产和灰度环境队列\n */", "score": 0.8154177069664001 }, { "filename": "src/main/java/com/easyhome/common/rocketmq/ListenerStateEnum.java", "retrieved_chunk": "package com.easyhome.common.rocketmq;\nimport lombok.Getter;\n/**\n * 灰度发版队列监听状态\n *\n * @author wangshufeng\n */\n@Getter\npublic enum ListenerStateEnum {\n /**", "score": 0.8120714426040649 } ]
java
("当前实例是否为灰度环境:{
package com.deshaw.pjrmi; import com.deshaw.io.BlockingPipe; import com.deshaw.util.StringUtil; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * A transport provider which uses PipedStreams to allow users to * communicate with another thread inside the process. */ public class PipedProvider implements Transport.Provider { /** * A simple PJRmi instance to use with this. */ public static class PipedPJRmi extends PJRmi { /** * The arguments supplied to the instance. */ private final Arguments myArguments; /** * Constructor. * * @param provider The provider to use. * * @throws IOException if there was a problem. * @throws IllegalArgumentException if there was a problem. */ public PipedPJRmi(PipedProvider provider) throws IOException, IllegalArgumentException { this(provider, null); } /** * Constructor. * * @param provider The provider to use. * @param args The PJRmi arguments. * * @throws IOException if there was a problem. * @throws IllegalArgumentException if there was a problem. */ public PipedPJRmi(PipedProvider provider, String[] args) throws IOException, IllegalArgumentException { super(provider.toString(), provider, new Arguments(args).useLocking); myArguments = new Arguments(args); // Multi-threading doesn't yet work in the in-process world as it // causes segfaults because there's no threading protection if (myArguments.numWorkers != 0) { throw new IllegalArgumentException( "Multi-threading not supporting for in-process instances" ); } } /** * {@inheritDoc} */ @Override protected Object getObjectInstance(CharSequence name) { if (StringUtil.equals(name, "LockManager")) { return getLockManager(); } else { return null; } } /** * {@inheritDoc} */ @Override protected boolean isClassBlockingOn() { return (myArguments.blockNonAllowlistedClasses != null) ? myArguments.blockNonAllowlistedClasses : super.isClassBlockingOn(); } /** * {@inheritDoc} */ @Override protected boolean isClassPermitted(CharSequence className) { return super.isClassPermitted(className) || ( className != null && myArguments.additionalAllowlistedClasses.contains( className.toString() ) ); } /** * {@inheritDoc} */ @Override protected boolean isClassInjectionPermitted() { return (myArguments.allowClassInjection != null) ? myArguments.allowClassInjection : super.isClassInjectionPermitted(); } /** * {@inheritDoc} */ @Override protected boolean isUserPermitted(CharSequence username) { return true; } /** * {@inheritDoc} */ @Override protected boolean isHostPermitted(InetAddress address) { return true; } /** * {@inheritDoc} */ @Override protected int numWorkers() { // We don't support multiple workers and multi-threading in the // in-process instance. Note that this method can be called in the // super CTOR if use-locking is enabled; this means that we have a // bootstrapping problem which needs to be fixed if we need to // reference myArguments here. return 0; } } /** * The pipe. */ public static class BidirectionalPipe { /** * Set to true when closed. */ private volatile boolean myIsClosed; /** * The input pipe going from outside into us. */ private final InputStream myJavaInputStream; /** * The output pipe going from us to the outside. */ private final OutputStream myJavaOutputStream; /** * The input pipe going us to the outside. */ private final InputStream myPythonInputStream; /** * The output pipe going from the outside to us. */ private final OutputStream myPythonOutputStream; /** * Constructor. */ private BidirectionalPipe() { // We are open, or will be when we are out of the CTOR anyhow myIsClosed = false; // Create and hook up the different ends final BlockingPipe in = new BlockingPipe(64 * 1024); final BlockingPipe out = new BlockingPipe(64 * 1024);
myJavaInputStream = in.getInputStream();
myJavaOutputStream = out.getOutputStream(); myPythonInputStream = out.getInputStream(); myPythonOutputStream = in.getOutputStream(); } /** * Close the pipe. */ public void close() { // Close all the pipes try { myJavaInputStream .close(); } catch (IOException e) { } try { myJavaOutputStream .close(); } catch (IOException e) { } try { myPythonInputStream .close(); } catch (IOException e) { } try { myPythonOutputStream.close(); } catch (IOException e) { } myIsClosed = true; } /** * Whether the pipe has been {@code close()}'d. * * @return whether the pipe is closed. */ public boolean isClosed() { return myIsClosed; } /** * Read a byte from the pipe (from the outside world). * * @return the byte, or -1 if EOF * * @throws IOException if there was a problem. */ public synchronized int read() throws IOException { return myPythonInputStream.read(); } /** * Write a byte into pipe (from the outside world). * * @param b The byte to write. * * @throws IOException if there was a problem. */ public synchronized void write(int b) throws IOException { myPythonOutputStream.write(b); } /** * Get the Java input stream. * * @return the input stream. */ protected InputStream getJavaInputStream() { return myJavaInputStream; } /** * Get the Java output stream. * * @return the output stream. */ protected OutputStream getJavaOutputStream() { return myJavaOutputStream; } } /** * The pipes waiting to connect. */ private volatile BlockingQueue<BidirectionalPipe> myPendingPipes; /** * CTOR. * * @throws IOException if there was a problem. */ public PipedProvider() throws IOException { myPendingPipes = new ArrayBlockingQueue<>(8); } /** * Allow the outside world to get a Pipe instance to talk down. Blocks * until the other side is close to being ready to service it. * * @return the new connection. * * @throws IOException if there was a problem. */ public BidirectionalPipe newConnection() throws IOException { final BidirectionalPipe pipe = new BidirectionalPipe(); for (BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; pipes != null; pipes = myPendingPipes) { try { pipes.put(pipe); return pipe; } catch (InterruptedException e) { // Just try again } } // If we got here then we have been closed throw new IOException("Provider is closed"); } /** * {@inheritDoc} */ @Override public Transport accept() throws IOException { for (BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; pipes != null; pipes = myPendingPipes) { try { return new PipedTransport(pipes.take()); } catch (InterruptedException e) { // Just try again } } // If we got here then we have been closed throw new IOException("Provider is closed"); } /** * {@inheritDoc} */ @Override public void close() { // Null the queue out so that new connections can't be made final BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; myPendingPipes = null; // Now clear the queue for (BidirectionalPipe pipe : pipes) { pipe.close(); } } /** * {@inheritDoc} */ @Override public boolean isClosed() { return (myPendingPipes == null); } /** * {@inheritDoc} */ @Override public String toString() { return "BidirectionalPipe"; } }
java/src/main/java/com/deshaw/pjrmi/PipedProvider.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " private final long myPythonId;\n /**\n * Where data comes in.\n */\n private final DataInputStream myIn;\n /**\n * Where data goes out.\n */\n private final DataOutputStream myOut;\n /**", "score": 0.8074192404747009 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/SocketTransport.java", "retrieved_chunk": " {\n return mySocket.getOutputStream();\n }\n /**\n * {@inheritDoc}\n */\n @Override\n public void close()\n {\n try {", "score": 0.8045915961265564 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " throws IOException,\n SecurityException\n {\n final Transport transport = myTransportProvider.accept();\n LOG.info(\n myName + \" Got connection \" + transport\n );\n // Grab its streams\n final InputStream is = transport.getInputStream();\n final OutputStream os = transport.getOutputStream();", "score": 0.804017186164856 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " myPythonId = pythonId;\n // We are active from the get-go\n myIsActive = true;\n // Set up the streams. It's important that we use a buffered output\n // stream for myOut since this will send the responses as a single\n // packet and this _greatly_ speeds up the way the clients work.\n // The 64k value is the usual MTU and should be way bigger than\n // anything we will end up sending.\n final InputStream inStream = transport.getInputStream();\n final OutputStream outStream = transport.getOutputStream();", "score": 0.8028226494789124 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": "package com.deshaw.pjrmi;\nimport com.deshaw.io.BlockingPipe;\nimport com.deshaw.python.Operations;\nimport com.deshaw.python.PythonPickle;\nimport com.deshaw.util.ByteList;\nimport com.deshaw.util.Instrumentor;\nimport com.deshaw.util.StringUtil;\nimport com.deshaw.util.StringUtil.HashableSubSequence;\nimport com.deshaw.util.ThreadLocalStringBuilder;\nimport com.deshaw.util.concurrent.LockManager;", "score": 0.8017351627349854 } ]
java
myJavaInputStream = in.getInputStream();
package com.deshaw.pjrmi; import com.deshaw.io.BlockingPipe; import com.deshaw.util.StringUtil; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; /** * A transport provider which uses PipedStreams to allow users to * communicate with another thread inside the process. */ public class PipedProvider implements Transport.Provider { /** * A simple PJRmi instance to use with this. */ public static class PipedPJRmi extends PJRmi { /** * The arguments supplied to the instance. */ private final Arguments myArguments; /** * Constructor. * * @param provider The provider to use. * * @throws IOException if there was a problem. * @throws IllegalArgumentException if there was a problem. */ public PipedPJRmi(PipedProvider provider) throws IOException, IllegalArgumentException { this(provider, null); } /** * Constructor. * * @param provider The provider to use. * @param args The PJRmi arguments. * * @throws IOException if there was a problem. * @throws IllegalArgumentException if there was a problem. */ public PipedPJRmi(PipedProvider provider, String[] args) throws IOException, IllegalArgumentException { super(provider.toString(), provider, new Arguments(args).useLocking); myArguments = new Arguments(args); // Multi-threading doesn't yet work in the in-process world as it // causes segfaults because there's no threading protection if (myArguments.numWorkers != 0) { throw new IllegalArgumentException( "Multi-threading not supporting for in-process instances" ); } } /** * {@inheritDoc} */ @Override protected Object getObjectInstance(CharSequence name) { if (StringUtil.equals(name, "LockManager")) { return getLockManager(); } else { return null; } } /** * {@inheritDoc} */ @Override protected boolean isClassBlockingOn() { return (myArguments.blockNonAllowlistedClasses != null) ? myArguments.blockNonAllowlistedClasses : super.isClassBlockingOn(); } /** * {@inheritDoc} */ @Override protected boolean isClassPermitted(CharSequence className) { return super.isClassPermitted(className) || ( className != null && myArguments.additionalAllowlistedClasses.contains( className.toString() ) ); } /** * {@inheritDoc} */ @Override protected boolean isClassInjectionPermitted() { return (myArguments.allowClassInjection != null) ? myArguments.allowClassInjection : super.isClassInjectionPermitted(); } /** * {@inheritDoc} */ @Override protected boolean isUserPermitted(CharSequence username) { return true; } /** * {@inheritDoc} */ @Override protected boolean isHostPermitted(InetAddress address) { return true; } /** * {@inheritDoc} */ @Override protected int numWorkers() { // We don't support multiple workers and multi-threading in the // in-process instance. Note that this method can be called in the // super CTOR if use-locking is enabled; this means that we have a // bootstrapping problem which needs to be fixed if we need to // reference myArguments here. return 0; } } /** * The pipe. */ public static class BidirectionalPipe { /** * Set to true when closed. */ private volatile boolean myIsClosed; /** * The input pipe going from outside into us. */ private final InputStream myJavaInputStream; /** * The output pipe going from us to the outside. */ private final OutputStream myJavaOutputStream; /** * The input pipe going us to the outside. */ private final InputStream myPythonInputStream; /** * The output pipe going from the outside to us. */ private final OutputStream myPythonOutputStream; /** * Constructor. */ private BidirectionalPipe() { // We are open, or will be when we are out of the CTOR anyhow myIsClosed = false; // Create and hook up the different ends final BlockingPipe in = new BlockingPipe(64 * 1024); final BlockingPipe out = new BlockingPipe(64 * 1024); myJavaInputStream = in.getInputStream(); myJavaOutputStream = out.getOutputStream();
myPythonInputStream = out.getInputStream();
myPythonOutputStream = in.getOutputStream(); } /** * Close the pipe. */ public void close() { // Close all the pipes try { myJavaInputStream .close(); } catch (IOException e) { } try { myJavaOutputStream .close(); } catch (IOException e) { } try { myPythonInputStream .close(); } catch (IOException e) { } try { myPythonOutputStream.close(); } catch (IOException e) { } myIsClosed = true; } /** * Whether the pipe has been {@code close()}'d. * * @return whether the pipe is closed. */ public boolean isClosed() { return myIsClosed; } /** * Read a byte from the pipe (from the outside world). * * @return the byte, or -1 if EOF * * @throws IOException if there was a problem. */ public synchronized int read() throws IOException { return myPythonInputStream.read(); } /** * Write a byte into pipe (from the outside world). * * @param b The byte to write. * * @throws IOException if there was a problem. */ public synchronized void write(int b) throws IOException { myPythonOutputStream.write(b); } /** * Get the Java input stream. * * @return the input stream. */ protected InputStream getJavaInputStream() { return myJavaInputStream; } /** * Get the Java output stream. * * @return the output stream. */ protected OutputStream getJavaOutputStream() { return myJavaOutputStream; } } /** * The pipes waiting to connect. */ private volatile BlockingQueue<BidirectionalPipe> myPendingPipes; /** * CTOR. * * @throws IOException if there was a problem. */ public PipedProvider() throws IOException { myPendingPipes = new ArrayBlockingQueue<>(8); } /** * Allow the outside world to get a Pipe instance to talk down. Blocks * until the other side is close to being ready to service it. * * @return the new connection. * * @throws IOException if there was a problem. */ public BidirectionalPipe newConnection() throws IOException { final BidirectionalPipe pipe = new BidirectionalPipe(); for (BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; pipes != null; pipes = myPendingPipes) { try { pipes.put(pipe); return pipe; } catch (InterruptedException e) { // Just try again } } // If we got here then we have been closed throw new IOException("Provider is closed"); } /** * {@inheritDoc} */ @Override public Transport accept() throws IOException { for (BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; pipes != null; pipes = myPendingPipes) { try { return new PipedTransport(pipes.take()); } catch (InterruptedException e) { // Just try again } } // If we got here then we have been closed throw new IOException("Provider is closed"); } /** * {@inheritDoc} */ @Override public void close() { // Null the queue out so that new connections can't be made final BlockingQueue<BidirectionalPipe> pipes = myPendingPipes; myPendingPipes = null; // Now clear the queue for (BidirectionalPipe pipe : pipes) { pipe.close(); } } /** * {@inheritDoc} */ @Override public boolean isClosed() { return (myPendingPipes == null); } /** * {@inheritDoc} */ @Override public String toString() { return "BidirectionalPipe"; } }
java/src/main/java/com/deshaw/pjrmi/PipedProvider.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " private final long myPythonId;\n /**\n * Where data comes in.\n */\n private final DataInputStream myIn;\n /**\n * Where data goes out.\n */\n private final DataOutputStream myOut;\n /**", "score": 0.8459541201591492 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " myPythonId = pythonId;\n // We are active from the get-go\n myIsActive = true;\n // Set up the streams. It's important that we use a buffered output\n // stream for myOut since this will send the responses as a single\n // packet and this _greatly_ speeds up the way the clients work.\n // The 64k value is the usual MTU and should be way bigger than\n // anything we will end up sending.\n final InputStream inStream = transport.getInputStream();\n final OutputStream outStream = transport.getOutputStream();", "score": 0.8429377675056458 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": "package com.deshaw.pjrmi;\nimport com.deshaw.io.BlockingPipe;\nimport com.deshaw.python.Operations;\nimport com.deshaw.python.PythonPickle;\nimport com.deshaw.util.ByteList;\nimport com.deshaw.util.Instrumentor;\nimport com.deshaw.util.StringUtil;\nimport com.deshaw.util.StringUtil.HashableSubSequence;\nimport com.deshaw.util.ThreadLocalStringBuilder;\nimport com.deshaw.util.concurrent.LockManager;", "score": 0.840240478515625 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " new ThreadLocalByteArrayDataOutputStream();\n /**\n * Our per-thread PythonPicklers, for converting values to pickle format.\n */\n private static final ThreadLocal<PythonPickle> ourPythonPickle =\n ThreadLocal.withInitial(PythonPickle::new);\n // ---------------------------------------------------------------------- //\n /**\n * Where connections come in.\n */", "score": 0.8268669843673706 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " throws IOException,\n SecurityException\n {\n final Transport transport = myTransportProvider.accept();\n LOG.info(\n myName + \" Got connection \" + transport\n );\n // Grab its streams\n final InputStream is = transport.getInputStream();\n final OutputStream os = transport.getOutputStream();", "score": 0.8201714754104614 } ]
java
myPythonInputStream = out.getInputStream();
package com.deshaw.pjrmi; import com.deshaw.util.StringUtil; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; /** * A transport provider which spawns a child Python process to talk to. */ public class PythonMinionProvider implements Transport.Provider { /** * Our stdin filename, if any. */ private final String myStdinFilename; /** * Our stdout filename, if any. */ private final String myStdoutFilename; /** * Our stderr filename, if any. */ private final String myStderrFilename; /** * Whether to use SHM data passing. */ private final boolean myUseShmdata; /** * The singleton child which we will spawn. */ private volatile PythonMinionTransport myMinion; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Spawn a Python minion with SHM value passing disabled by default. * * @return the minion instance. * * @throws IOException If there was a problem spawning the child. */ public static PythonMinion spawn() throws IOException { try { return spawn(null, null, null, false); } catch (IllegalArgumentException e) { // Should never happen throw new AssertionError(e); } } /** * Spawn a Python minion, and a PJRmi connection to handle its callbacks. * This allows users to specify if they want to use native array * handling. * * @param useShmArgPassing Whether to use native array handling. * * @return the minion instance. * * @throws IOException If there was a problem spawning the child. */ public static PythonMinion spawn(final boolean useShmArgPassing) throws IOException { try { return spawn(null, null, null, useShmArgPassing); } catch (IllegalArgumentException e) { // Should never happen throw new AssertionError(e); } } /** * Spawn a Python minion with SHM value passing disabled by default. * * @param stdinFilename The filename the child process should use for * stdin, or {@code null} if none. * @param stdoutFilename The filename the child process should use for * stdout, or {@code null} if none. * @param stderrFilename The filename the child process should use for * stderr, or {@code null} if none. * * @return the minion instance. * * @throws IOException If there was a problem spawning * the child. * @throws IllegalArgumentException If any of the stio redirects were * disallowed. */ public static PythonMinion spawn(final String stdinFilename, final String stdoutFilename, final String stderrFilename) throws IOException, IllegalArgumentException { return spawn(stdinFilename, stdoutFilename, stderrFilename, false); } /** * Spawn a Python minion, and a PJRmi connection to handle its callbacks. * * <p>This method allows the caller to provide optional overrides for * the child process's stdio. Since the child uses stdin and stdout to * talk to the parent these must not be any of the "/dev/std???" files. * This method also allows users to specify whether to enable passing * of some values by SHM copying. * * @param stdinFilename The filename the child process should use for * stdin, or {@code null} if none. * @param stdoutFilename The filename the child process should use for * stdout, or {@code null} if none. * @param stderrFilename The filename the child process should use for * stderr, or {@code null} if none. * @param useShmArgPassing Whether to use native array handling. * * @return the minion instance. * * @throws IOException If there was a problem spawning * the child. * @throws IllegalArgumentException If any of the stio redirects were * disallowed. */ public static PythonMinion spawn(final String stdinFilename, final String stdoutFilename, final String stderrFilename, final boolean useShmArgPassing) throws IOException, IllegalArgumentException { // Make sure that people don't interfere with our comms channel assertGoodForStdio("stdin", stdinFilename ); assertGoodForStdio("stdout", stdoutFilename); assertGoodForStdio("stderr", stderrFilename); // Create the PJRmi instance now, along with the transport we'll // need for it final PythonMinionProvider provider = new PythonMinionProvider(stdinFilename, stdoutFilename, stderrFilename, useShmArgPassing); final PJRmi pjrmi = new PJRmi("PythonMinion", provider, false, useShmArgPassing) { @Override protected Object getObjectInstance(CharSequence name) { return null; } @Override protected boolean isUserPermitted(CharSequence username) { return true; } @Override protected boolean isHostPermitted(InetAddress address) { return true; } @Override protected int numWorkers() { return 16; } }; // Give back the connection to handle evals return pjrmi.awaitConnection(); } /** * Ensure that someone isn't trying to be clever with the output * filenames, if any. This should prevent people accidently using our * comms channel for their own purposes. * * @param what The file description. * @param filename The file path. */ private static void assertGoodForStdio(final String what, final String filename) throws IllegalArgumentException { // Early-out if there's no override if (filename == null) { return; } // Using /dev/null is fine if (filename.equals("/dev/null")) { return; } // Disallow all files which look potentially dubious. We could try // to walk the symlinks here but that seems like overkill if (filename.startsWith("/dev/") || filename.startsWith("/proc/")) { throw new IllegalArgumentException( "Given " + what + " file was of a disallowed type: " + filename ); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * CTOR. * * @param stdinFilename The stdin path. * @param stdoutFilename The stdout path. * @param stderrFilename The stderr path. * @param useShmArgPassing Whether to use shared-memory arg passing. */ private PythonMinionProvider(final String stdinFilename, final String stdoutFilename, final String stderrFilename, final boolean useShmArgPassing) { myStdinFilename = stdinFilename; myStdoutFilename = stdoutFilename; myStderrFilename = stderrFilename; myUseShmdata = useShmArgPassing; myMinion = null; } /** * {@inheritDoc} */ @Override public Transport accept() throws IOException { if (myMinion == null) { myMinion = new PythonMinionTransport(myStdinFilename, myStdoutFilename, myStderrFilename, myUseShmdata); return myMinion; } else { while (myMinion != null) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Nothing } } // If we get here we have been closed so throw as such throw new IOException("Instance is closed"); } } /** * {@inheritDoc} */ @Override public void close() { if (myMinion != null) { myMinion.close(); myMinion = null; } } /** * {@inheritDoc} */ @Override public boolean isClosed() { return myMinion == null; } /** * {@inheritDoc} */ @Override public String toString() { return "PythonMinion"; } /** * Testing method. * * @param args What to eval. * * @throws Throwable if there was a problem. */ public static void main(String[] args) throws Throwable { final PythonMinion python = spawn(); System.out.println(); System.out.println("Calling eval and invoke..."); Object result; for (String arg : args) { // Do the eval try { result = python.eval(arg); } catch (Throwable t) { result
= StringUtil.stackTraceToString(t);
} System.out.println(" \"" + arg + "\" -> " + result); // Call a function on the argument try { result = python.invoke("len", Integer.class, arg); } catch (Throwable t) { result = StringUtil.stackTraceToString(t); } System.out.println(" len('" + arg + "') -> " + result); } // Stress test System.out.println(); System.out.println("Stress testing invoke()..."); for (int round = 1; round <= 3; round++) { Object foo = "foo"; final int count = 10000; long start = System.nanoTime(); for (int i=0; i < count; i++) { python.invoke("len", Integer.class, foo); } long end = System.nanoTime(); System.out.println(" time(len('" + foo + "')) = " + ((end - start) / count / 1000) + "us"); foo = PythonMinion.byValue(foo); start = System.nanoTime(); for (int i=0; i < count; i++) { python.invoke("len", Integer.class, foo); } end = System.nanoTime(); System.out.println(" time(len('" + foo + "')) = " + ((end - start) / count / 1000) + "us"); } // Done System.out.println(); } }
java/src/main/java/com/deshaw/pjrmi/PythonMinionProvider.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " public T apply(T arg)\n {\n try {\n return invoke(arg);\n }\n catch (PythonCallbackException e) {\n throw new RuntimeException(\"Failed to invoke callback\",\n e.getCause());\n }\n catch (Throwable t) {", "score": 0.8384404182434082 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " */\n protected T doInvoke(final Map<String,Object> kwargs,\n final Object... args)\n throws IOException,\n PythonCallbackException\n {\n // Say we're doing it\n if (LOG.isLoggable(Level.FINEST)) {\n LOG.finest(\"Invoking \" + this + \" \" +\n \"with args \" + Arrays.toString(args));", "score": 0.8278733491897583 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PythonFunction.java", "retrieved_chunk": " *\n * @param args The method's arguments, if any (may be null).\n *\n * @return the result of the call.\n *\n * @throws IllegalArgumentException if the arguments were incorrect.\n * @throws NoSuchMethodException if there was no such method in the\n * Python object.\n */\n public T invoke(final Object... args)", "score": 0.8253813982009888 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " {\n try {\n invoke();\n }\n catch (PythonCallbackException e) {\n throw new RuntimeException(\"Failed to invoke callback\",\n e.getCause());\n }\n catch (Throwable t) {\n throw new RuntimeException(\"Failed to invoke callback\", t);", "score": 0.8210320472717285 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " @Override\n public R apply(T arg)\n {\n try {\n return invoke(arg);\n }\n catch (PythonCallbackException e) {\n throw new RuntimeException(\"Failed to invoke callback\",\n e.getCause());\n }", "score": 0.8191016912460327 } ]
java
= StringUtil.stackTraceToString(t);
package com.deshaw.python; import com.deshaw.util.ByteList; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.RandomAccess; /** * Serialization of basic Java objects into a format compatible with Python's * pickle protocol. This should allow objects to be marshalled from Java into * Python. * * <p>This class is not thread-safe. */ public class PythonPickle { // Keep in sync with pickle.Pickler._BATCHSIZE. This is how many elements // batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will // break if this gets out of sync with pickle.py, but it's unclear that // would help anything either. private static final int BATCHSIZE = 1000; private static final byte MARK_V = Operations.MARK.code; // ---------------------------------------------------------------------- /** * We buffer up everything in here for dumping. */ private final ByteArrayOutputStream myStream = new ByteArrayOutputStream(); /** * Used to provide a handle on objects which we have already stored (so that * we don't duplicate them in the result). */ private final IdentityHashMap<Object,Integer> myMemo = new IdentityHashMap<>(); // Scratch space private final ByteBuffer myTwoByteBuffer = ByteBuffer.allocate(2); private final ByteBuffer myFourByteBuffer = ByteBuffer.allocate(4); private final ByteBuffer myEightByteBuffer = ByteBuffer.allocate(8); private final ByteList myByteList = new ByteList(); // ---------------------------------------------------------------------- /** * Dump an object out to a given stream. */ public void toStream(Object o, OutputStream stream) throws IOException { // Might be better to use the stream directly, rather than staging // locally. toPickle(o); myStream.writeTo(stream); } /** * Dump to a byte-array. */ public byte[] toByteArray(Object o) { toPickle(o); return myStream.toByteArray(); } /** * Pickle an arbitrary object which isn't handled by default. * * <p>Subclasses can override this to extend the class's behaviour. * * @throws UnsupportedOperationException if the object could not be pickled. */ protected void saveObject(Object o) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Cannot pickle " + o.getClass().getCanonicalName() ); } // ---------------------------------------------------------------------------- // Methods which subclasses might need to extend funnctionality /** * Get back the reference to a previously saved object. */ protected final void get(Object o) { writeOpcodeForValue(Operations.BINGET, Operations.LONG_BINGET, myMemo.get(o)); } /** * Save a reference to an object. */ protected final void put(Object o) { // 1-indexed; see comment about positve vs. non-negative in Python's // C pickle code final int n = myMemo.size() + 1; myMemo.put(o, n); writeOpcodeForValue(Operations.BINPUT, Operations.LONG_BINPUT, n); } /** * Write out an opcode, depending on the size of the 'n' value we are * encoding (i.e. if it fits in a byte). */ protected final void writeOpcodeForValue(Operations op1, Operations op5, int n) { if (n < 256) { write(op1); write((byte) n); } else { write(op5); // The pickle protocol saves this in little-endian format. writeLittleEndianInt(n); } } /** * Dump out a string as ASCII. */ protected final void writeAscii(String s) { write(s.getBytes(StandardCharsets.US_ASCII)); } /** * Write out a byte. */ protected final void write(Operations op) { myStream.write(op.code); } /** * Write out a byte. */ protected final void write(byte i) { myStream.write(i); } /** * Write out a char. */ protected final void write(char c) { myStream.write(c); } /** * Write out an int, in little-endian format. */ protected final void writeLittleEndianInt(final int n) { write(myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, n)); } /** * Write out the contents of a ByteBuffer. */ protected final void write(ByteBuffer b) { write(b.array()); } /** * Write out the contents of a byte array. */ protected final void write(byte[] array) { myStream.write(array, 0, array.length); } /** * Dump out a 32bit float. */ protected final void saveFloat(float o) {
myByteList.clear();
myByteList.append(Float.toString(o).getBytes()); write(Operations.FLOAT); write(myByteList.toArray()); write((byte) '\n'); } /** * Dump out a 64bit double. */ protected final void saveFloat(double o) { write(Operations.BINFLOAT); // The pickle protocol saves Python floats in big-endian format. write(myEightByteBuffer.order(ByteOrder.BIG_ENDIAN).putDouble(0, o)); } /** * Write a 32-or-less bit integer. */ protected final void saveInteger(int o) { // The pickle protocol saves Python integers in little-endian format. final byte[] a = myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, o) .array(); if (a[2] == 0 && a[3] == 0) { if (a[1] == 0) { // BININT1 is for integers [0, 256), not [-128, 128). write(Operations.BININT1); write(a[0]); return; } // BININT2 is for integers [256, 65536), not [-32768, 32768). write(Operations.BININT2); write(a[0]); write(a[1]); return; } write(Operations.BININT); write(a); } /** * Write a 64-or-less bit integer. */ protected final void saveInteger(long o) { if (o <= Integer.MAX_VALUE && o >= Integer.MIN_VALUE) { saveInteger((int) o); } else { write(Operations.LONG1); write((byte)8); write(myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putLong(0, o)); } } /** * Write out a string as real unicode. */ protected final void saveUnicode(String o) { final byte[] b; b = o.getBytes(StandardCharsets.UTF_8); write(Operations.BINUNICODE); // Pickle protocol is always little-endian writeLittleEndianInt(b.length); write(b); put(o); } // ---------------------------------------------------------------------- // Serializing objects intended to be unpickled as numpy arrays // // Instead of serializing array-like objects exactly the way numpy // arrays are serialized, we simply serialize them to be unpickled // as numpy arrays. The simplest way to do this is to use // numpy.fromstring(). We write out opcodes to build the // following stack: // // [..., numpy.fromstring, binary_data_string, dtype_string] // // and then call TUPLE2 and REDUCE to get: // // [..., numpy.fromstring(binary_data_string, dtype_string)] // // http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html /** * Save the Python function module.name. We use this function * with the REDUCE opcode to build Python objects when unpickling. */ protected final void saveGlobal(String module, String name) { write(Operations.GLOBAL); writeAscii(module); writeAscii("\n"); writeAscii(name); writeAscii("\n"); } /** * Save a boolean array as a numpy array. */ protected final void saveNumpyBooleanArray(boolean[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (boolean d : o) { write((byte) (d?1:0)); } addNumpyArrayEnding(DType.Type.BOOLEAN, o); } /** * Save a byte array as a numpy array. */ protected final void saveNumpyByteArray(byte[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (byte d : o) { write(d); } addNumpyArrayEnding(DType.Type.INT8, o); } /** * Save a char array as a numpy array. */ protected final void saveNumpyCharArray(char[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (char c : o) { write(c); } addNumpyArrayEnding(DType.Type.CHAR, o); } /** * Save a ByteList as a numpy array. */ protected final void saveNumpyByteArray(ByteList o) { saveGlobal("numpy", "fromstring"); final int n = o.size(); writeBinStringHeader((long) n); for (int i=0; i < n; ++i) { write(o.getNoCheck(i)); } addNumpyArrayEnding(DType.Type.INT8, o); } /** * Save a short array as a numpy array. */ protected final void saveNumpyShortArray(short[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(2 * (long) n); myTwoByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (short d : o) { write(myTwoByteBuffer.putShort(0, d)); } addNumpyArrayEnding(DType.Type.INT16, o); } /** * Save an int array as a numpy array. */ protected final void saveNumpyIntArray(int[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(4 * (long) n); myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (int d : o) { write(myFourByteBuffer.putInt(0, d)); } addNumpyArrayEnding(DType.Type.INT32, o); } /** * Save a long array as a numpy array. */ protected final void saveNumpyLongArray(long[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(8 * (long) n); myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (long d : o) { write(myEightByteBuffer.putLong(0, d)); } addNumpyArrayEnding(DType.Type.INT64, o); } /** * Save a float array as a numpy array. */ protected final void saveNumpyFloatArray(float[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(4 * (long) n); myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (float f : o) { write(myFourByteBuffer.putFloat(0, f)); } addNumpyArrayEnding(DType.Type.FLOAT32, o); } /** * Save a double array as a numpy array. */ protected final void saveNumpyDoubleArray(double[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(8 * (long) n); myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (double d : o) { write(myEightByteBuffer.putDouble(0, d)); } addNumpyArrayEnding(DType.Type.FLOAT64, o); } // ---------------------------------------------------------------------------- /** * Actually do the dump. */ private void toPickle(Object o) { myStream.reset(); write(Operations.PROTO); write((byte) 2); save(o); write(Operations.STOP); myMemo.clear(); } /** * Pickle an arbitrary object. */ @SuppressWarnings("unchecked") private void save(Object o) throws UnsupportedOperationException { if (o == null) { write(Operations.NONE); } else if (myMemo.containsKey(o)) { get(o); } else if (o instanceof Boolean) { write(((Boolean) o) ? Operations.NEWTRUE : Operations.NEWFALSE); } else if (o instanceof Float) { saveFloat((Float) o); } else if (o instanceof Double) { saveFloat((Double) o); } else if (o instanceof Byte) { saveInteger(((Byte) o).intValue()); } else if (o instanceof Short) { saveInteger(((Short) o).intValue()); } else if (o instanceof Integer) { saveInteger((Integer) o); } else if (o instanceof Long) { saveInteger((Long) o); } else if (o instanceof String) { saveUnicode((String) o); } else if (o instanceof boolean[]) { saveNumpyBooleanArray((boolean[]) o); } else if (o instanceof char[]) { saveNumpyCharArray((char[]) o); } else if (o instanceof byte[]) { saveNumpyByteArray((byte[]) o); } else if (o instanceof short[]) { saveNumpyShortArray((short[]) o); } else if (o instanceof int[]) { saveNumpyIntArray((int[]) o); } else if (o instanceof long[]) { saveNumpyLongArray((long[]) o); } else if (o instanceof float[]) { saveNumpyFloatArray((float[]) o); } else if (o instanceof double[]) { saveNumpyDoubleArray((double[]) o); } else if (o instanceof List) { saveList((List<Object>) o); } else if (o instanceof Map) { saveDict((Map<Object,Object>) o); } else if (o instanceof Collection) { saveCollection((Collection<Object>) o); } else if (o.getClass().isArray()) { saveList(Arrays.asList((Object[]) o)); } else { saveObject(o); } } /** * Write out the header for a binary "string" of data. */ private void writeBinStringHeader(long n) { if (n < 256) { write(Operations.SHORT_BINSTRING); write((byte) n); } else if (n <= Integer.MAX_VALUE) { write(Operations.BINSTRING); // Pickle protocol is always little-endian writeLittleEndianInt((int) n); } else { throw new UnsupportedOperationException("String length of " + n + " is too large"); } } /** * The string for which {@code numpy.dtype(...)} returns the desired dtype. */ private String dtypeDescr(final DType.Type type) { if (type == null) { throw new NullPointerException("Null dtype"); } switch (type) { case BOOLEAN: return "|b1"; case CHAR: return "<S1"; case INT8: return "<i1"; case INT16: return "<i2"; case INT32: return "<i4"; case INT64: return "<i8"; case FLOAT32: return "<f4"; case FLOAT64: return "<f8"; default: throw new IllegalArgumentException("Unhandled type: " + type); } } /** * Add the suffix of a serialized numpy array * * @param dtype type of the numpy array * @param o the array (or list) being serialized */ private void addNumpyArrayEnding(DType.Type dtype, Object o) { final String descr = dtypeDescr(dtype); writeBinStringHeader(descr.length()); writeAscii(descr); write(Operations.TUPLE2); write(Operations.REDUCE); put(o); } /** * Save a Collection of arbitrary Objects as a tuple. */ private void saveCollection(Collection<Object> x) { // Tuples over 3 elements in size need a "mark" to look back to if (x.size() > 3) { write(Operations.MARK); } // Save all the elements for (Object o : x) { save(o); } // And say what we sent switch (x.size()) { case 0: write(Operations.EMPTY_TUPLE); break; case 1: write(Operations.TUPLE1); break; case 2: write(Operations.TUPLE2); break; case 3: write(Operations.TUPLE3); break; default: write(Operations.TUPLE); break; } put(x); } /** * Save a list of arbitrary objects. */ private void saveList(List<Object> x) { // Two implementations here. For RandomAccess lists it's faster to do // explicit get methods. For other ones iteration is faster. if (x instanceof RandomAccess) { write(Operations.EMPTY_LIST); put(x); for (int i=0; i < x.size(); i++) { final Object first = x.get(i); if (++i >= x.size()) { save(first); write(Operations.APPEND); break; } final Object second = x.get(i); write(MARK_V); save(first); save(second); int left = BATCHSIZE - 2; while (left > 0 && ++i < x.size()) { final Object item = x.get(i); save(item); left -= 1; } write(Operations.APPENDS); } } else { write(Operations.EMPTY_LIST); put(x); final Iterator<Object> items = x.iterator(); while (true) { if (!items.hasNext()) break; final Object first = items.next(); if (!items.hasNext()) { save(first); write(Operations.APPEND); break; } final Object second = items.next(); write(MARK_V); save(first); save(second); int left = BATCHSIZE - 2; while (left > 0 && items.hasNext()) { final Object item = items.next(); save(item); left -= 1; } write(Operations.APPENDS); } } } /** * Save a map of arbitrary objects as a dict. */ private void saveDict(Map<Object,Object> x) { write(Operations.EMPTY_DICT); put(x); final Iterator<Entry<Object,Object>> items = x.entrySet().iterator(); while (true) { if (!items.hasNext()) break; final Entry<Object,Object> first = items.next(); if (!items.hasNext()) { save(first.getKey()); save(first.getValue()); write(Operations.SETITEM); break; } final Entry<Object,Object> second = items.next(); write(MARK_V); save(first.getKey()); save(first.getValue()); save(second.getKey()); save(second.getValue()); int left = BATCHSIZE - 2; while (left > 0 && items.hasNext()) { final Entry<Object,Object> item = items.next(); save(item.getKey()); save(item.getValue()); left -= 1; } write(Operations.SETITEMS); } } }
java/src/main/java/com/deshaw/python/PythonPickle.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " dataOut.writeLong((Long)object);\n }\n else if (object instanceof java.lang.Float) {\n dataOut.writeInt(Float.BYTES);\n dataOut.writeFloat((Float)object);\n }\n else if (object instanceof java.lang.Double) {\n dataOut.writeInt(Double.BYTES);\n dataOut.writeDouble((Double)object);\n }", "score": 0.8080004453659058 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " else if (object instanceof java.lang.Short) {\n dataOut.writeInt(Short.BYTES);\n dataOut.writeShort((Short)object);\n }\n else if (object instanceof java.lang.Integer) {\n dataOut.writeInt(Integer.BYTES);\n dataOut.writeInt((Integer)object);\n }\n else if (object instanceof java.lang.Long) {\n dataOut.writeInt(Long.BYTES);", "score": 0.7999964356422424 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " case \"char\":\n dataOut.writeChar((Character)object);\n break;\n case \"double\":\n dataOut.writeDouble((Double)object);\n break;\n case \"float\":\n dataOut.writeFloat((Float)object);\n break;\n case \"int\":", "score": 0.7940115928649902 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " final ByteArrayDataOutputStream bados = ourByteOutBuffer.get();\n bados.dataOut.writeInt(requestId);\n bados.dataOut.writeInt(myObjectId);\n bados.dataOut.writeInt(myTypeMapping.getId(method.getReturnType()));\n writeUTF16 (bados.dataOut, method.getName());\n // Handle any arguments\n if (args == null) {\n bados.dataOut.writeInt(0);\n }\n else {", "score": 0.7863413691520691 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " out.writeInt (bytes.length);\n out.write (bytes, 0, bytes.length);\n }\n }\n }\n else if (arg instanceof PythonObjectImpl) {\n out.writeByte(PythonValueFormat.PYTHON_REFERENCE.id);\n out.writeInt (((PythonObjectImpl)arg).getId());\n }\n else {", "score": 0.7863273620605469 } ]
java
myByteList.clear();
package com.deshaw.python; import com.deshaw.util.ByteList; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.RandomAccess; /** * Serialization of basic Java objects into a format compatible with Python's * pickle protocol. This should allow objects to be marshalled from Java into * Python. * * <p>This class is not thread-safe. */ public class PythonPickle { // Keep in sync with pickle.Pickler._BATCHSIZE. This is how many elements // batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will // break if this gets out of sync with pickle.py, but it's unclear that // would help anything either. private static final int BATCHSIZE = 1000; private static final byte MARK_V = Operations.MARK.code; // ---------------------------------------------------------------------- /** * We buffer up everything in here for dumping. */ private final ByteArrayOutputStream myStream = new ByteArrayOutputStream(); /** * Used to provide a handle on objects which we have already stored (so that * we don't duplicate them in the result). */ private final IdentityHashMap<Object,Integer> myMemo = new IdentityHashMap<>(); // Scratch space private final ByteBuffer myTwoByteBuffer = ByteBuffer.allocate(2); private final ByteBuffer myFourByteBuffer = ByteBuffer.allocate(4); private final ByteBuffer myEightByteBuffer = ByteBuffer.allocate(8); private final ByteList myByteList = new ByteList(); // ---------------------------------------------------------------------- /** * Dump an object out to a given stream. */ public void toStream(Object o, OutputStream stream) throws IOException { // Might be better to use the stream directly, rather than staging // locally. toPickle(o); myStream.writeTo(stream); } /** * Dump to a byte-array. */ public byte[] toByteArray(Object o) { toPickle(o); return myStream.toByteArray(); } /** * Pickle an arbitrary object which isn't handled by default. * * <p>Subclasses can override this to extend the class's behaviour. * * @throws UnsupportedOperationException if the object could not be pickled. */ protected void saveObject(Object o) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Cannot pickle " + o.getClass().getCanonicalName() ); } // ---------------------------------------------------------------------------- // Methods which subclasses might need to extend funnctionality /** * Get back the reference to a previously saved object. */ protected final void get(Object o) { writeOpcodeForValue(Operations.BINGET, Operations.LONG_BINGET, myMemo.get(o)); } /** * Save a reference to an object. */ protected final void put(Object o) { // 1-indexed; see comment about positve vs. non-negative in Python's // C pickle code final int n = myMemo.size() + 1; myMemo.put(o, n); writeOpcodeForValue(Operations.BINPUT, Operations.LONG_BINPUT, n); } /** * Write out an opcode, depending on the size of the 'n' value we are * encoding (i.e. if it fits in a byte). */ protected final void writeOpcodeForValue(Operations op1, Operations op5, int n) { if (n < 256) { write(op1); write((byte) n); } else { write(op5); // The pickle protocol saves this in little-endian format. writeLittleEndianInt(n); } } /** * Dump out a string as ASCII. */ protected final void writeAscii(String s) { write(s.getBytes(StandardCharsets.US_ASCII)); } /** * Write out a byte. */ protected final void write(Operations op) { myStream.write(op.code); } /** * Write out a byte. */ protected final void write(byte i) { myStream.write(i); } /** * Write out a char. */ protected final void write(char c) { myStream.write(c); } /** * Write out an int, in little-endian format. */ protected final void writeLittleEndianInt(final int n) { write(myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, n)); } /** * Write out the contents of a ByteBuffer. */ protected final void write(ByteBuffer b) { write(b.array()); } /** * Write out the contents of a byte array. */ protected final void write(byte[] array) { myStream.write(array, 0, array.length); } /** * Dump out a 32bit float. */ protected final void saveFloat(float o) { myByteList.clear(); myByteList.append(Float.toString(o).getBytes()); write(Operations.FLOAT); write
(myByteList.toArray());
write((byte) '\n'); } /** * Dump out a 64bit double. */ protected final void saveFloat(double o) { write(Operations.BINFLOAT); // The pickle protocol saves Python floats in big-endian format. write(myEightByteBuffer.order(ByteOrder.BIG_ENDIAN).putDouble(0, o)); } /** * Write a 32-or-less bit integer. */ protected final void saveInteger(int o) { // The pickle protocol saves Python integers in little-endian format. final byte[] a = myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putInt(0, o) .array(); if (a[2] == 0 && a[3] == 0) { if (a[1] == 0) { // BININT1 is for integers [0, 256), not [-128, 128). write(Operations.BININT1); write(a[0]); return; } // BININT2 is for integers [256, 65536), not [-32768, 32768). write(Operations.BININT2); write(a[0]); write(a[1]); return; } write(Operations.BININT); write(a); } /** * Write a 64-or-less bit integer. */ protected final void saveInteger(long o) { if (o <= Integer.MAX_VALUE && o >= Integer.MIN_VALUE) { saveInteger((int) o); } else { write(Operations.LONG1); write((byte)8); write(myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN).putLong(0, o)); } } /** * Write out a string as real unicode. */ protected final void saveUnicode(String o) { final byte[] b; b = o.getBytes(StandardCharsets.UTF_8); write(Operations.BINUNICODE); // Pickle protocol is always little-endian writeLittleEndianInt(b.length); write(b); put(o); } // ---------------------------------------------------------------------- // Serializing objects intended to be unpickled as numpy arrays // // Instead of serializing array-like objects exactly the way numpy // arrays are serialized, we simply serialize them to be unpickled // as numpy arrays. The simplest way to do this is to use // numpy.fromstring(). We write out opcodes to build the // following stack: // // [..., numpy.fromstring, binary_data_string, dtype_string] // // and then call TUPLE2 and REDUCE to get: // // [..., numpy.fromstring(binary_data_string, dtype_string)] // // http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromstring.html /** * Save the Python function module.name. We use this function * with the REDUCE opcode to build Python objects when unpickling. */ protected final void saveGlobal(String module, String name) { write(Operations.GLOBAL); writeAscii(module); writeAscii("\n"); writeAscii(name); writeAscii("\n"); } /** * Save a boolean array as a numpy array. */ protected final void saveNumpyBooleanArray(boolean[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (boolean d : o) { write((byte) (d?1:0)); } addNumpyArrayEnding(DType.Type.BOOLEAN, o); } /** * Save a byte array as a numpy array. */ protected final void saveNumpyByteArray(byte[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (byte d : o) { write(d); } addNumpyArrayEnding(DType.Type.INT8, o); } /** * Save a char array as a numpy array. */ protected final void saveNumpyCharArray(char[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader((long) n); for (char c : o) { write(c); } addNumpyArrayEnding(DType.Type.CHAR, o); } /** * Save a ByteList as a numpy array. */ protected final void saveNumpyByteArray(ByteList o) { saveGlobal("numpy", "fromstring"); final int n = o.size(); writeBinStringHeader((long) n); for (int i=0; i < n; ++i) { write(o.getNoCheck(i)); } addNumpyArrayEnding(DType.Type.INT8, o); } /** * Save a short array as a numpy array. */ protected final void saveNumpyShortArray(short[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(2 * (long) n); myTwoByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (short d : o) { write(myTwoByteBuffer.putShort(0, d)); } addNumpyArrayEnding(DType.Type.INT16, o); } /** * Save an int array as a numpy array. */ protected final void saveNumpyIntArray(int[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(4 * (long) n); myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (int d : o) { write(myFourByteBuffer.putInt(0, d)); } addNumpyArrayEnding(DType.Type.INT32, o); } /** * Save a long array as a numpy array. */ protected final void saveNumpyLongArray(long[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(8 * (long) n); myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (long d : o) { write(myEightByteBuffer.putLong(0, d)); } addNumpyArrayEnding(DType.Type.INT64, o); } /** * Save a float array as a numpy array. */ protected final void saveNumpyFloatArray(float[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(4 * (long) n); myFourByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (float f : o) { write(myFourByteBuffer.putFloat(0, f)); } addNumpyArrayEnding(DType.Type.FLOAT32, o); } /** * Save a double array as a numpy array. */ protected final void saveNumpyDoubleArray(double[] o) { saveGlobal("numpy", "fromstring"); final int n = o.length; writeBinStringHeader(8 * (long) n); myEightByteBuffer.order(ByteOrder.LITTLE_ENDIAN); for (double d : o) { write(myEightByteBuffer.putDouble(0, d)); } addNumpyArrayEnding(DType.Type.FLOAT64, o); } // ---------------------------------------------------------------------------- /** * Actually do the dump. */ private void toPickle(Object o) { myStream.reset(); write(Operations.PROTO); write((byte) 2); save(o); write(Operations.STOP); myMemo.clear(); } /** * Pickle an arbitrary object. */ @SuppressWarnings("unchecked") private void save(Object o) throws UnsupportedOperationException { if (o == null) { write(Operations.NONE); } else if (myMemo.containsKey(o)) { get(o); } else if (o instanceof Boolean) { write(((Boolean) o) ? Operations.NEWTRUE : Operations.NEWFALSE); } else if (o instanceof Float) { saveFloat((Float) o); } else if (o instanceof Double) { saveFloat((Double) o); } else if (o instanceof Byte) { saveInteger(((Byte) o).intValue()); } else if (o instanceof Short) { saveInteger(((Short) o).intValue()); } else if (o instanceof Integer) { saveInteger((Integer) o); } else if (o instanceof Long) { saveInteger((Long) o); } else if (o instanceof String) { saveUnicode((String) o); } else if (o instanceof boolean[]) { saveNumpyBooleanArray((boolean[]) o); } else if (o instanceof char[]) { saveNumpyCharArray((char[]) o); } else if (o instanceof byte[]) { saveNumpyByteArray((byte[]) o); } else if (o instanceof short[]) { saveNumpyShortArray((short[]) o); } else if (o instanceof int[]) { saveNumpyIntArray((int[]) o); } else if (o instanceof long[]) { saveNumpyLongArray((long[]) o); } else if (o instanceof float[]) { saveNumpyFloatArray((float[]) o); } else if (o instanceof double[]) { saveNumpyDoubleArray((double[]) o); } else if (o instanceof List) { saveList((List<Object>) o); } else if (o instanceof Map) { saveDict((Map<Object,Object>) o); } else if (o instanceof Collection) { saveCollection((Collection<Object>) o); } else if (o.getClass().isArray()) { saveList(Arrays.asList((Object[]) o)); } else { saveObject(o); } } /** * Write out the header for a binary "string" of data. */ private void writeBinStringHeader(long n) { if (n < 256) { write(Operations.SHORT_BINSTRING); write((byte) n); } else if (n <= Integer.MAX_VALUE) { write(Operations.BINSTRING); // Pickle protocol is always little-endian writeLittleEndianInt((int) n); } else { throw new UnsupportedOperationException("String length of " + n + " is too large"); } } /** * The string for which {@code numpy.dtype(...)} returns the desired dtype. */ private String dtypeDescr(final DType.Type type) { if (type == null) { throw new NullPointerException("Null dtype"); } switch (type) { case BOOLEAN: return "|b1"; case CHAR: return "<S1"; case INT8: return "<i1"; case INT16: return "<i2"; case INT32: return "<i4"; case INT64: return "<i8"; case FLOAT32: return "<f4"; case FLOAT64: return "<f8"; default: throw new IllegalArgumentException("Unhandled type: " + type); } } /** * Add the suffix of a serialized numpy array * * @param dtype type of the numpy array * @param o the array (or list) being serialized */ private void addNumpyArrayEnding(DType.Type dtype, Object o) { final String descr = dtypeDescr(dtype); writeBinStringHeader(descr.length()); writeAscii(descr); write(Operations.TUPLE2); write(Operations.REDUCE); put(o); } /** * Save a Collection of arbitrary Objects as a tuple. */ private void saveCollection(Collection<Object> x) { // Tuples over 3 elements in size need a "mark" to look back to if (x.size() > 3) { write(Operations.MARK); } // Save all the elements for (Object o : x) { save(o); } // And say what we sent switch (x.size()) { case 0: write(Operations.EMPTY_TUPLE); break; case 1: write(Operations.TUPLE1); break; case 2: write(Operations.TUPLE2); break; case 3: write(Operations.TUPLE3); break; default: write(Operations.TUPLE); break; } put(x); } /** * Save a list of arbitrary objects. */ private void saveList(List<Object> x) { // Two implementations here. For RandomAccess lists it's faster to do // explicit get methods. For other ones iteration is faster. if (x instanceof RandomAccess) { write(Operations.EMPTY_LIST); put(x); for (int i=0; i < x.size(); i++) { final Object first = x.get(i); if (++i >= x.size()) { save(first); write(Operations.APPEND); break; } final Object second = x.get(i); write(MARK_V); save(first); save(second); int left = BATCHSIZE - 2; while (left > 0 && ++i < x.size()) { final Object item = x.get(i); save(item); left -= 1; } write(Operations.APPENDS); } } else { write(Operations.EMPTY_LIST); put(x); final Iterator<Object> items = x.iterator(); while (true) { if (!items.hasNext()) break; final Object first = items.next(); if (!items.hasNext()) { save(first); write(Operations.APPEND); break; } final Object second = items.next(); write(MARK_V); save(first); save(second); int left = BATCHSIZE - 2; while (left > 0 && items.hasNext()) { final Object item = items.next(); save(item); left -= 1; } write(Operations.APPENDS); } } } /** * Save a map of arbitrary objects as a dict. */ private void saveDict(Map<Object,Object> x) { write(Operations.EMPTY_DICT); put(x); final Iterator<Entry<Object,Object>> items = x.entrySet().iterator(); while (true) { if (!items.hasNext()) break; final Entry<Object,Object> first = items.next(); if (!items.hasNext()) { save(first.getKey()); save(first.getValue()); write(Operations.SETITEM); break; } final Entry<Object,Object> second = items.next(); write(MARK_V); save(first.getKey()); save(first.getValue()); save(second.getKey()); save(second.getValue()); int left = BATCHSIZE - 2; while (left > 0 && items.hasNext()) { final Entry<Object,Object> item = items.next(); save(item.getKey()); save(item.getValue()); left -= 1; } write(Operations.SETITEMS); } } }
java/src/main/java/com/deshaw/python/PythonPickle.java
deshaw-pjrmi-4212d0a
[ { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " dataOut.writeLong((Long)object);\n }\n else if (object instanceof java.lang.Float) {\n dataOut.writeInt(Float.BYTES);\n dataOut.writeFloat((Float)object);\n }\n else if (object instanceof java.lang.Double) {\n dataOut.writeInt(Double.BYTES);\n dataOut.writeDouble((Double)object);\n }", "score": 0.8141543865203857 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " else if (object instanceof java.lang.Short) {\n dataOut.writeInt(Short.BYTES);\n dataOut.writeShort((Short)object);\n }\n else if (object instanceof java.lang.Integer) {\n dataOut.writeInt(Integer.BYTES);\n dataOut.writeInt((Integer)object);\n }\n else if (object instanceof java.lang.Long) {\n dataOut.writeInt(Long.BYTES);", "score": 0.7995998859405518 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " case \"char\":\n dataOut.writeChar((Character)object);\n break;\n case \"double\":\n dataOut.writeDouble((Double)object);\n break;\n case \"float\":\n dataOut.writeFloat((Float)object);\n break;\n case \"int\":", "score": 0.793247401714325 }, { "filename": "java/src/main/java/com/deshaw/python/NumpyArray.java", "retrieved_chunk": " case INT16: myByteBuffer.putShort (linearIx, (short) v); break;\n case INT32: myByteBuffer.putInt (linearIx, (int) v); break;\n case INT64: myByteBuffer.putLong (linearIx, v); break;\n case FLOAT32: myByteBuffer.putFloat (linearIx, v); break;\n case FLOAT64: myByteBuffer.putDouble(linearIx, v); break;\n default:\n throw new UnsupportedOperationException(\n \"Unrecognized type \" + myType + \" of dtype \" + myDType\n );\n }", "score": 0.7867287397384644 }, { "filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java", "retrieved_chunk": " }\n }\n else if (object instanceof java.lang.Boolean) {\n dataOut.writeInt(1);\n dataOut.writeBoolean((Boolean)object);\n }\n else if (object instanceof java.lang.Byte) {\n dataOut.writeInt(Byte.BYTES);\n dataOut.writeByte((Byte)object);\n }", "score": 0.7831066846847534 } ]
java
(myByteList.toArray());