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/tinker/ShareReflectUtil.java",
"retrieved_chunk": " *\n * @param instance an object to search the field into.\n * @param name field name\n * @return a field object\n * @throws NoSuchFieldException if the field cannot be located\n */\n public static Field findField(Object instance, String name) throws NoSuchFieldException {\n for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {\n try {\n Field field = clazz.getDeclaredField(name);",
"score": 0.7767641544342041
},
{
"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.7740198373794556
},
{
"filename": "app/src/main/java/com/example/nativecpp/MainActivity.java",
"retrieved_chunk": "public class MainActivity extends AppCompatActivity {\n // Used to load the 'nativecpptwo' library on application startup.\n static {\n //System.loadLibrary(\"nativecpptwo\");\n }\n private ActivityMainBinding binding;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String path = \"/data/data/com.example.nativecpp/\";",
"score": 0.7730989456176758
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " activityThread = Class.forName(\"android.app.ActivityThread\");\n }\n Method m = activityThread.getMethod(\"currentActivityThread\");\n m.setAccessible(true);\n Object currentActivityThread = m.invoke(null);\n if (currentActivityThread == null && context != null) {\n // In older versions of Android (prior to frameworks/base 66a017b63461a22842)\n // the currentActivityThread was built on thread locals, so we'll need to try\n // even harder\n Field mLoadedApk = context.getClass().getField(\"mLoadedApk\");",
"score": 0.768888533115387
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " if (!field.isAccessible()) {\n field.setAccessible(true);\n }\n return field;\n } catch (NoSuchFieldException e) {\n // ignore and search next\n }\n }\n throw new NoSuchFieldException(\"Field \" + name + \" not found in \" + instance.getClass());\n }",
"score": 0.7677647471427917
}
] | 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.9396094083786011
},
{
"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.9142277240753174
},
{
"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.912254810333252
},
{
"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.8966652154922485
},
{
"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.8905720710754395
}
] | 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.9682694673538208
},
{
"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.9338737726211548
},
{
"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.9329503178596497
},
{
"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.9298332929611206
},
{
"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.9293764233589172
}
] | 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.9587537050247192
},
{
"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.9256500601768494
},
{
"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.9252675771713257
},
{
"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.9243852496147156
},
{
"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.9228298664093018
}
] | 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": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": "package com.example.lib_sillyboy.tinker;\nimport android.os.Handler;\nimport android.os.Message;\nimport android.util.Log;\nimport java.lang.reflect.Constructor;\npublic class ShareTinkerLog {\n private static final String TAG = \"Tinker.ShareTinkerLog\";\n public static final int FN_LOG_PRINT_STACKTRACE = 0xFA1;\n public static final int FN_LOG_PRINT_PENDING_LOGS = 0xFA2;\n private static final Handler[] tinkerLogInlineFenceRef = {null};",
"score": 0.8187819719314575
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": "package com.example.lib_sillyboy.tinker;\nimport android.content.Context;\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.util.Arrays;\npublic class ShareReflectUtil {\n /**\n * Locates a given field anywhere in the class inheritance hierarchy.",
"score": 0.8024145364761353
},
{
"filename": "app/src/main/java/com/example/nativecpp/MainActivity.java",
"retrieved_chunk": "public class MainActivity extends AppCompatActivity {\n // Used to load the 'nativecpptwo' library on application startup.\n static {\n //System.loadLibrary(\"nativecpptwo\");\n }\n private ActivityMainBinding binding;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String path = \"/data/data/com.example.nativecpp/\";",
"score": 0.7842102646827698
},
{
"filename": "app/src/main/java/com/example/nativecpp/CustomApplication.java",
"retrieved_chunk": "package com.example.nativecpp;\nimport android.app.Application;\nimport android.util.Log;\nimport com.example.lib_sillyboy.DynamicSo;\nimport java.io.File;\npublic class CustomApplication extends Application {\n @Override\n public void onCreate() {\n super.onCreate();\n //String absolutePath = getFilesDir().getAbsolutePath();",
"score": 0.7827566862106323
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " final Class<?> clazz = Class.forName(\"com.tencent.tinker.lib.util.TinkerLogInlineFence\");\n final Constructor<?> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n tinkerLogInlineFenceRef[0] = (Handler) ctor.newInstance();\n } catch (Throwable thr) {\n Log.e(TAG, \"[-] Fail to create inline fence instance.\", thr);\n tinkerLogInlineFenceRef[0] = null;\n }\n }\n }",
"score": 0.7546408176422119
}
] | java | ShareTinkerLog.e(TAG, "installNativeLibraryPath, folder %s is illegal", folder); |
/*
* 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.6844578385353088
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " final Class<?> clazz = Class.forName(\"com.tencent.tinker.lib.util.TinkerLogInlineFence\");\n final Constructor<?> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n tinkerLogInlineFenceRef[0] = (Handler) ctor.newInstance();\n } catch (Throwable thr) {\n Log.e(TAG, \"[-] Fail to create inline fence instance.\", thr);\n tinkerLogInlineFenceRef[0] = null;\n }\n }\n }",
"score": 0.5921039581298828
},
{
"filename": "app/src/main/java/com/example/nativecpp/MainActivity.java",
"retrieved_chunk": "public class MainActivity extends AppCompatActivity {\n // Used to load the 'nativecpptwo' library on application startup.\n static {\n //System.loadLibrary(\"nativecpptwo\");\n }\n private ActivityMainBinding binding;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String path = \"/data/data/com.example.nativecpp/\";",
"score": 0.5908839702606201
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " return;\n }\n Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(), finalLength);\n System.arraycopy(original, reduceSize, combined, 0, finalLength);\n jlrField.set(instance, combined);\n }\n public static Object getActivityThread(Context context,\n Class<?> activityThread) {\n try {\n if (activityThread == null) {",
"score": 0.5907993316650391
},
{
"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.5882461071014404
}
] | java | final Method makeElements = ShareReflectUtil.findMethod(dexPathList, "makePathElements", 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.9885151386260986
},
{
"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.935711681842804
},
{
"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.9349901676177979
},
{
"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.9342162013053894
},
{
"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.9323073625564575
}
] | 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/tinker/ShareReflectUtil.java",
"retrieved_chunk": " return;\n }\n Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(), finalLength);\n System.arraycopy(original, reduceSize, combined, 0, finalLength);\n jlrField.set(instance, combined);\n }\n public static Object getActivityThread(Context context,\n Class<?> activityThread) {\n try {\n if (activityThread == null) {",
"score": 0.7433378100395203
},
{
"filename": "app/src/main/java/com/example/nativecpp/MainActivity.java",
"retrieved_chunk": "public class MainActivity extends AppCompatActivity {\n // Used to load the 'nativecpptwo' library on application startup.\n static {\n //System.loadLibrary(\"nativecpptwo\");\n }\n private ActivityMainBinding binding;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String path = \"/data/data/com.example.nativecpp/\";",
"score": 0.742924153804779
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " log = \"\";\n }\n log += \" \" + Log.getStackTraceString(tr);\n Log.e(tag, log);\n }\n };\n private static final TinkerLogImp[] tinkerLogImpRef = {debugLog};\n static {\n synchronized (tinkerLogInlineFenceRef) {\n try {",
"score": 0.732886791229248
},
{
"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.7311297059059143
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " activityThread = Class.forName(\"android.app.ActivityThread\");\n }\n Method m = activityThread.getMethod(\"currentActivityThread\");\n m.setAccessible(true);\n Object currentActivityThread = m.invoke(null);\n if (currentActivityThread == null && context != null) {\n // In older versions of Android (prior to frameworks/base 66a017b63461a22842)\n // the currentActivityThread was built on thread locals, so we'll need to try\n // even harder\n Field mLoadedApk = context.getClass().getField(\"mLoadedApk\");",
"score": 0.7301504611968994
}
] | 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": "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.7185651063919067
},
{
"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.6556590795516968
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/DynamicSo.java",
"retrieved_chunk": " ElfParser parser = null;\n final List<String> dependencies;\n try {\n parser = new ElfParser(soFIle);\n dependencies = parser.parseNeededDependencies();\n } finally {\n if (parser != null) {\n parser.close();\n }\n }",
"score": 0.615666389465332
},
{
"filename": "app/src/main/java/com/example/nativecpp/MainActivity.java",
"retrieved_chunk": "public class MainActivity extends AppCompatActivity {\n // Used to load the 'nativecpptwo' library on application startup.\n static {\n //System.loadLibrary(\"nativecpptwo\");\n }\n private ActivityMainBinding binding;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n String path = \"/data/data/com.example.nativecpp/\";",
"score": 0.6113455295562744
},
{
"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.6110481023788452
}
] | 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.6928659677505493
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareReflectUtil.java",
"retrieved_chunk": " return;\n }\n Object[] combined = (Object[]) Array.newInstance(original.getClass().getComponentType(), finalLength);\n System.arraycopy(original, reduceSize, combined, 0, finalLength);\n jlrField.set(instance, combined);\n }\n public static Object getActivityThread(Context context,\n Class<?> activityThread) {\n try {\n if (activityThread == null) {",
"score": 0.6350396871566772
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/tinker/ShareTinkerLog.java",
"retrieved_chunk": " final Class<?> clazz = Class.forName(\"com.tencent.tinker.lib.util.TinkerLogInlineFence\");\n final Constructor<?> ctor = clazz.getDeclaredConstructor();\n ctor.setAccessible(true);\n tinkerLogInlineFenceRef[0] = (Handler) ctor.newInstance();\n } catch (Throwable thr) {\n Log.e(TAG, \"[-] Fail to create inline fence instance.\", thr);\n tinkerLogInlineFenceRef[0] = null;\n }\n }\n }",
"score": 0.6200699806213379
},
{
"filename": "lib_sillyboy/src/main/java/com/example/lib_sillyboy/elf/ElfParser.java",
"retrieved_chunk": " } else if (fileClass == Header.ELFCLASS64) {\n return new Elf64Header(bigEndian, this);\n }\n throw new IllegalStateException(\"Invalid class type!\");\n }\n public List<String> parseNeededDependencies() throws IOException {\n channel.position(0);\n final List<String> dependencies = new ArrayList<String>();\n final Header header = parseHeader();\n final ByteBuffer buffer = ByteBuffer.allocate(8);",
"score": 0.6165200471878052
},
{
"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.6146358251571655
}
] | 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.9858786463737488
},
{
"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.9349877834320068
},
{
"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.9307771921157837
},
{
"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.9261861443519592
},
{
"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.9227559566497803
}
] | 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.91838139295578
},
{
"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.8683769702911377
},
{
"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.8611117005348206
},
{
"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.8471724987030029
},
{
"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.8390014171600342
}
] | 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.9606113433837891
},
{
"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.9252657890319824
},
{
"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.9219040274620056
},
{
"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.9216283559799194
},
{
"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.9200558662414551
}
] | 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.9943051338195801
},
{
"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.9506517052650452
},
{
"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.9485712051391602
},
{
"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.9385571479797363
},
{
"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.9309415817260742
}
] | 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.9873723387718201
},
{
"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.935542106628418
},
{
"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.9339355230331421
},
{
"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.9223225712776184
},
{
"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.9202924966812134
}
] | 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.9758374691009521
},
{
"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.9467576742172241
},
{
"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.944015622138977
},
{
"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.9355790615081787
},
{
"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.9342013597488403
}
] | 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 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/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.9429190158843994
},
{
"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.9422670006752014
},
{
"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.9396577477455139
},
{
"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.9330892562866211
},
{
"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.9313336610794067
}
] | java | offset = 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 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/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.9445905685424805
},
{
"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.9405875205993652
},
{
"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.9365604519844055
},
{
"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.9320552945137024
},
{
"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.9308290481567383
}
] | 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.9925314784049988
},
{
"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.9547686576843262
},
{
"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.9508966207504272
},
{
"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.937947154045105
},
{
"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.9366819858551025
}
] | java | = parser.readWord(buffer, baseOffset + 0x14); |
/*
* 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/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.8135548233985901
},
{
"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.8074478507041931
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " this.executorService = Executors.newCachedThreadPool();\n }\n private static Properties producerProperties(String bootstrapServers) {\n var props = new Properties();\n props.put(\"bootstrap.servers\", bootstrapServers);\n props.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n props.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n return props;\n }\n private static Properties consumerProperties(String bootstrapServers) {",
"score": 0.7914310693740845
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " private final KafkaProducer<String, String> producer;\n private final Map<String, DecodableStreamImpl> streams;\n private final ExecutorService executorService;\n /** Creates a new testing context, using the given {@link TestEnvironment}. */\n public PipelineTestContext(TestEnvironment testEnvironment) {\n EnvironmentAccess.setEnvironment(testEnvironment);\n this.testEnvironment = testEnvironment;\n this.producer =\n new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers()));\n this.streams = new HashMap<>();",
"score": 0.7871213555335999
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " @SuppressWarnings(\"unchecked\")\n StreamConfig streamConfig =\n new StreamConfig(\n streamId, streamName, (Map<String, String>) config.get(\"properties\"));\n configsByStreamId.put(streamId, streamConfig);\n configsByStreamName.put(streamName, streamConfig);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(\n String.format(\"Couldn't parse stream configuration env variable %s\", entry.getKey()),\n e);",
"score": 0.7733958959579468
}
] | 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/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java",
"retrieved_chunk": " this.startupMode = StartupMode.fromString(properties.get(\"scan.startup.mode\"));\n this.transactionalIdPrefix = properties.get(\"sink.transactional-id-prefix\");\n this.deliveryGuarantee = properties.get(\"sink.delivery-guarantee\");\n this.properties =\n properties.entrySet().stream()\n .filter(e -> e.getKey().startsWith(\"properties\"))\n .collect(\n Collectors.toUnmodifiableMap(e -> e.getKey().substring(11), e -> e.getValue()));\n }\n public String id() {",
"score": 0.7181740403175354
},
{
"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.7181223630905151
},
{
"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.7083185911178589
},
{
"filename": "examples/apache-maven/custom-pipelines-hello-world/src/main/java/co/decodable/examples/cpdemo/DataStreamJob.java",
"retrieved_chunk": "\t\t\t\tDecodableStreamSource.<String>builder()\n\t\t\t\t\t.withStreamName(PURCHASE_ORDERS_STREAM)\n\t\t\t\t\t.withDeserializationSchema(new SimpleStringSchema())\n\t\t\t\t\t.build();\n\t\tDecodableStreamSink<String> sink =\n\t\t\tDecodableStreamSink.<String>builder()\n\t\t\t\t.withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n\t\t\t\t.withSerializationSchema(new SimpleStringSchema())\n\t\t\t\t.build();\n\t\tDataStream<String> stream =",
"score": 0.6492974162101746
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/snippets/PurchaseOrderProcessingJob.java",
"retrieved_chunk": " DecodableStreamSource<PurchaseOrder> source = DecodableStreamSource.<PurchaseOrder>builder()\n .withStreamName(PURCHASE_ORDERS_STREAM)\n .withDeserializationSchema(new JsonDeserializationSchema<>(PurchaseOrder.class))\n .build();\n DecodableStreamSink<PurchaseOrder> sink = DecodableStreamSink.<PurchaseOrder>builder()\n .withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n .withSerializationSchema(new JsonSerializationSchema<>())\n .build();\n // @end\n DataStream<PurchaseOrder> stream = env.fromSource(source, WatermarkStrategy.noWatermarks(), \"Purchase Orders Source\")",
"score": 0.6295642256736755
}
] | 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.812164306640625
},
{
"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.8109448552131653
},
{
"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.8108924031257629
},
{
"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.8024917840957642
},
{
"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.7908571362495422
}
] | 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.884985089302063
},
{
"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.8076179027557373
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " /** Returns a stream for the given name. */\n public DecodableStream<String> stream(String name) {\n KafkaConsumer<String, String> consumer =\n new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers()));\n consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name)));\n return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer));\n }\n /** Asynchronously executes the given Flink job main method. */\n public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args)\n throws Exception {",
"score": 0.7260899543762207
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " private final KafkaProducer<String, String> producer;\n private final Map<String, DecodableStreamImpl> streams;\n private final ExecutorService executorService;\n /** Creates a new testing context, using the given {@link TestEnvironment}. */\n public PipelineTestContext(TestEnvironment testEnvironment) {\n EnvironmentAccess.setEnvironment(testEnvironment);\n this.testEnvironment = testEnvironment;\n this.producer =\n new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers()));\n this.streams = new HashMap<>();",
"score": 0.7257319688796997
},
{
"filename": "examples/apache-maven/custom-pipelines-hello-world/src/main/java/co/decodable/examples/cpdemo/DataStreamJob.java",
"retrieved_chunk": "\t\t\t\tDecodableStreamSource.<String>builder()\n\t\t\t\t\t.withStreamName(PURCHASE_ORDERS_STREAM)\n\t\t\t\t\t.withDeserializationSchema(new SimpleStringSchema())\n\t\t\t\t\t.build();\n\t\tDecodableStreamSink<String> sink =\n\t\t\tDecodableStreamSink.<String>builder()\n\t\t\t\t.withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n\t\t\t\t.withSerializationSchema(new SimpleStringSchema())\n\t\t\t\t.build();\n\t\tDataStream<String> stream =",
"score": 0.7252844572067261
}
] | 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.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.883639931678772
},
{
"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.8445371389389038
},
{
"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.8427010178565979
},
{
"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.8375210762023926
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSourceBuilderImpl.java",
"retrieved_chunk": "import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;\npublic class DecodableStreamSourceBuilderImpl<T> implements DecodableStreamSourceBuilder<T> {\n private String streamId;\n private String streamName;\n private StartupMode startupMode;\n private DeserializationSchema<T> deserializationSchema;\n @Override\n public DecodableStreamSourceBuilder<T> withStreamName(String streamName) {\n this.streamName = streamName;\n return this;",
"score": 0.836590051651001
}
] | 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.7157942056655884
},
{
"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.7127166390419006
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfig.java",
"retrieved_chunk": " this.startupMode = StartupMode.fromString(properties.get(\"scan.startup.mode\"));\n this.transactionalIdPrefix = properties.get(\"sink.transactional-id-prefix\");\n this.deliveryGuarantee = properties.get(\"sink.delivery-guarantee\");\n this.properties =\n properties.entrySet().stream()\n .filter(e -> e.getKey().startsWith(\"properties\"))\n .collect(\n Collectors.toUnmodifiableMap(e -> e.getKey().substring(11), e -> e.getValue()));\n }\n public String id() {",
"score": 0.712069034576416
},
{
"filename": "examples/apache-maven/custom-pipelines-hello-world/src/main/java/co/decodable/examples/cpdemo/DataStreamJob.java",
"retrieved_chunk": "\t\t\t\tDecodableStreamSource.<String>builder()\n\t\t\t\t\t.withStreamName(PURCHASE_ORDERS_STREAM)\n\t\t\t\t\t.withDeserializationSchema(new SimpleStringSchema())\n\t\t\t\t\t.build();\n\t\tDecodableStreamSink<String> sink =\n\t\t\tDecodableStreamSink.<String>builder()\n\t\t\t\t.withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n\t\t\t\t.withSerializationSchema(new SimpleStringSchema())\n\t\t\t\t.build();\n\t\tDataStream<String> stream =",
"score": 0.6441031694412231
},
{
"filename": "sdk/src/test/java/co/decodable/sdk/pipeline/snippets/PurchaseOrderProcessingJob.java",
"retrieved_chunk": " DecodableStreamSource<PurchaseOrder> source = DecodableStreamSource.<PurchaseOrder>builder()\n .withStreamName(PURCHASE_ORDERS_STREAM)\n .withDeserializationSchema(new JsonDeserializationSchema<>(PurchaseOrder.class))\n .build();\n DecodableStreamSink<PurchaseOrder> sink = DecodableStreamSink.<PurchaseOrder>builder()\n .withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n .withSerializationSchema(new JsonSerializationSchema<>())\n .build();\n // @end\n DataStream<PurchaseOrder> stream = env.fromSource(source, WatermarkStrategy.noWatermarks(), \"Purchase Orders Source\")",
"score": 0.618513286113739
}
] | 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.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.9272999167442322
},
{
"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.8456289768218994
},
{
"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.8333525657653809
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkImpl.java",
"retrieved_chunk": " public StatefulSinkWriter<T, Object> restoreWriter(\n InitContext context, Collection<Object> recoveredState) throws IOException {\n return delegate.restoreWriter(context, recoveredState);\n }\n @Override\n public SimpleVersionedSerializer<Object> getWriterStateSerializer() {\n return delegate.getWriterStateSerializer();\n }\n @Override\n public Committer<Object> createCommitter() throws IOException {",
"score": 0.8229654431343079
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DelegatingSplitEnumerator.java",
"retrieved_chunk": " public void addReader(int subtaskId) {\n delegate.addReader(subtaskId);\n }\n @Override\n public DecodableSourceEnumeratorState snapshotState(long checkpointId) throws Exception {\n return new DecodableSourceEnumeratorStateImpl(delegate.snapshotState(checkpointId));\n }\n @Override\n public void close() throws IOException {\n delegate.close();",
"score": 0.8202284574508667
}
] | 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.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.8910734057426453
},
{
"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.8120056390762329
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " private final KafkaProducer<String, String> producer;\n private final Map<String, DecodableStreamImpl> streams;\n private final ExecutorService executorService;\n /** Creates a new testing context, using the given {@link TestEnvironment}. */\n public PipelineTestContext(TestEnvironment testEnvironment) {\n EnvironmentAccess.setEnvironment(testEnvironment);\n this.testEnvironment = testEnvironment;\n this.producer =\n new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers()));\n this.streams = new HashMap<>();",
"score": 0.7333001494407654
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " /** Returns a stream for the given name. */\n public DecodableStream<String> stream(String name) {\n KafkaConsumer<String, String> consumer =\n new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers()));\n consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name)));\n return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer));\n }\n /** Asynchronously executes the given Flink job main method. */\n public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args)\n throws Exception {",
"score": 0.7331182956695557
},
{
"filename": "examples/apache-maven/custom-pipelines-hello-world/src/main/java/co/decodable/examples/cpdemo/DataStreamJob.java",
"retrieved_chunk": "\t\t\t\tDecodableStreamSource.<String>builder()\n\t\t\t\t\t.withStreamName(PURCHASE_ORDERS_STREAM)\n\t\t\t\t\t.withDeserializationSchema(new SimpleStringSchema())\n\t\t\t\t\t.build();\n\t\tDecodableStreamSink<String> sink =\n\t\t\tDecodableStreamSink.<String>builder()\n\t\t\t\t.withStreamName(PURCHASE_ORDERS_PROCESSED_STREAM)\n\t\t\t\t.withSerializationSchema(new SimpleStringSchema())\n\t\t\t\t.build();\n\t\tDataStream<String> stream =",
"score": 0.7248426675796509
}
] | 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.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": " STREAM_CONFIG_TEMPLATE,\n e.getValue().topic(),\n bootstrapServers,\n e.getValue().name())));\n }\n /** Returns the name of the Kafka topic backing the given stream. */\n public String topicFor(String streamName) {\n StreamConfiguration config = streams.get(streamName);\n if (config == null) {\n throw new IllegalArgumentException(\"Stream '\" + streamName + \"' has not been configured\");",
"score": 0.8262683153152466
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/config/StreamConfigMapping.java",
"retrieved_chunk": " @SuppressWarnings(\"unchecked\")\n StreamConfig streamConfig =\n new StreamConfig(\n streamId, streamName, (Map<String, String>) config.get(\"properties\"));\n configsByStreamId.put(streamId, streamConfig);\n configsByStreamName.put(streamName, streamConfig);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(\n String.format(\"Couldn't parse stream configuration env variable %s\", entry.getKey()),\n e);",
"score": 0.8022897243499756
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java",
"retrieved_chunk": "public class DecodableStreamSinkBuilderImpl<T> implements DecodableStreamSinkBuilder<T> {\n private String streamId;\n private String streamName;\n private SerializationSchema<T> serializationSchema;\n @Override\n public DecodableStreamSinkBuilder<T> withStreamName(String streamName) {\n this.streamName = streamName;\n return this;\n }\n @Override",
"score": 0.7918499112129211
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/internal/DecodableStreamSinkBuilderImpl.java",
"retrieved_chunk": " public DecodableStreamSinkBuilder<T> withStreamId(String streamId) {\n this.streamId = streamId;\n return this;\n }\n @Override\n public DecodableStreamSinkBuilder<T> withSerializationSchema(\n SerializationSchema<T> serializationSchema) {\n this.serializationSchema = serializationSchema;\n return this;\n }",
"score": 0.7912915945053101
},
{
"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.7877107858657837
}
] | 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.8864582777023315
},
{
"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.8097418546676636
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " private final KafkaProducer<String, String> producer;\n private final Map<String, DecodableStreamImpl> streams;\n private final ExecutorService executorService;\n /** Creates a new testing context, using the given {@link TestEnvironment}. */\n public PipelineTestContext(TestEnvironment testEnvironment) {\n EnvironmentAccess.setEnvironment(testEnvironment);\n this.testEnvironment = testEnvironment;\n this.producer =\n new KafkaProducer<String, String>(producerProperties(testEnvironment.bootstrapServers()));\n this.streams = new HashMap<>();",
"score": 0.7331395745277405
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " /** Returns a stream for the given name. */\n public DecodableStream<String> stream(String name) {\n KafkaConsumer<String, String> consumer =\n new KafkaConsumer<String, String>(consumerProperties(testEnvironment.bootstrapServers()));\n consumer.subscribe(Collections.singleton(testEnvironment.topicFor(name)));\n return streams.computeIfAbsent(name, n -> new DecodableStreamImpl(n, consumer));\n }\n /** Asynchronously executes the given Flink job main method. */\n public void runJobAsync(ThrowingConsumer<String[]> jobMainMethod, String... args)\n throws Exception {",
"score": 0.7292934656143188
},
{
"filename": "sdk/src/main/java/co/decodable/sdk/pipeline/testing/PipelineTestContext.java",
"retrieved_chunk": " this.executorService = Executors.newCachedThreadPool();\n }\n private static Properties producerProperties(String bootstrapServers) {\n var props = new Properties();\n props.put(\"bootstrap.servers\", bootstrapServers);\n props.put(\"key.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n props.put(\"value.serializer\", \"org.apache.kafka.common.serialization.StringSerializer\");\n return props;\n }\n private static Properties consumerProperties(String bootstrapServers) {",
"score": 0.7226693034172058
}
] | 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/services/ChatConfig.java",
"retrieved_chunk": " @PostConstruct\n public void initOutConfig() {\n loadingOutConfig();\n }\n private void loadingOutConfig(){\n log.info(\"################## 开始加载配置 #####################\");\n List<TbApikeyEntity> tbApikeyEntities = tbApikeyDAO.queryForList(new TbApikeyQuery());\n Map<String, Object> apikeyMap = tbApikeyEntities.stream().collect(Collectors.toMap(TbApikeyEntity::getApiKey, Function.identity()));\n redisDataHelper.setKey(Constant.API_KEY_,apikeyMap);\n log.info(\"################## 结束加载配置 #####################\");",
"score": 0.8016015291213989
},
{
"filename": "src/main/java/com/home/chat/controllers/ChatgptController.java",
"retrieved_chunk": " if(StringUtils.isBlank(request.getKey())){\n QueryUserBalanceResponse response = new QueryUserBalanceResponse();\n response.setMessage(\"请输入UserKey进行查询\");\n jo.set(\"data\",response);\n jo.set(\"status\",\"Fail\");\n return jo;\n }\n jo.set(\"status\",\"Success\");\n jo.set(\"data\",gptService.queryUserBalance(request));\n return jo;",
"score": 0.6722860932350159
},
{
"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.6626498699188232
},
{
"filename": "src/main/java/com/home/chat/dao/TbApikeyDAO.java",
"retrieved_chunk": "package com.home.chat.dao;\nimport com.home.chat.pojo.entity.TbApikeyEntity;\nimport com.home.chat.pojo.query.TbApikeyQuery;\nimport java.util.List;\n/**\n * 此类由工具自动生成,重新生成不会覆盖,可以手动修改.\n *\n * 创建日期:2023-04-10 18:06:33 星期一\n */\npublic interface TbApikeyDAO {",
"score": 0.638280987739563
},
{
"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.6326295733451843
}
] | 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 [email protected]
* @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": " 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.731305718421936
},
{
"filename": "jdbc-plus-samples/src/test/java/com/github/deeround/jdbc/plus/samples/Tests.java",
"retrieved_chunk": " @Test\n void testPageWithMp() {\n PageInfo<Map<String, Object>> page1 = this.jdbcTemplateTestService.page1();\n Page<TestUser> page2 = this.testUserService.page(new Page<TestUser>(1, 2));\n log.info(\"total:{},records:{},page1:{}\", page1.getTotal(), page1.getList().size(), page1.getList());\n log.info(\"total:{},records:{},page2:{}\", page2.getTotal(), page2.getRecords().size(), page2.getRecords());\n }\n /**\n * 条件查询:jdbc-plus和mybatis-plus查询使用对比\n */",
"score": 0.7259089946746826
},
{
"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.7241094708442688
},
{
"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.7226121425628662
},
{
"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.7188127636909485
}
] | 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.8688545227050781
},
{
"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.841799259185791
},
{
"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.8368043303489685
},
{
"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.8128533363342285
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " }\n public void resolveParameter(List<Object[]> batchParameter) {\n if (this.actionInfo != null) {\n if (batchParameter == null || batchParameter.size() == 0) {\n throw new RuntimeException(\"batchParameter不能为空\");\n }\n this.actionInfo.setBatchParameter(batchParameter);\n if (this.actionInfo.isHasParameter()) {\n if (!this.actionInfo.isParameterIsPss()) {\n if (this.actionInfo.isParameterIsBatch()) {",
"score": 0.79972904920578
}
] | 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 [email protected]
* @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/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.7590421438217163
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java",
"retrieved_chunk": " public List<Object> extractData(ResultSet rs) throws SQLException, DataAccessException {\n List<Object> query = new ArrayList<>();\n int rowNum = 0;\n while (rs.next()) {\n log.info(\"rowNum==>{}\", rowNum++);\n query.add(TestAllServiceImpl.toMap(rs));\n }\n return query;\n }\n });",
"score": 0.7540367841720581
},
{
"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.7489668726921082
},
{
"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.7472784519195557
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java",
"retrieved_chunk": " PageHelper.startPage(1, 5);\n String sql = \"select * from test_log\";\n List<Object> query = this.jdbcTemplate.query(sql, 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);\n }\n });\n PageInfo<Object> page = new PageInfo<>(query);",
"score": 0.7430636882781982
}
] | 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 [email protected]
* @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.7249329090118408
},
{
"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.7214720249176025
},
{
"filename": "jdbc-plus-samples/src/test/java/com/github/deeround/jdbc/plus/samples/Tests.java",
"retrieved_chunk": " @Test\n void testPageWithMp() {\n PageInfo<Map<String, Object>> page1 = this.jdbcTemplateTestService.page1();\n Page<TestUser> page2 = this.testUserService.page(new Page<TestUser>(1, 2));\n log.info(\"total:{},records:{},page1:{}\", page1.getTotal(), page1.getList().size(), page1.getList());\n log.info(\"total:{},records:{},page2:{}\", page2.getTotal(), page2.getRecords().size(), page2.getRecords());\n }\n /**\n * 条件查询:jdbc-plus和mybatis-plus查询使用对比\n */",
"score": 0.7192323207855225
},
{
"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.7164742946624756
},
{
"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.7163313031196594
}
] | 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.7992809414863586
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodActionInfo.java",
"retrieved_chunk": " this(false, parameterIndex, -1,\n hasReturn, returnIsList);\n this.sqlIsBatch = sqlIsBatch;\n this.parameterIsBatch = parameterIsBatch;\n }\n public MethodActionInfo() {\n //不支持方法时使用无参构造函数\n }\n}",
"score": 0.7867653369903564
},
{
"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.7804335355758667
},
{
"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.776042640209198
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " this.args[this.actionInfo.getParameterIndex()] = this.actionInfo.getBatchParameter();\n } else {\n this.args[this.actionInfo.getParameterIndex()] = this.actionInfo.getParameter();\n }\n }\n }\n }\n }\n //=================METHOD END================\n /**",
"score": 0.7583519220352173
}
] | java | .debug("finish sql==>{ |
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 [email protected]
* @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/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.8775696754455566
},
{
"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.8741825819015503
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " this.interceptors = interceptors;\n }\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;\n Object[] args = methodInvocation.getArguments();\n Method method = methodInvocation.getMethod();\n JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();\n final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);\n log.debug(\"method==>name:{},actionType:{}\", methodInfo.getName(), methodInfo.getActionInfo().getActionType());",
"score": 0.844983696937561
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java",
"retrieved_chunk": " */\n private TableNameHandler tableNameHandler;\n public DynamicTableNameInterceptor(TableNameHandler tableNameHandler) {\n this.tableNameHandler = tableNameHandler;\n }\n @Override\n public boolean supportMethod(MethodInvocationInfo methodInfo) {\n if (!methodInfo.isSupport()) {\n return false;\n }",
"score": 0.838848352432251
},
{
"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.8248493671417236
}
] | java | MethodActionInfo actionInfo = methodInfo.getActionInfo(); |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 [email protected]
*
* 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": " }\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.8420136570930481
},
{
"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.8181981444358826
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java",
"retrieved_chunk": " }\n //分页合理化,针对不合理的页码自动处理\n if ((this.reasonable != null && this.reasonable) && this.pageNum > this.pages) {\n if (this.pages != 0) {\n this.pageNum = this.pages;\n }\n this.calculateStartAndEndRow();\n }\n }\n public Boolean getReasonable() {",
"score": 0.8134866952896118
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageHelper.java",
"retrieved_chunk": " * @param count 是否进行count查询\n * @param reasonable 分页合理化,null时用默认配置\n * @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置\n */\n public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {\n Page<E> page = new Page<E>(pageNum, pageSize, count, reasonable, pageSizeZero);\n setLocalPage(page);\n return page;\n }\n /**",
"score": 0.8122782111167908
},
{
"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.806434154510498
}
] | 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 [email protected]
* @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.9239661693572998
},
{
"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.7607117891311646
},
{
"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.7589287161827087
},
{
"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.7580486536026001
},
{
"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.7429841160774231
}
] | java | ] = this.actionInfo.getParameter(); |
/*
* 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-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.8370332717895508
},
{
"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.8320828676223755
},
{
"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.8259933590888977
},
{
"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.8245365619659424
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/PaginationInterceptor.java",
"retrieved_chunk": "public class PaginationInterceptor implements IInterceptor {\n @Override\n public boolean supportMethod(final MethodInvocationInfo methodInfo) {\n if (!methodInfo.isSupport()) {\n return false;\n }\n if (MethodType.QUERY.equals(methodInfo.getType())) {\n return true;\n }\n return false;",
"score": 0.8085113167762756
}
] | java | .debug("method==>name:{ |
/*
* 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.6521256566047668
},
{
"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.5950034260749817
},
{
"filename": "src/test/java/dev/cru/context/PrintDemoConfigTest.java",
"retrieved_chunk": "\t\t\t\tList.of(\n\t\t\t\t\tnew RepoConfig.K8sLocation(\n\t\t\t\t\t\t\"kustomize/overlays/prod/patch-resources.yaml\",\n\t\t\t\t\t\t\"prod-clsuter\",\n\t\t\t\t\t\t\"prod-namespace\",\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tnull\n\t\t\t\t\t),\n\t\t\t\t\tnew RepoConfig.K8sLocation(\n\t\t\t\t\t\t\"kustomize/overlays/non-prod/patch-resources.yaml\",",
"score": 0.5733236074447632
},
{
"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.5589526295661926
},
{
"filename": "src/test/java/dev/cru/context/PrintDemoConfigTest.java",
"retrieved_chunk": "\t\t\t\t\t\t\"prod-clsuter\",\n\t\t\t\t\t\t\"non-prod-cluster\",\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tnull\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t),\n\t\t\tnull\n\t\t);\n\t\tSystem.out.println(new ObjectMapper(new YAMLFactory()).writerWithDefaultPrettyPrinter().writeValueAsString(config));",
"score": 0.5567795038223267
}
] | 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 [email protected]
* @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/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.7575052976608276
},
{
"filename": "jdbc-plus-samples/src/main/java/com/github/deeround/jdbc/plus/samples/service/impl/TestAllServiceImpl.java",
"retrieved_chunk": " public List<Object> extractData(ResultSet rs) throws SQLException, DataAccessException {\n List<Object> query = new ArrayList<>();\n int rowNum = 0;\n while (rs.next()) {\n log.info(\"rowNum==>{}\", rowNum++);\n query.add(TestAllServiceImpl.toMap(rs));\n }\n return query;\n }\n });",
"score": 0.7517682909965515
},
{
"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.7490125894546509
},
{
"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.747951865196228
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " this.args[0] = this.actionInfo.getBatchSql();\n } else {\n this.args[0] = this.actionInfo.getSql();\n }\n }\n }\n public void resolveParameter(Object[] parameter) {\n List<Object[]> objects = new ArrayList<>();\n objects.add(parameter);\n this.resolveParameter(objects);",
"score": 0.7411292791366577
}
] | 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 [email protected]
* @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/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.8437339067459106
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " this.interceptors = interceptors;\n }\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;\n Object[] args = methodInvocation.getArguments();\n Method method = methodInvocation.getMethod();\n JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();\n final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);\n log.debug(\"method==>name:{},actionType:{}\", methodInfo.getName(), methodInfo.getActionInfo().getActionType());",
"score": 0.8407645225524902
},
{
"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.8394142389297485
},
{
"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.8382406234741211
},
{
"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.8209433555603027
}
] | java | String sql = actionInfo.getSql(); |
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 [email protected]
* @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/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.81036376953125
},
{
"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.8088254928588867
},
{
"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.806501030921936
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " public void resolveSql(String sql) {\n this.resolveSql(new String[]{sql});\n }\n public void resolveSql(String[] batchSql) {\n if (this.actionInfo != null) {\n if (batchSql == null || batchSql.length == 0) {\n throw new RuntimeException(\"batchSql不能为空\");\n }\n this.actionInfo.setBatchSql(batchSql);\n if (this.actionInfo.isSqlIsBatch()) {",
"score": 0.7973930835723877
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/TenantLineInterceptor.java",
"retrieved_chunk": " @Override\n protected void processUpdate(Update update, int index, String sql, Object obj) {\n final Table table = update.getTable();\n if (this.tenantLineHandler.ignoreTable(table.getName())) {\n // 过滤退出执行\n return;\n }\n update.setWhere(this.andExpression(table, update.getWhere(), (String) obj));\n }\n /**",
"score": 0.7929966449737549
}
] | 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.
*/
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.9201631546020508
},
{
"filename": "src/main/java/dev/cru/git/GitClient.java",
"retrieved_chunk": "import org.eclipse.jgit.api.CloneCommand;\nimport org.eclipse.jgit.api.Git;\nimport org.eclipse.jgit.api.errors.GitAPIException;\npublic class GitClient {\n\tprivate final Git instance;\n\tpublic GitClient(String uri, Path temporaryFolder) {\n\t\tCloneCommand cloneCommand = Git.cloneRepository().setURI(uri).setDirectory(temporaryFolder.toFile()).setDepth(1);\n\t\ttry (Git git = cloneCommand.call()) {\n\t\t\tthis.instance = git;\n\t\t} catch (GitAPIException e) {",
"score": 0.7948984503746033
},
{
"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.77476966381073
},
{
"filename": "src/test/java/dev/cru/context/RepoConfigSchemaGeneratorTest.java",
"retrieved_chunk": "import com.github.victools.jsonschema.generator.*;\nimport dev.cru.conf.RepoConfig;\nimport org.junit.jupiter.api.Test;\nclass RepoConfigSchemaGeneratorTest {\n\t@Test\n\tvoid name() {\n\t\tSchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(\n\t\t\tSchemaVersion.DRAFT_2020_12,\n\t\t\tOptionPreset.PLAIN_JSON\n\t\t);",
"score": 0.7611474990844727
},
{
"filename": "src/main/java/dev/cru/repository/RepositoryApi.java",
"retrieved_chunk": "import dev.cru.context.Location;\npublic interface RepositoryApi {\n\tIterable<Repository> findRepositories();\n\tIterable<Location> readLocationsFrom(Repository repository);\n}",
"score": 0.7569430470466614
}
] | 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 [email protected]
* @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/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.8120654821395874
},
{
"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.8106890320777893
},
{
"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.7998988032341003
},
{
"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.7946176528930664
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " this.interceptors = interceptors;\n }\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;\n Object[] args = methodInvocation.getArguments();\n Method method = methodInvocation.getMethod();\n JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();\n final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);\n log.debug(\"method==>name:{},actionType:{}\", methodInfo.getName(), methodInfo.getActionInfo().getActionType());",
"score": 0.7757567167282104
}
] | 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-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.8447206020355225
},
{
"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.8409191370010376
},
{
"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.8310678601264954
},
{
"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.816031813621521
},
{
"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.7523216009140015
}
] | java | (methodInfo.getActionInfo().getBatchParameter())); |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 [email protected]
*
* 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": " }\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.8432798981666565
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java",
"retrieved_chunk": " }\n //分页合理化,针对不合理的页码自动处理\n if ((this.reasonable != null && this.reasonable) && this.pageNum > this.pages) {\n if (this.pages != 0) {\n this.pageNum = this.pages;\n }\n this.calculateStartAndEndRow();\n }\n }\n public Boolean getReasonable() {",
"score": 0.8172848224639893
},
{
"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.8052965402603149
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java",
"retrieved_chunk": " public void setTotal(long total) {\n this.total = total;\n if (total == -1) {\n this.pages = 1;\n return;\n }\n if (this.pageSize > 0) {\n this.pages = (int) (total / this.pageSize + ((total % this.pageSize == 0) ? 0 : 1));\n } else {\n this.pages = 0;",
"score": 0.7864488363265991
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/Page.java",
"retrieved_chunk": " }\n this.pageNum = pageNum;\n this.pageSize = pageSize;\n this.count = count;\n this.calculateStartAndEndRow();\n this.setReasonable(reasonable);\n this.setPageSizeZero(pageSizeZero);\n }\n public List<E> getResult() {\n return this;",
"score": 0.7707405686378479
}
] | java | page.getStartRow() + 1; |
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 [email protected]
* @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": " 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.7815889120101929
},
{
"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.7760658264160156
},
{
"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.7740652561187744
},
{
"filename": "jdbc-plus-samples/src/test/java/com/github/deeround/jdbc/plus/samples/Tests.java",
"retrieved_chunk": " @Test\n void testPageWithMp() {\n PageInfo<Map<String, Object>> page1 = this.jdbcTemplateTestService.page1();\n Page<TestUser> page2 = this.testUserService.page(new Page<TestUser>(1, 2));\n log.info(\"total:{},records:{},page1:{}\", page1.getTotal(), page1.getList().size(), page1.getList());\n log.info(\"total:{},records:{},page2:{}\", page2.getTotal(), page2.getRecords().size(), page2.getRecords());\n }\n /**\n * 条件查询:jdbc-plus和mybatis-plus查询使用对比\n */",
"score": 0.7629224061965942
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/pagination/PageInfo.java",
"retrieved_chunk": " if (list instanceof Page) {\n Page page = (Page) list;\n this.pageNum = page.getPageNum();\n this.pageSize = page.getPageSize();\n this.pages = page.getPages();\n this.size = page.size();\n //由于结果是>startRow的,所以实际的需要+1\n if (this.size == 0) {\n this.startRow = 0;\n this.endRow = 0;",
"score": 0.7333469390869141
}
] | java | methodInfo.resolveSql(sql); |
/*
* 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-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.8606022596359253
},
{
"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.8574472665786743
},
{
"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.8405144214630127
},
{
"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.8223508596420288
},
{
"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.7795764803886414
}
] | java | toStr(methodInfo.getActionInfo().getBatchSql())); |
/*
* 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.8567235469818115
},
{
"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.8197976350784302
},
{
"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.8171483874320984
},
{
"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.7990286350250244
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " }\n public void resolveParameter(List<Object[]> batchParameter) {\n if (this.actionInfo != null) {\n if (batchParameter == null || batchParameter.size() == 0) {\n throw new RuntimeException(\"batchParameter不能为空\");\n }\n this.actionInfo.setBatchParameter(batchParameter);\n if (this.actionInfo.isHasParameter()) {\n if (!this.actionInfo.isParameterIsPss()) {\n if (this.actionInfo.isParameterIsBatch()) {",
"score": 0.7804310321807861
}
] | java | if (methodInfo.getArgs() != null && methodInfo.getArgs().length > 0) { |
/*
* Copyright (c) 2011-2022, baomidou ([email protected]).
*
* 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": " for (Expression originOnExpression : originOnExpressions) {\n List<Table> currentTableList = onTableDeque.poll();\n if (CollectionUtils.isEmpty(currentTableList)) {\n onExpressions.add(originOnExpression);\n } else {\n onExpressions.add(this.builderExpression(originOnExpression, currentTableList, whereSegment));\n }\n }\n join.setOnExpressions(onExpressions);\n }",
"score": 0.7808291912078857
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " }\n mainTables = new ArrayList<>();\n if (mainTable != null) {\n mainTables.add(mainTable);\n }\n // 获取 join 尾缀的 on 表达式列表\n Collection<Expression> originOnExpressions = join.getOnExpressions();\n // 正常 join on 表达式只有一个,立刻处理\n if (originOnExpressions.size() == 1 && onTables != null) {\n List<Expression> onExpressions = new LinkedList<>();",
"score": 0.7730047702789307
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " onExpressions.add(this.builderExpression(originOnExpressions.iterator().next(), onTables, whereSegment));\n join.setOnExpressions(onExpressions);\n leftTable = joinTable;\n continue;\n }\n // 表名压栈,忽略的表压入 null,以便后续不处理\n onTableDeque.push(onTables);\n // 尾缀多个 on 表达式的时候统一处理\n if (originOnExpressions.size() > 1) {\n Collection<Expression> onExpressions = new LinkedList<>();",
"score": 0.770102322101593
},
{
"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.7685629725456238
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " mainTables = this.processJoins(mainTables, joins, whereSegment);\n }\n // 当有 mainTable 时,进行 where 条件追加\n if (CollectionUtils.isNotEmpty(mainTables)) {\n plainSelect.setWhere(this.builderExpression(where, mainTables, whereSegment));\n }\n }\n private List<Table> processFromItem(FromItem fromItem, final String whereSegment) {\n // 处理括号括起来的表达式\n while (fromItem instanceof ParenthesisFromItem) {",
"score": 0.7681639194488525
}
] | java | equalsTo.setRightExpression(this.tenantLineHandler.getTenantId()); |
/*
* Copyright (c) 2011-2022, baomidou ([email protected]).
*
* 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": " }\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.8672980666160583
},
{
"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.8494131565093994
},
{
"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.8463003635406494
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " /**\n * 处理 sub join\n *\n * @param subJoin subJoin\n * @return Table subJoin 中的主表\n */\n private List<Table> processSubJoin(SubJoin subJoin, final String whereSegment) {\n List<Table> mainTables = new ArrayList<>();\n if (subJoin.getJoinList() != null) {\n List<Table> list = this.processFromItem(subJoin.getLeft(), whereSegment);",
"score": 0.8429471254348755
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " mainTables = this.processJoins(mainTables, joins, whereSegment);\n }\n // 当有 mainTable 时,进行 where 条件追加\n if (CollectionUtils.isNotEmpty(mainTables)) {\n plainSelect.setWhere(this.builderExpression(where, mainTables, whereSegment));\n }\n }\n private List<Table> processFromItem(FromItem fromItem, final String whereSegment) {\n // 处理括号括起来的表达式\n while (fromItem instanceof ParenthesisFromItem) {",
"score": 0.8308286070823669
}
] | java | new EqualsTo(this.getAliasColumn(table), this.tenantLineHandler.getTenantId()); |
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 [email protected]
* @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/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.8610690832138062
},
{
"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.8505620360374451
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " this.interceptors = interceptors;\n }\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;\n Object[] args = methodInvocation.getArguments();\n Method method = methodInvocation.getMethod();\n JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();\n final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);\n log.debug(\"method==>name:{},actionType:{}\", methodInfo.getName(), methodInfo.getActionInfo().getActionType());",
"score": 0.8316035270690918
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/DynamicTableNameInterceptor.java",
"retrieved_chunk": " */\n private TableNameHandler tableNameHandler;\n public DynamicTableNameInterceptor(TableNameHandler tableNameHandler) {\n this.tableNameHandler = tableNameHandler;\n }\n @Override\n public boolean supportMethod(MethodInvocationInfo methodInfo) {\n if (!methodInfo.isSupport()) {\n return false;\n }",
"score": 0.8129807710647583
},
{
"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.809705913066864
}
] | java | (methodInfo.getActionInfo().isReturnIsList()) { |
/*
* Copyright (c) 2011-2022, baomidou ([email protected]).
*
* 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": " 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.8415244221687317
},
{
"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.8279331922531128
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " for (Expression originOnExpression : originOnExpressions) {\n List<Table> currentTableList = onTableDeque.poll();\n if (CollectionUtils.isEmpty(currentTableList)) {\n onExpressions.add(originOnExpression);\n } else {\n onExpressions.add(this.builderExpression(originOnExpression, currentTableList, whereSegment));\n }\n }\n join.setOnExpressions(onExpressions);\n }",
"score": 0.8252861499786377
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " if (where == null) {\n return;\n }\n if (where instanceof FromItem) {\n this.processOtherFromItem((FromItem) where, whereSegment);\n return;\n }\n if (where.toString().indexOf(\"SELECT\") > 0) {\n // 有子查询\n if (where instanceof BinaryExpression) {",
"score": 0.825006365776062
},
{
"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.8248966932296753
}
] | java | (new SelectExpressionItem(new Column(this.tenantLineHandler.getTenantIdColumn()))); |
/*
* 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.9612818956375122
},
{
"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.9225109815597534
},
{
"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.8874013423919678
},
{
"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.8691271543502808
},
{
"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.8688749670982361
}
] | 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/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.9091814160346985
},
{
"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.9057618379592896
},
{
"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.8958189487457275
},
{
"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.8690576553344727
},
{
"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.867104709148407
}
] | java | DataType.buildFormattedString(elementType, 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;
/*
* 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/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.9249545931816101
},
{
"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.8835813999176025
},
{
"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.866128146648407
},
{
"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.8625772595405579
},
{
"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.8517252802848816
}
] | 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/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.9175966382026672
},
{
"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.8967013359069824
},
{
"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.8590292930603027
},
{
"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.8353801965713501
},
{
"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.8276616334915161
}
] | java | prefix, valueType.getTypeName(),
valueContainsNull)); |
/*
* 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/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.9152712821960449
},
{
"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.898408830165863
},
{
"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.8898160457611084
},
{
"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.8872703313827515
},
{
"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.869875967502594
}
] | java | .format("%s-- element: %s (containsNull = %b)\n", prefix, elementType.getTypeName(),
containsNull)); |
/*
* 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/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.931701123714447
},
{
"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.8839607238769531
},
{
"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.8713127374649048
},
{
"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.865774393081665
},
{
"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.8510209321975708
}
] | java | dataType.getTypeName(), nullable, metadata.toString())); |
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.6747528910636902
},
{
"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.6723462343215942
},
{
"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.6695092916488647
},
{
"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.6664559841156006
},
{
"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.6614222526550293
}
] | 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/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.6946758031845093
},
{
"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.6793303489685059
},
{
"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.6705994606018066
},
{
"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.668346643447876
},
{
"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.6668116450309753
}
] | 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.7075679302215576
},
{
"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.6995766758918762
},
{
"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.6879023313522339
},
{
"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.6850181818008423
},
{
"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.6811932325363159
}
] | 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 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.9505358934402466
},
{
"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.9119336605072021
},
{
"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.8882431387901306
},
{
"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.8804790377616882
},
{
"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.865288257598877
}
] | 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/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.8547469973564148
},
{
"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.8493403196334839
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " }\n private int maxInset(Insets shadowInsets) {\n return Math.max(Math.max(shadowInsets.left, shadowInsets.right), Math.max(shadowInsets.top, shadowInsets.bottom));\n }\n @Override\n public Insets getBorderInsets() {\n return UIScale.scale(super.getBorderInsets());\n }\n @Override\n public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {",
"score": 0.8478217124938965
},
{
"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.8357120752334595
},
{
"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.8281294107437134
}
] | java | Insets insets = UIUtils.getInsets("Toast.shadowInsets", new Insets(0, 0, 6, 6)); |
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": " 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.8384321928024292
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " int outlineWidth = FlatPropertiesLaf.getStyleableValue(com, \"outlineWidth\");\n if (outlineWidth > 0) {\n Color outlineColor = FlatPropertiesLaf.getStyleableValue(com, \"outlineColor\");\n g2.setColor(outlineColor);\n FlatUIUtils.paintOutline(g2, lx, ly, lw, lh, UIScale.scale(outlineWidth), UIScale.scale(arc));\n }\n g2.dispose();\n }\n private void createEffect(JComponent c, Graphics2D g2, int x, int y, int width, int height, int arc) {\n Color effectColor = FlatPropertiesLaf.getStyleableValue(c, \"effectColor\");",
"score": 0.8094028830528259
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " float effectWidth = FlatPropertiesLaf.getStyleableValue(c, \"effectWidth\");\n float effectOpacity = FlatPropertiesLaf.getStyleableValue(c, \"effectOpacity\");\n boolean effectRight = FlatPropertiesLaf.getStyleableValue(c, \"effectAlignment\").equals(\"right\");\n if (!effectRight) {\n g2.setPaint(new GradientPaint(x, 0, effectColor, x + (width * effectWidth), 0, c.getBackground()));\n } else {\n g2.setPaint(new GradientPaint(x + width, 0, effectColor, x + width - (width * effectWidth), 0, c.getBackground()));\n }\n g2.setComposite(AlphaComposite.SrcOver.derive(effectOpacity));\n if (arc > 0) {",
"score": 0.809091329574585
},
{
"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.7984640598297119
},
{
"filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java",
"retrieved_chunk": " private String toTextColor(Color color) {\n return \"rgb(\" + color.getRed() + \",\" + color.getGreen() + \",\" + color.getBlue() + \")\";\n }\n public Icon getDefaultIcon() {\n String key = getKey();\n Icon icon = UIManager.getIcon(\"Toast.\" + key + \".icon\");\n if (icon != null) {\n return icon;\n }\n FlatSVGIcon svgIcon = new FlatSVGIcon(\"raven/toast/svg/\" + key + \".svg\");",
"score": 0.7566289901733398
}
] | 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.8740140199661255
},
{
"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.7762537002563477
},
{
"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.7719894647598267
},
{
"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.7180851101875305
},
{
"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.7140817642211914
}
] | 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": " 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.8624425530433655
},
{
"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.8325818181037903
},
{
"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.8105596303939819
},
{
"filename": "src/main/java/raven/toast/ui/ToastPanelUI.java",
"retrieved_chunk": " button.setFocusable(false);\n button.setName(\"Toast.closeButton\");\n button.putClientProperty(BUTTON_TYPE, BUTTON_TYPE_TOOLBAR_BUTTON);\n button.putClientProperty(STYLE, \"\" +\n \"arc:999\");\n button.setIcon(closeButtonIcon);\n button.addActionListener(e -> closeButtonClicked(c));\n return button;\n }\n protected void closeButtonClicked(JComponent c) {",
"score": 0.7978006601333618
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": "import java.awt.event.ActionListener;\nimport java.util.Random;\npublic class Test extends JFrame {\n public Test() {\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setSize(1000, 768);\n setLocationRelativeTo(null);\n getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));\n JButton button = new JButton(\"Show\");\n Notifications.getInstance().setJFrame(this);",
"score": 0.7942894697189331
}
] | java | toastNotificationPanel.setDialog(window); |
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.8561873435974121
},
{
"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.7767831683158875
},
{
"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.76148521900177
},
{
"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.7303492426872253
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": " } else {\n return Notifications.Type.ERROR;\n }\n }\n private void changeMode(boolean dark) {\n if (FlatLaf.isLafDark() != dark) {\n if (dark) {\n EventQueue.invokeLater(() -> {\n FlatAnimatedLafChange.showSnapshot();\n FlatDarculaLaf.setup();",
"score": 0.7273027896881104
}
] | 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/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.8476263284683228
},
{
"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.7781461477279663
},
{
"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.7774983644485474
},
{
"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.7603161334991455
},
{
"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.754875898361206
}
] | java | hold = notificationHolder.getHold(notificationAnimation.getLocation()); |
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": " 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.8421165943145752
},
{
"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.8376118540763855
},
{
"filename": "src/main/java/raven/toast/ui/ToastPanelUI.java",
"retrieved_chunk": " super.uninstallDefaults(p);\n oldStyleValues = null;\n }\n protected Border createDefaultBorder() {\n Color color = FlatUIUtils.getUIColor(\"Toast.shadowColor\", new Color(0, 0, 0));\n Insets insets = UIUtils.getInsets(\"Toast.shadowInsets\", new Insets(0, 0, 6, 6));\n float shadowOpacity = FlatUIUtils.getUIFloat(\"Toast.shadowOpacity\", 0.1f);\n return new DropShadowBorder(color, insets, shadowOpacity);\n }\n protected String getPropertyPrefix() {",
"score": 0.8348418474197388
},
{
"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.8173208832740784
},
{
"filename": "src/main/java/raven/toast/ui/ToastPanelUI.java",
"retrieved_chunk": " }\n @Override\n public void layoutContainer(Container parent) {\n synchronized (parent.getTreeLock()) {\n Insets insets = FlatUIUtils.addInsets(parent.getInsets(), UIScale.scale(margin));\n int x = insets.left;\n int y = insets.top;\n int height = 0;\n if (iconComponent != null) {\n int iconW = iconComponent.getPreferredSize().width;",
"score": 0.8041427135467529
}
] | java | UIUtils.getInsets("Toast.frameInsets", new Insets(10, 10, 10, 10)); |
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": " 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.8448166847229004
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " int outlineWidth = FlatPropertiesLaf.getStyleableValue(com, \"outlineWidth\");\n if (outlineWidth > 0) {\n Color outlineColor = FlatPropertiesLaf.getStyleableValue(com, \"outlineColor\");\n g2.setColor(outlineColor);\n FlatUIUtils.paintOutline(g2, lx, ly, lw, lh, UIScale.scale(outlineWidth), UIScale.scale(arc));\n }\n g2.dispose();\n }\n private void createEffect(JComponent c, Graphics2D g2, int x, int y, int width, int height, int arc) {\n Color effectColor = FlatPropertiesLaf.getStyleableValue(c, \"effectColor\");",
"score": 0.807631254196167
},
{
"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.7801735997200012
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " float effectWidth = FlatPropertiesLaf.getStyleableValue(c, \"effectWidth\");\n float effectOpacity = FlatPropertiesLaf.getStyleableValue(c, \"effectOpacity\");\n boolean effectRight = FlatPropertiesLaf.getStyleableValue(c, \"effectAlignment\").equals(\"right\");\n if (!effectRight) {\n g2.setPaint(new GradientPaint(x, 0, effectColor, x + (width * effectWidth), 0, c.getBackground()));\n } else {\n g2.setPaint(new GradientPaint(x + width, 0, effectColor, x + width - (width * effectWidth), 0, c.getBackground()));\n }\n g2.setComposite(AlphaComposite.SrcOver.derive(effectOpacity));\n if (arc > 0) {",
"score": 0.7780996561050415
},
{
"filename": "src/main/java/raven/toast/ui/ToastNotificationPanel.java",
"retrieved_chunk": " private String toTextColor(Color color) {\n return \"rgb(\" + color.getRed() + \",\" + color.getGreen() + \",\" + color.getBlue() + \")\";\n }\n public Icon getDefaultIcon() {\n String key = getKey();\n Icon icon = UIManager.getIcon(\"Toast.\" + key + \".icon\");\n if (icon != null) {\n return icon;\n }\n FlatSVGIcon svgIcon = new FlatSVGIcon(\"raven/toast/svg/\" + key + \".svg\");",
"score": 0.7603926062583923
}
] | java | + ".closeIcon", UIUtils.createIcon("raven/toast/svg/close.svg", closeIconColor, 0.75f)); |
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": " 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.8453470468521118
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " int outlineWidth = FlatPropertiesLaf.getStyleableValue(com, \"outlineWidth\");\n if (outlineWidth > 0) {\n Color outlineColor = FlatPropertiesLaf.getStyleableValue(com, \"outlineColor\");\n g2.setColor(outlineColor);\n FlatUIUtils.paintOutline(g2, lx, ly, lw, lh, UIScale.scale(outlineWidth), UIScale.scale(arc));\n }\n g2.dispose();\n }\n private void createEffect(JComponent c, Graphics2D g2, int x, int y, int width, int height, int arc) {\n Color effectColor = FlatPropertiesLaf.getStyleableValue(c, \"effectColor\");",
"score": 0.813861608505249
},
{
"filename": "src/main/java/raven/toast/ui/DropShadowBorder.java",
"retrieved_chunk": " float effectWidth = FlatPropertiesLaf.getStyleableValue(c, \"effectWidth\");\n float effectOpacity = FlatPropertiesLaf.getStyleableValue(c, \"effectOpacity\");\n boolean effectRight = FlatPropertiesLaf.getStyleableValue(c, \"effectAlignment\").equals(\"right\");\n if (!effectRight) {\n g2.setPaint(new GradientPaint(x, 0, effectColor, x + (width * effectWidth), 0, c.getBackground()));\n } else {\n g2.setPaint(new GradientPaint(x + width, 0, effectColor, x + width - (width * effectWidth), 0, c.getBackground()));\n }\n g2.setComposite(AlphaComposite.SrcOver.derive(effectOpacity));\n if (arc > 0) {",
"score": 0.7722275257110596
},
{
"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.7622441053390503
},
{
"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.7510851621627808
}
] | 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.8563380837440491
},
{
"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.8493618965148926
},
{
"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.8353731632232666
},
{
"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.7748832702636719
},
{
"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.7637293934822083
}
] | java | notificationHolder.clearHold(location); |
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.8187394142150879
},
{
"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.8128294944763184
},
{
"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.8046468496322632
},
{
"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.8040794134140015
},
{
"filename": "src/test/java/raven/demo/Test.java",
"retrieved_chunk": " CustomNotification customNotification = new CustomNotification();\n customNotification.setJFrame(this);\n button.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n Notifications.getInstance().show(getRandomType(), Notifications.Location.TOP_RIGHT, getRandomText());\n }\n });\n JButton cmdMode = new JButton(\"Mode Light\");\n cmdMode.addActionListener(new ActionListener() {",
"score": 0.7843543887138367
}
] | java | toastNotificationPanel.set(type, message); |
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.8023015260696411
},
{
"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.8014600276947021
},
{
"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.7936276197433472
},
{
"filename": "src/main/java/raven/toast/ui/ToastPanelUI.java",
"retrieved_chunk": " super.uninstallDefaults(p);\n oldStyleValues = null;\n }\n protected Border createDefaultBorder() {\n Color color = FlatUIUtils.getUIColor(\"Toast.shadowColor\", new Color(0, 0, 0));\n Insets insets = UIUtils.getInsets(\"Toast.shadowInsets\", new Insets(0, 0, 6, 6));\n float shadowOpacity = FlatUIUtils.getUIFloat(\"Toast.shadowOpacity\", 0.1f);\n return new DropShadowBorder(color, insets, shadowOpacity);\n }\n protected String getPropertyPrefix() {",
"score": 0.7898814678192139
},
{
"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.7877178192138672
}
] | java | notificationHolder.hold(notificationAnimation); |
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/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.8448711037635803
},
{
"filename": "src/main/java/transformations/MoveBy.java",
"retrieved_chunk": " protected Point transformPoint(Point originalPoint) {\n Point newPoint = new Point(originalPoint.getX() + x, originalPoint.getY() + y);\n return newPoint;\n }\n}",
"score": 0.8227705955505371
},
{
"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.818095862865448
},
{
"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.8131020069122314
},
{
"filename": "src/main/java/primitives/Quadrilateral.java",
"retrieved_chunk": " public Quadrilateral(Point vertex1, Point vertex2, Point vertex3, Point vertex4) {\n this.vertex1 = vertex1;\n this.vertex2 = vertex2;\n this.vertex3 = vertex3;\n this.vertex4 = vertex4;\n }\n @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n result.addAll(new Line(vertex1, vertex2).getPoints());",
"score": 0.8064224720001221
}
] | java | lowerLeft.getX(), lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints(); |
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/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.8449969291687012
},
{
"filename": "src/main/java/transformations/MoveBy.java",
"retrieved_chunk": " protected Point transformPoint(Point originalPoint) {\n Point newPoint = new Point(originalPoint.getX() + x, originalPoint.getY() + y);\n return newPoint;\n }\n}",
"score": 0.8226490616798401
},
{
"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.8199755549430847
},
{
"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.8126351833343506
},
{
"filename": "src/main/java/primitives/Quadrilateral.java",
"retrieved_chunk": " public Quadrilateral(Point vertex1, Point vertex2, Point vertex3, Point vertex4) {\n this.vertex1 = vertex1;\n this.vertex2 = vertex2;\n this.vertex3 = vertex3;\n this.vertex4 = vertex4;\n }\n @Override\n public List<Point> getPoints() {\n List<Point> result = new ArrayList<>();\n result.addAll(new Line(vertex1, vertex2).getPoints());",
"score": 0.808268666267395
}
] | java | lowerLeft.getY()).transform(new GenericShape(originalPoints)).getPoints(); |
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/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.8459103107452393
},
{
"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.8015162348747253
},
{
"filename": "src/main/java/sprites/House.java",
"retrieved_chunk": "import java.util.List;\npublic class House extends CompositeShape {\n private final Point lowerLeft;\n public House(Point lowerLeft) {\n this.lowerLeft = lowerLeft;\n }\n @Override\n protected List<Shape> getShapes() {\n List<Shape> allShapes = new ArrayList<>();\n allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall",
"score": 0.7850043773651123
},
{
"filename": "src/main/java/canvas/TextCanvas.java",
"retrieved_chunk": " private String UNSET = \" · \";\n public TextCanvas(int width, int height) {\n this.width = width;\n this.height = height;\n this.pixels = new Pixel[height][width];\n clean();\n }\n public void clean() {\n for (Pixel[] row : pixels) {\n Arrays.fill(row, new Pixel(false));",
"score": 0.773296594619751
},
{
"filename": "src/main/java/transformations/MoveBy.java",
"retrieved_chunk": " protected Point transformPoint(Point originalPoint) {\n Point newPoint = new Point(originalPoint.getX() + x, originalPoint.getY() + y);\n return newPoint;\n }\n}",
"score": 0.7715920209884644
}
] | java | getX() * factor, point.getY() * factor + 50, factor, factor); |
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.8148072361946106
},
{
"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.7708814144134521
},
{
"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.7548452019691467
},
{
"filename": "src/main/java/domain/Point.java",
"retrieved_chunk": "package domain;\npublic class Point {\n private final int x;\n private final int y;\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n public int getX() {\n return x;",
"score": 0.7515939474105835
},
{
"filename": "src/main/java/domain/Point.java",
"retrieved_chunk": " }\n public int getY() {\n return y;\n }\n @Override\n public String toString() {\n return \"Point{\" +\n \"x=\" + x +\n \", y=\" + y +\n '}';",
"score": 0.749472975730896
}
] | 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.8705421090126038
},
{
"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.8446903228759766
},
{
"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.8188475370407104
},
{
"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.8069028854370117
},
{
"filename": "src/main/java/sprites/House.java",
"retrieved_chunk": "import java.util.List;\npublic class House extends CompositeShape {\n private final Point lowerLeft;\n public House(Point lowerLeft) {\n this.lowerLeft = lowerLeft;\n }\n @Override\n protected List<Shape> getShapes() {\n List<Shape> allShapes = new ArrayList<>();\n allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall",
"score": 0.8006951212882996
}
] | java | (point.getX(), point.getY()); |
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/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.8450777530670166
},
{
"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.7983204126358032
},
{
"filename": "src/main/java/sprites/House.java",
"retrieved_chunk": "import java.util.List;\npublic class House extends CompositeShape {\n private final Point lowerLeft;\n public House(Point lowerLeft) {\n this.lowerLeft = lowerLeft;\n }\n @Override\n protected List<Shape> getShapes() {\n List<Shape> allShapes = new ArrayList<>();\n allShapes.add(new Rectangle(new Point(0, 0), new Point(26, 20))); //wall",
"score": 0.7856121063232422
},
{
"filename": "src/main/java/canvas/TextCanvas.java",
"retrieved_chunk": " private String UNSET = \" · \";\n public TextCanvas(int width, int height) {\n this.width = width;\n this.height = height;\n this.pixels = new Pixel[height][width];\n clean();\n }\n public void clean() {\n for (Pixel[] row : pixels) {\n Arrays.fill(row, new Pixel(false));",
"score": 0.7721410989761353
},
{
"filename": "src/main/java/canvas/TextCanvas.java",
"retrieved_chunk": " }\n }\n @Override\n public void show() {\n for (int y = height - 1; y >= 0; y--) {\n if (y % 5 == 0) {\n System.out.print(String.format(\"%1$3s\", y));\n } else {\n System.out.print(\" \");\n }",
"score": 0.7721049785614014
}
] | java | .drawOval(point.getX() * factor, point.getY() * factor + 50, factor, factor); |
/*
* Copyright (c) 2011-2022, baomidou ([email protected]).
*
* 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": " for (Expression originOnExpression : originOnExpressions) {\n List<Table> currentTableList = onTableDeque.poll();\n if (CollectionUtils.isEmpty(currentTableList)) {\n onExpressions.add(originOnExpression);\n } else {\n onExpressions.add(this.builderExpression(originOnExpression, currentTableList, whereSegment));\n }\n }\n join.setOnExpressions(onExpressions);\n }",
"score": 0.8186310529708862
},
{
"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.8167568445205688
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/Interceptor/BaseMultiTableInterceptor.java",
"retrieved_chunk": " *\n * @param function\n */\n protected void processFunction(Function function, final String whereSegment) {\n ExpressionList parameters = function.getParameters();\n if (parameters != null) {\n parameters.getExpressions().forEach(expression -> {\n if (expression instanceof SubSelect) {\n this.processSelectBody(((SubSelect) expression).getSelectBody(), whereSegment);\n } else if (expression instanceof Function) {",
"score": 0.7955412864685059
},
{
"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.7921340465545654
},
{
"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.789485514163971
}
] | java | ExceptionUtils.mpe("Failed to process multiple-table update, please exclude the tableName or statementId"); |
/*
* Copyright (c) 2011-2022, baomidou ([email protected]).
*
* 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.9714236855506897
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " this.args[0] = this.actionInfo.getBatchSql();\n } else {\n this.args[0] = this.actionInfo.getSql();\n }\n }\n }\n public void resolveSql(int i, String sql) {\n if (this.actionInfo != null) {\n this.actionInfo.getBatchSql()[i] = sql;\n if (this.actionInfo.isSqlIsBatch()) {",
"score": 0.8848139047622681
},
{
"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.8711605072021484
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/method/MethodInvocationInfo.java",
"retrieved_chunk": " public void resolveSql(String sql) {\n this.resolveSql(new String[]{sql});\n }\n public void resolveSql(String[] batchSql) {\n if (this.actionInfo != null) {\n if (batchSql == null || batchSql.length == 0) {\n throw new RuntimeException(\"batchSql不能为空\");\n }\n this.actionInfo.setBatchSql(batchSql);\n if (this.actionInfo.isSqlIsBatch()) {",
"score": 0.8657947182655334
},
{
"filename": "jdbc-plus-spring-boot-starter/src/main/java/com/github/deeround/jdbc/plus/aop/JdbcTemplateMethodInterceptor.java",
"retrieved_chunk": " this.interceptors = interceptors;\n }\n @Override\n public Object invoke(MethodInvocation invocation) throws Throwable {\n ReflectiveMethodInvocation methodInvocation = (ReflectiveMethodInvocation) invocation;\n Object[] args = methodInvocation.getArguments();\n Method method = methodInvocation.getMethod();\n JdbcTemplate jdbcTemplate = (JdbcTemplate) methodInvocation.getThis();\n final MethodInvocationInfo methodInfo = new MethodInvocationInfo(args, method);\n log.debug(\"method==>name:{},actionType:{}\", methodInfo.getName(), methodInfo.getActionInfo().getActionType());",
"score": 0.8550276756286621
}
] | java | , this.parserMulti(methodInfo.getActionInfo().getBatchSql()[i], null)); |
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/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.7882720828056335
},
{
"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.7469701766967773
},
{
"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.7433757781982422
},
{
"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.728066086769104
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/GrayMessageListener.java",
"retrieved_chunk": " public Action consume(Message message, ConsumeContext context) {\n if(message.getTopic().endsWith(GrayscaleConstant.GRAY_TOPIC_SUFFIX)){\n GrayParamHolder.putValue(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n GrayParamHolder.putValue(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n log.info(\"为当前mq设置传递灰度标识。\");\n }\n Action result= messageListener.consume(message,context);\n GrayParamHolder.clearValue();\n return result;\n }",
"score": 0.7184035778045654
}
] | 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/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.7970681190490723
},
{
"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.7698171734809875
},
{
"filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java",
"retrieved_chunk": " *\n * @param map\n */\n public static void putValues(Map<String,String> map) {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if (Objects.isNull(paramMap) || paramMap.isEmpty()) {\n paramMap = new HashMap<>(6);\n GrayParamHolder.paramLocal.set(paramMap);\n }\n if(Objects.nonNull(map)&&!map.isEmpty()){",
"score": 0.7560631036758423
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/GrayMessageListener.java",
"retrieved_chunk": " public Action consume(Message message, ConsumeContext context) {\n if(message.getTopic().endsWith(GrayscaleConstant.GRAY_TOPIC_SUFFIX)){\n GrayParamHolder.putValue(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n GrayParamHolder.putValue(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);\n log.info(\"为当前mq设置传递灰度标识。\");\n }\n Action result= messageListener.consume(message,context);\n GrayParamHolder.clearValue();\n return result;\n }",
"score": 0.7471650838851929
},
{
"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.742228627204895
}
] | 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/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.8126227259635925
},
{
"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.8088774085044861
},
{
"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.8042300939559937
},
{
"filename": "src/main/java/com/easyhome/common/nacos/NacosMetadataConfig.java",
"retrieved_chunk": " log.info(\"注册服务添加元数据:当前实例是否为灰度环境-{}\", grayFlg);\n nacosDiscoveryProperties.getMetadata().put(GrayscaleConstant.POD_GRAY, grayFlg);\n if(Objects.equals(grayFlg,GrayscaleConstant.STR_BOOLEAN_TRUE)){\n String groupFlg = GrayUtil.podGroup();\n nacosDiscoveryProperties.getMetadata().put(GrayscaleConstant.GRAY_GROUP, groupFlg);\n }\n return new NacosWatch(nacosDiscoveryProperties);\n }\n}",
"score": 0.7729681730270386
},
{
"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.7669374942779541
}
] | 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/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.8510282039642334
},
{
"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.8006350994110107
},
{
"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.7799892425537109
},
{
"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.7715326547622681
},
{
"filename": "src/main/java/com/easyhome/common/job/JavaGrayProcessor.java",
"retrieved_chunk": " * @author wangshufeng\n */\n@Slf4j\npublic abstract class JavaGrayProcessor implements JobProcessor {\n @Override\n public void preProcess(JobContext context) throws Exception {\n GrayParamHolder.clearValue();\n if (GrayUtil.isGrayPod()) {\n GrayParamHolder.putValue(GrayscaleConstant.HEADER_KEY, GrayscaleConstant.HEADER_VALUE);\n GrayParamHolder.putValue(GrayscaleConstant.PRINT_HEADER_LOG_KEY, GrayscaleConstant.STR_BOOLEAN_TRUE);",
"score": 0.7660701274871826
}
] | java | if(GrayUtil.isGrayPod()){ |
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/python/NumpyArray.java",
"retrieved_chunk": " * @return the integer at that index.\n */\n public static int getInt(final Object array, final int ix)\n {\n return ((NumpyArray) array).getInt(ix);\n }\n /**\n * Helper for extracting a long from what we know is a\n * 1D {@code NumpyArray}.\n *",
"score": 0.9068368077278137
},
{
"filename": "java/src/main/java/com/deshaw/python/NumpyArray.java",
"retrieved_chunk": " * Helper for extracting a double from what we know is a\n * 1D {@code NumpyArray}.\n *\n * @param array The array to get the value from.\n * @param ix The index of the element to get.\n *\n * @return the double at that index.\n */\n public static double getDouble(Object array, int ix)\n {",
"score": 0.8951374888420105
},
{
"filename": "java/src/main/java/com/deshaw/python/NumpyArray.java",
"retrieved_chunk": " /**\n * Number of array dimensions (same as {@code shape().length}).\n *\n * @return the dimensionality of this array.\n */\n public int numDimensions()\n {\n return myNumDimensions;\n }\n /**",
"score": 0.890723466873169
},
{
"filename": "java/src/main/java/com/deshaw/python/NumpyArray.java",
"retrieved_chunk": " * @param array The array to get the value from.\n * @param ix The index of the element to get.\n *\n * @return the long at that index.\n */\n public static long getLong(final Object array, final int ix)\n {\n return ((NumpyArray) array).getLong(ix);\n }\n /**",
"score": 0.8904052972793579
},
{
"filename": "java/src/main/java/com/deshaw/python/NumpyArray.java",
"retrieved_chunk": " * @return the copy.\n */\n public NumpyArray copy()\n {\n return asType(myDType, true, myIsFortran, false);\n }\n /**\n * Return the array with the same contents as this array, cast to a specific\n * type.\n *",
"score": 0.8859652280807495
}
] | java | array.validateShape(String.valueOf(key), expectedShape); |
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.7690231204032898
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " for (SubscriptionData item : subscribes) {\n if (Objects.nonNull(consumerGray)) {\n consumerGray.subscribe(GrayUtil.topicGrayName(item.getTopic()), item.getSubExpression(), item.getListener());\n }\n }\n shutdownConsumerProduction();\n }\n }\n /**\n * 添加订阅规则",
"score": 0.7626701593399048
},
{
"filename": "src/main/java/com/easyhome/common/job/JavaGrayProcessor.java",
"retrieved_chunk": " log.info(\"当前实例是否为灰度环境:true,Job设置传递灰度标识。\");\n }\n }\n @Override\n public ProcessResult postProcess(JobContext context) {\n GrayParamHolder.clearValue();\n return null;\n }\n @Override\n public void kill(JobContext context) {",
"score": 0.7589609026908875
},
{
"filename": "src/main/java/com/easyhome/common/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " return null;\n }\n }\n /**\n * 根据当前请求是否为灰度过滤服务实例列表\n *\n * @param instances\n * @return List<Instance>\n */\n private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) {",
"score": 0.7571558952331543
},
{
"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.7553274035453796
}
] | java | info("当前实例监听mq队列的状态:{ |
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": " * Listen for incoming data. We do this while the connection is still\n * good.\n */\n private void listen()\n {\n // Variables for stats gathering\n final long startTimeMs = System.currentTimeMillis();\n int numRequests = 0;\n // How we pull in the data\n final ByteList payload = new ByteList(1024 * 1024);",
"score": 0.8664780855178833
},
{
"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.8607931137084961
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " private volatile VirtualThread myThread = null;\n private volatile int myRequestId = -1;\n private final ByteList myPayload = new ByteList(1024 * 1024);\n private volatile DataOutputStream myOut = null;\n /**\n * This gets set to false if we are ever done. It is IMPORTANT that\n * it is never set to false when this thread is in the worker queue,\n * otherwise you will lose messages.\n */\n private volatile boolean myActive = true;",
"score": 0.851646900177002
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " // Nope, handle directly, and time it here\n final Instrumentor instr = myInstrumentors[type.ordinal()];\n final long start = instr.start();\n // Whether we acquired the global lock, or not\n boolean lockedGlobal = false;\n // The result goes in here. It's important that\n // no-one else uses this buffer for anything; we own\n // it here.\n final ByteArrayDataOutputStream sendBuf = mySendBufs.get();\n // Do all this inside a try-catch since we don't",
"score": 0.8390343189239502
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " final Transport.Provider provider,\n final boolean useGlobalLock,\n final boolean useShmdata,\n final PJRmiLockManager lockManager)\n throws IOException\n {\n // Set up our thread nicely\n super(name);\n setDaemon(true);\n // Very simply, create the connection and set it running; we make it",
"score": 0.8334538340568542
}
] | java | myJavaInputStream = in.getInputStream(); |
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.7685447335243225
},
{
"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.763403594493866
},
{
"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.7513833045959473
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " if (Objects.nonNull(consumer)) {\n consumer.subscribe(item.getTopic(), item.getSubExpression(), item.getListener());\n }\n if (Objects.nonNull(consumerGray)) {\n consumerGray.subscribe(GrayUtil.topicGrayName(item.getTopic()), item.getSubExpression(), item.getListener());\n }\n }\n }\n if (ListenerStateEnum.GRAYSCALE.equals(listenerStateEnum)) {\n initConsumerGray();",
"score": 0.7447282075881958
},
{
"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.7310746908187866
}
] | java | =GrayUtil.requestGroup(); |
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": " 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.8403552770614624
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " myIn = (inStream instanceof DataInputStream) ?\n (DataInputStream)inStream : new DataInputStream(inStream);\n myOut =\n new DataOutputStream(\n new BufferedOutputStream(outStream, 65536)\n );\n // How we render with pickle in a best-effort fashion\n myBestEffortPythonPickle =\n ThreadLocal.withInitial(BestEffortPythonPickle::new);\n // Try to ensure that all the handles have a reasonably unique",
"score": 0.8369244933128357
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " throws ClassCastException,\n IOException,\n PythonCallbackException\n {\n // The python callback request ID\n final int requestId = myPythonCallbackRequestId.getAndIncrement();\n // Get the thread ID\n final long threadId = getThreadId();\n // Build the data to make the call\n final ByteArrayDataOutputStream bados = ourByteOutBuffer.get();",
"score": 0.8328131437301636
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " * Listen for incoming data. We do this while the connection is still\n * good.\n */\n private void listen()\n {\n // Variables for stats gathering\n final long startTimeMs = System.currentTimeMillis();\n int numRequests = 0;\n // How we pull in the data\n final ByteList payload = new ByteList(1024 * 1024);",
"score": 0.8262312412261963
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " // Nope, handle directly, and time it here\n final Instrumentor instr = myInstrumentors[type.ordinal()];\n final long start = instr.start();\n // Whether we acquired the global lock, or not\n boolean lockedGlobal = false;\n // The result goes in here. It's important that\n // no-one else uses this buffer for anything; we own\n // it here.\n final ByteArrayDataOutputStream sendBuf = mySendBufs.get();\n // Do all this inside a try-catch since we don't",
"score": 0.8255785703659058
}
] | java | myPythonInputStream = out.getInputStream(); |
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/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " return null;\n }\n }\n /**\n * 根据当前请求是否为灰度过滤服务实例列表\n *\n * @param instances\n * @return List<Instance>\n */\n private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) {",
"score": 0.8726658225059509
},
{
"filename": "src/main/java/com/easyhome/common/feign/GrayParamHolder.java",
"retrieved_chunk": " public static String getValue(String key) {\n Map<String, String> paramMap = GrayParamHolder.paramLocal.get();\n if (Objects.nonNull(paramMap) && !paramMap.isEmpty()) {\n return paramMap.get(key);\n }\n return null;\n }\n /**\n * 获取所有参数\n *",
"score": 0.830858051776886
},
{
"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.8236851692199707
},
{
"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.8183268904685974
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " }\n /**\n * 设置RoketMq配置属性\n *\n * @param mqProperties 配置属性\n * @return AbstractGrayEventListener\n */\n public AbstractGrayEventListener setMqProperties(Properties mqProperties) {\n this.mqProperties = mqProperties;\n return this;",
"score": 0.8081084489822388
}
] | 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/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.7902418375015259
},
{
"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.7838636636734009
},
{
"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.7745608687400818
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/GrayMessageListener.java",
"retrieved_chunk": " * 通过topic后缀判断是否为灰度流量\n * @author wangshufeng\n */\n@Slf4j\npublic final class GrayMessageListener implements MessageListener {\n private MessageListener messageListener;\n public GrayMessageListener(MessageListener messageListener) {\n this.messageListener = messageListener;\n }\n @Override",
"score": 0.7496875524520874
},
{
"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.7425797581672668
}
] | 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/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.7947575449943542
},
{
"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.7922588586807251
},
{
"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.7450337409973145
},
{
"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.7405458688735962
},
{
"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.7371518611907959
}
] | java | getHeader(item.getValue()); |
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.8748031854629517
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " PythonCallbackException\n {\n try {\n evalOrExec(false, string, Object.class);\n }\n catch (ClassCastException e) {\n // Shouldn't happen\n throw new AssertionError(\"Unexpected error\", e);\n }\n }",
"score": 0.8610020875930786
},
{
"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.8587950468063354
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " }\n else {\n return myMethods[index].invoke(instance, arguments);\n }\n }\n catch (InvocationTargetException e) {\n // Throw the exception which came out of the call\n throw e.getTargetException();\n }\n catch (Throwable t) {",
"score": 0.8544368743896484
},
{
"filename": "java/src/main/java/com/deshaw/pjrmi/PJRmi.java",
"retrieved_chunk": " public boolean test(T arg1, U arg2)\n {\n try {\n // We'll try to keep the same semantics that we expect in\n // Python given various types\n final Object result = invoke(arg1, arg2);\n if (result instanceof Boolean) {\n return ((Boolean)result).booleanValue();\n }\n else if (result instanceof String) {",
"score": 0.8542613983154297
}
] | java | = StringUtil.stackTraceToString(t); |
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/nacos/ribbon/NacosRule.java",
"retrieved_chunk": " return null;\n }\n }\n /**\n * 根据当前请求是否为灰度过滤服务实例列表\n *\n * @param instances\n * @return List<Instance>\n */\n private List<Instance> getGrayFilterInstances(List<Instance> instances, Object key) {",
"score": 0.7965437173843384
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " initConsumerGray();\n } else {\n initConsumerProduction();\n }\n }\n /**\n * 初始化生产消费者实例\n */\n private void initConsumerProduction() {\n if (consumer == null) {",
"score": 0.7776331901550293
},
{
"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.7681409120559692
},
{
"filename": "src/main/java/com/easyhome/common/job/JavaGrayProcessor.java",
"retrieved_chunk": " log.info(\"当前实例是否为灰度环境:true,Job设置传递灰度标识。\");\n }\n }\n @Override\n public ProcessResult postProcess(JobContext context) {\n GrayParamHolder.clearValue();\n return null;\n }\n @Override\n public void kill(JobContext context) {",
"score": 0.7628841996192932
},
{
"filename": "src/main/java/com/easyhome/common/rocketmq/AbstractGrayEventListener.java",
"retrieved_chunk": " * 销毁生产消费实例\n */\n private void shutdownConsumerProduction() {\n if (Objects.nonNull(consumer)) {\n consumer.shutdown();\n consumer = null;\n }\n }\n /**\n * 销毁灰度消费者实例",
"score": 0.759469211101532
}
] | java | ("当前实例是否为灰度环境:{ |
/*
* Copyright 2023 edgematrix Labs Ltd.
*
* 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 pro.edgematrix.crypto;
import org.web3j.rlp.RlpType;
import pro.edgematrix.crypto.type.IRtcMsg;
import pro.edgematrix.crypto.type.RtcMsg;
import pro.edgematrix.crypto.type.RtcMsgType;
import java.util.List;
/**
* RawRtcMsg class used for signing RawRtcMsg locally.<br>
* For the specification, refer to <a href="http://www.edgematrix.pro/api/paper.pdf">yellow
* paper</a>.
*/
public class RawRtcMsg {
private final IRtcMsg transaction;
protected RawRtcMsg(final IRtcMsg transaction) {
this.transaction = transaction;
}
public static RawRtcMsg createRtcMsg(
String subject, String application, String content, String to) {
return new RawRtcMsg(
| RtcMsg.createContractTransaction(
subject, application, content, to)); |
}
public List<RlpType> asRlpValues(Sign.SignatureData signatureData) {
return transaction.asRlpValues(signatureData);
}
public String getSubject() {
return transaction.getSubject();
}
public String getApplication() {
return transaction.getApplication();
}
public String getContent() {
return transaction.getContent();
}
public String getTo() {
return transaction.getTo();
}
public RtcMsgType getType() {
return transaction.getType();
}
public IRtcMsg getTransaction() {
return transaction;
}
}
| src/main/java/pro/edgematrix/crypto/RawRtcMsg.java | EMCProtocol-dev-emc_java_sdk-82e4b0e | [
{
"filename": "src/main/java/pro/edgematrix/RtcMsg.java",
"retrieved_chunk": " private String application;\n // rtc text content.\n private String content;\n // address of rtc message to.\n // 0x0 is broadcast address\n private String to;\n public static RtcMsg createRtcMsg(\n String subject, String application, String content, String to) {\n RtcMsg rtcMsg = new RtcMsg();\n rtcMsg.application = application;",
"score": 0.887050986289978
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/RtcMsg.java",
"retrieved_chunk": " public static RtcMsg createContractTransaction(\n String subject, String application, String content, String to) {\n return new RtcMsg(subject, application, content, to);\n }\n @Override\n public RtcMsgType getType() {\n return type;\n }\n public String getSubject() {\n return subject;",
"score": 0.8747655153274536
},
{
"filename": "src/main/java/pro/edgematrix/crypto/RtcMsgEncoder.java",
"retrieved_chunk": " return encode(rawTransaction, null);\n }\n /**\n * Encode RtcMsg with chainId together\n *\n * @return encoded bytes\n */\n public static byte[] encode(RawRtcMsg rawTransaction, long chainId) {\n Sign.SignatureData signatureData =\n new Sign.SignatureData(longToBytes(chainId), new byte[]{}, new byte[]{});",
"score": 0.8581145405769348
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/RtcMsgType.java",
"retrieved_chunk": " }\n public Byte getRlpType() {\n return type;\n }\n public boolean isSubject() {\n return this.equals(RtcMsgType.SubjectMsg);\n }\n public boolean isState() {\n return this.equals(RtcMsgType.StateMsg);\n }",
"score": 0.8460479974746704
},
{
"filename": "src/main/java/pro/edgematrix/RtcMsg.java",
"retrieved_chunk": " rtcMsg.subject = subject;\n rtcMsg.to = to;\n rtcMsg.content = content;\n return rtcMsg;\n }\n public String getSubject() {\n return subject;\n }\n public void setSubject(String subject) {\n this.subject = subject;",
"score": 0.8305034637451172
}
] | java | RtcMsg.createContractTransaction(
subject, application, content, to)); |
/*
* Copyright 2023 edgematrix Labs Ltd.
*
* 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 pro.edgematrix;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.utils.Numeric;
import pro.edgematrix.common.PrecompileAddress;
import pro.edgematrix.crypto.RawRtcMsg;
import pro.edgematrix.crypto.RawTelegram;
import pro.edgematrix.crypto.RtcMsgEncoder;
import pro.edgematrix.crypto.TelegramEncoder;
import pro.edgematrix.protocol.methods.response.EdgeSendRtcMsg;
import pro.edgematrix.protocol.methods.response.EdgeSendTelegram;
import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.ExecutionException;
/**
* JSON-RPC Request service.
*/
public class EdgeService {
/**
* send a telegram to edge-matrix node
*
* @param web3j EdgeWeb3j instance
* @param chainId EMC chain id, 2 is testnet chain id
* @param nonce nonce for caller
* @param contractAddress address to
* @param credentials caller's credential
* @param data data for call, "" is empty data
* @return deserialized JSON-RPC responses
*/
public String sendTelegram(EdgeWeb3j web3j, long chainId, BigInteger nonce, String contractAddress, Credentials credentials, String data) {
if (web3j == null) return null;
BigInteger gasPrice = BigInteger.valueOf(0);
BigInteger gasLimit = BigInteger.valueOf(0);
BigInteger value = BigInteger.valueOf(0);
RawTelegram | rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, contractAddress, value, data); |
byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials);
String signData = Numeric.toHexString(signMessage);
if (!"".equals(signData)) {
try {
EdgeSendTelegram send = web3j.edgeSendRawTelegram(signData).send();
if (send.hasError()) {
throw new RuntimeException(send.getError().getMessage());
} else {
return send.getResult();
}
} catch (IOException e) {
throw new RuntimeException("send telegram exception");
}
}
return null;
}
/**
* create a rtc subject on edge-matrix net
*
* @param web3j EdgeWeb3j instance
* @param chainId EMC chain id, 2 is testnet chain id
* @param nonce nonce for caller
* @param credentials caller's credential
* @return deserialized JSON-RPC responses
*/
public String createRtcSubject(EdgeWeb3j web3j, long chainId, BigInteger nonce, Credentials credentials) {
if (web3j == null) return null;
BigInteger gasPrice = BigInteger.valueOf(0);
BigInteger gasLimit = BigInteger.valueOf(0);
BigInteger value = BigInteger.valueOf(0);
RawTelegram rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, PrecompileAddress.EDGE_RTC_SUBJECT.getAddress(), value, "");
byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials);
String signData = Numeric.toHexString(signMessage);
if (!"".equals(signData)) {
try {
EdgeSendTelegram send = web3j.edgeSendRawTelegram(signData).send();
if (send.hasError()) {
throw new RuntimeException(send.getError().getMessage());
} else {
return send.getResult();
}
} catch (IOException e) {
throw new RuntimeException("send telegram exception");
}
}
return null;
}
public String callEdgeApi(EdgeWeb3j web3j, long chainId, BigInteger nonce, Credentials credentials, String peerId, String apiHttpMethod, String apiPath, String apiData) {
if (web3j == null) return null;
BigInteger gasPrice = BigInteger.valueOf(0);
BigInteger gasLimit = BigInteger.valueOf(0);
BigInteger value = BigInteger.valueOf(0);
String data = String.format("{\"peerId\":\"%s\",\"endpoint\":\"/api\",\"Input\":{\"method\": \"%s\",\"headers\":[],\"path\":\"%s\",\"body\":%s}}",peerId,apiHttpMethod,apiPath,apiData);
RawTelegram rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, PrecompileAddress.EDGE_CALL.getAddress(), value, data);
byte[] signMessage = TelegramEncoder.signMessage(rawTransaction, chainId, credentials);
String signData = Numeric.toHexString(signMessage);
if (!"".equals(signData)) {
try {
Request<?, EdgeSendTelegram> edgeSendTelegramRequest = web3j.edgeSendRawTelegram(signData);
EdgeSendTelegram send = edgeSendTelegramRequest.send();
if (send.hasError()) {
throw new RuntimeException(send.getError().getMessage());
} else {
return send.getResult();
}
} catch (IOException e) {
throw new RuntimeException("send telegram exception");
}
}
return null;
}
/**
* send a message to rtc subject
*
* @param web3j EdgeWeb3j instance
* @param chainId EMC chain id, 2 is testnet chain id
* @param credentials caller's credential
* @param rtcMsg RtcMsg instance to be sent
* @return deserialized JSON-RPC responses
*/
public String sendRtcMsg(EdgeWeb3j web3j, long chainId, Credentials credentials, RtcMsg rtcMsg) {
if (web3j == null) return null;
RawRtcMsg rawTransaction = RawRtcMsg.createRtcMsg(rtcMsg.getSubject(), rtcMsg.getApplication(), rtcMsg.getContent(), rtcMsg.getTo());
byte[] signMessage = RtcMsgEncoder.signMessage(rawTransaction, chainId, credentials);
String signData = Numeric.toHexString(signMessage);
if (!"".equals(signData)) {
try {
EdgeSendRtcMsg send = web3j.edgeSendRawMsg(signData).send();
if (send.hasError()) {
throw new RuntimeException(send.getError().getMessage());
} else {
return send.getResult();
}
} catch (IOException e) {
throw new RuntimeException("send rtcMsg exception");
}
}
return null;
}
/**
* get next nonce for caller
*
* @param web3j EdgeWeb3j instance
* @param address caller's address - e.g. "0x0aF137aa3EcC7d10d926013ee34049AfA77382e6"
* @return number of nonce, will be used for sendTelegram
* @throws ExecutionException ExecutionException
* @throws InterruptedException InterruptedException
*/
public BigInteger getNextTelegramNonce(EdgeWeb3j web3j, String address) throws ExecutionException, InterruptedException {
if (web3j == null) return null;
EthGetTransactionCount ethGetTransactionCount = web3j.edgeGetTelegramCount(
address, DefaultBlockParameterName.LATEST).sendAsync().get();
if (ethGetTransactionCount != null) {
return ethGetTransactionCount.getTransactionCount();
}
return null;
}
/**
* get a receipt of sendTelegram call
*
* @param web3j EdgeWeb3j instance
* @param telegramHash hashString returned by a sendTelegram call, - e.g. "0x6b7c880d58fef940e7b7932b9239d2737b4a71583c4640757e234de94bb98c0b"
* @return EthGetTransactionReceipt
* @throws IOException IOException
*/
public TransactionReceipt getTelegramReceipt(EdgeWeb3j web3j, String telegramHash) throws IOException {
EthGetTransactionReceipt transactionReceipt = web3j.edgeGetTelegramReceipt(telegramHash).send();
if (transactionReceipt != null && transactionReceipt.getTransactionReceipt().isPresent()) {
return transactionReceipt.getTransactionReceipt().get();
} else {
return null;
}
}
}
| src/main/java/pro/edgematrix/EdgeService.java | EMCProtocol-dev-emc_java_sdk-82e4b0e | [
{
"filename": "src/main/java/pro/edgematrix/crypto/RawTelegram.java",
"retrieved_chunk": " BigInteger gasPrice,\n BigInteger gasLimit,\n String to,\n BigInteger value) {\n return new RawTelegram(\n LegacyTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, value));\n }\n public static RawTelegram createTransaction(\n BigInteger nonce,\n BigInteger gasPrice,",
"score": 0.8896942734718323
},
{
"filename": "src/main/java/pro/edgematrix/crypto/RawTelegram.java",
"retrieved_chunk": " BigInteger nonce,\n BigInteger gasPrice,\n BigInteger gasLimit,\n String to,\n BigInteger value,\n String data) {\n this(new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, Numeric.toHexString(data.getBytes(StandardCharsets.UTF_8))));\n }\n public static RawTelegram createContractTransaction(\n BigInteger nonce,",
"score": 0.8858188390731812
},
{
"filename": "src/main/java/pro/edgematrix/crypto/RawTelegram.java",
"retrieved_chunk": " BigInteger gasPrice,\n BigInteger gasLimit,\n BigInteger value,\n String init) {\n return new RawTelegram(\n LegacyTransaction.createContractTransaction(\n nonce, gasPrice, gasLimit, value, init));\n }\n public static RawTelegram createEtherTransaction(\n BigInteger nonce,",
"score": 0.883983314037323
},
{
"filename": "src/main/java/pro/edgematrix/crypto/type/Telegram.java",
"retrieved_chunk": " BigInteger gasPrice,\n BigInteger gasLimit,\n String to,\n BigInteger value) {\n return new LegacyTransaction(nonce, gasPrice, gasLimit, to, value, \"\");\n }\n public static LegacyTransaction createTransaction(\n BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String to, String data) {\n return createTransaction(nonce, gasPrice, gasLimit, to, BigInteger.ZERO, data);\n }",
"score": 0.8722667694091797
},
{
"filename": "src/main/java/pro/edgematrix/crypto/RawTelegram.java",
"retrieved_chunk": " BigInteger gasLimit,\n String to,\n BigInteger value,\n String data) {\n return new RawTelegram(\n LegacyTransaction.createTransaction(nonce, gasPrice, gasLimit, to, value, Numeric.toHexString(data.getBytes(StandardCharsets.UTF_8))));\n }\n public BigInteger getNonce() {\n return transaction.getNonce();\n }",
"score": 0.8695803284645081
}
] | java | rawTransaction = RawTelegram.createTransaction(nonce, gasPrice, gasLimit, contractAddress, value, data); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.